<?php
if (!defined('ISC_BASE_PATH')) {
	die();
}
require_once(ISC_BASE_PATH.'/lib/class.xml.php');
class ISC_REMOTE extends ISC_XML_PARSER
{
	public function __construct(){
		parent::__construct();
	}

	public function HandleToDo(){
		convertRequestInput();
		$what = isc_strtolower(@$_REQUEST['w']);
		switch  ($what) {
			case "countrystates": {
				$this->GetCountryStates();
				break;
			}
			case "getstates": {
				$this->GetStateList();
				break;
			}
			case "getcountries": {
				$this->GetCountryList();
				break;
			}
			case "getexchangerate": {
				$this->GetExchangeRate();
				break;
			}
			case "expresscheckoutlogin":
				$this->ExpressCheckoutLogin();
				break;
			case "expresscheckoutgetaddressfields":
				$this->GetExpressCheckoutAddressFields();
				break;
			case 'getexpresscheckoutconfirmation':
				$this->GetExpressCheckoutConfirmation();
				break;
			case "expresscheckoutloadpaymentform":
				$this->GetExpressCheckoutPaymentForm();
				break;
			case 'saveexpresscheckoutbillingaddress':
				$this->saveExpressCheckoutBillingAddress();
				break;
			case 'saveexpresscheckoutshippingaddress':
				$this->saveExpressCheckoutShippingAddress();
				break;
			case 'saveexpresscheckoutshippingprovider':
				$this->saveExpressCheckoutShippingProvider();
				break;
			case "getshippingquotes":
				$this->GetShippingQuotes();
				break;
			case 'selectgiftwrapping':
				$this->SelectGiftWrapping();
				break;
			case 'editconfigurablefieldsincart':
				$this->EditConfigurableFieldsInCart();
				break;
			case 'deleteuploadedfileincart':
				$this->DeleteUploadedFileInCart();
				break;
			case 'addproducts':
				$this->AddProductsToCart();
				break;
			case 'paymentprovideraction':
				$this->ProcessRemoteActions();
				break;
			case 'doadvancesearch':
				$this->doAdvanceSearch();
				break;
			case 'sortadvancesearch':
				$this->sortAdvanceSearch();
				break;
			case 'getvariationoptions':
				$this->GetVariationOptions();
				break;
			case "updatelanguage": {
				$this->UpdateLanguage();
				break;
			}
			case 'disabledesignmode':
				$this->DisableDesignMode();
				break;
			case 'recomendar':
				$this->Recomendar();
				break;

			case 'simularfrete':
				$this->SimularFrete();
				break;

			case 'simularparcelas':
				$this->SimularParcelas();
				break;

			case 'simularparcelas2':
				$this->SimularParcelas2();
				break;

			case 'simularparcelas3':
				$this->SimularParcelas3();
				break;

			case 'orcamento':
				$this->Orcamento();
				break;

			case 'duvida':
				$this->duvida();
				break;
			case 'getnewproducts':
           	 $this->getNewProducts($_GET['page']);
            break;
            case 'verificaremail':
            	$this->verificarEmail();
            break;

		}
	}
	private function verificarEmail(){
		$email = $GLOBALS['ISC_CLASS_DB']->Protect($_POST['email']);
		$GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
		if($GLOBALS['ISC_CLASS_CUSTOMER']->AccountWithEmailAlreadyExists($email)){
			die("1");
		}
		die("0");
	}
	
	private function ValorProduto($produto) {
		$query = "SELECT prodcalculatedprice, FROM [|PREFIX|]products WHERE productid=".$produto;
		$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
		$a = $GLOBALS['ISC_CLASS_DB']->Fetch($result);
		$GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
	    $g = $GLOBALS['ISC_CLASS_CUSTOMER']->GetCustomerGroup();
		$valor = $a['prodcalculatedprice']-(($a['prodcalculatedprice']/100)*$g['discount']);
	    return $valor;
	}
	
	public function jurosSimples($valor, $taxa, $parcelas) {
		$taxa = $taxa/100;
		$m = $valor * (1 + $taxa * $parcelas);
		$valParcela = $m/$parcelas;
		return $valParcela;
	}

	public function jurosComposto($valor, $taxa, $parcelas) {
		$taxa = $taxa/100;
		$valParcela = $valor * pow((1 + $taxa), $parcelas);
		$valParcela = $valParcela/$parcelas;
		return $valParcela;
	}

	private function EnviaDuvida($produto,$name,$email,$message){
		$produto = $GLOBALS['ISC_CLASS_DB']->Protect($produto);
		$store_name = GetConfig('StoreName');
		$url = GetConfig('ShopPath');	
		$ler = "SELECT productid,prodname FROM [|PREFIX|]products WHERE productid = '".$produto."'";
		$resultado = $GLOBALS['ISC_CLASS_DB']->Query($ler);
		$linhas = $GLOBALS['ISC_CLASS_DB']->Fetch($resultado);
		$html = 'Olá Admin,seu cliente tem duvidas sobre o item abaixo<br>
			<b>Produto: </b>'.$linhas['prodname'].'<br><b>ID: </b>#'.$linhas['productid'].'<br>
			<h2>Dados do Cliente</h2>
			<b>Nome: </b> '.$name.'<br>
			<b>Email: </b> '.$email.'<br>
			<h2>Mensagem</h2>
			<i>'.$message.'</i>
			<br>
			<br><b>'.$store_name.'</b>'
			;
		$email = GetConfig('AdminEmail');
		require_once(ISC_BASE_PATH . "/lib/email.php");
		$obj_email = GetEmailClass();
		$obj_email->Set('CharSet', GetConfig('CharacterSet'));
		$obj_email->From($email, $name);
		$obj_email->Set("Subject", 'Duvida sobre o Produto - '.$linhas['prodname']);
		$obj_email->AddBody("html", $html);
		$obj_email->AddRecipient($email, "", "h");
		$email_result = $obj_email->Send();
		if($email_result['success']) {
			$result = array("outcome" => "success",
				"message" => '<div class="alert alert-success" role="alert"><center><h4>Sua Pergunta foi enviada com sucesso!<br> Retornaremos em breve.</h4></center></div>'
			);
		}else{
			$result = array("outcome" => "fail",
				"message" => '<div class="alert alert-danger" role="alert"><center><h4>Falha no envio! Verifique o email digitado!</h4></center></div>'
			);
		}
		return $result['message'];
	}

	private function duvida(){
		$id = $GLOBALS['ISC_CLASS_DB']->Protect($_GET['id']);
		$ler = "SELECT productid,prodname FROM [|PREFIX|]products WHERE productid = '".$id."'";
		$resultado = $GLOBALS['ISC_CLASS_DB']->Query($ler);
		$linhas = $GLOBALS['ISC_CLASS_DB']->Fetch($resultado);
		$GLOBALS['Produton'] = $linhas['prodname'];
		$GLOBALS['ProdutoIdn'] = $linhas['productid'];
		if(empty($_GET['acao'])) {
			if(GetConfig('Attrecaptchav3')){
				$GLOBALS['SiteKey'] = GetConfig('SiteKey');
				$select = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('DuvidaRecaptcha');
			}else{
				$select = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('Duvida');
			}
			echo $GLOBALS['ISC_CLASS_TEMPLATE']->ParseSnippets($select, true);
		}else{
			if(GetConfig('Attrecaptchav3')){
				if ($_SERVER["REQUEST_METHOD"] == "POST") {
					$url = "https://www.google.com/recaptcha/api/siteverify";
					$data = [
					    'secret' => GetConfig('SecretKey'),
					    'response' => $_POST['token'],
					    'remoteip' => $_SERVER['REMOTE_ADDR']
					];
					$options = array(
					    'http' => array(
					      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
					      'method'  => 'POST',
					      'content' => http_build_query($data)
					    )
				    );
				    $context  = stream_context_create($options);
				    $response = file_get_contents($url, false, $context);
				    $res = json_decode($response, true);
				    if ($res['success'] == true && $res['score'] >= 0.5) {
				    	$name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST['nome'])));
	    				$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
	    				$message = trim($_POST['Message']);
	    				if(!empty($name) and filter_var($email, FILTER_VALIDATE_EMAIL) and !empty($message)){
	    					$dados = $this->EnviaDuvida($GLOBALS['ProdutoIdn'],$name,$email,$message);
	    					echo '<h1>'.$dados.'</h1>';
	    				}else{
	    					echo '<div class="alert alert-danger" role="alert">E-mail incorreto!</div>';
	    				}
				    }else{
				    	echo '<div class="alert alert-danger" role="alert">Erro! O token de segurança expirou ou você é um Robô.</div>';
				    }
				} 
			}else{
				$name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST['nome'])));
	    		$email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
	    		$message = trim($_POST['Message']);
	    		if(!empty($name) and filter_var($email, FILTER_VALIDATE_EMAIL) and !empty($message)){
	    			$dados = $this->EnviaDuvida($GLOBALS['ProdutoIdn'],$name,$email,$message);
	    			echo '<h1>'.$dados.'</h1>';
	    		}else{
	    			echo '<div class="alert alert-danger" role="alert">E-mail incorreto!</div>';
	    		}
			}
		}
	}
	private function EnviaOrcamento($produto,$name,$email,$mess,$emp,$tel,$cid,$qtd){
		$produto = $GLOBALS['ISC_CLASS_DB']->Protect($produto);
		$store_name = GetConfig('StoreName');
		$url = GetConfig('ShopPath');	
		$ler = "SELECT productid,prodname FROM [|PREFIX|]products WHERE productid = '".$produto."'";
		$resultado = $GLOBALS['ISC_CLASS_DB']->Query($ler);
		$linhas = $GLOBALS['ISC_CLASS_DB']->Fetch($resultado);
		$ord = rand(1111,99999999);
		$html = 'Olá Admin,um cliente solicitou um orçamento do item abaixo<br>
			<b>Produto: </b>'.$linhas['prodname'].'<br><b>ID: </b>#'.$linhas['productid'].'<br>
			<b>Quantidade desejada: </b> '.$qtd.'<br>
			<br>
			<h2>Dados do Cliente</h2>
			<b>Nome: </b> '.$name.'<br>
			<b>Email: </b> '.$email.'<br>
			<b>Empresa: </b> '.$emp.'<br>
			<b>Telefone: </b> '.$tel.'<br>
			<b>Cidade: </b> '.$cid.'<br>
			<h2>Mensagem</h2>
			<i>'.$mess.'</i>
			<br>
			<b>'.$store_name.'</b>';
		$email = GetConfig('AdminEmail');
		require_once(ISC_BASE_PATH . "/lib/email.php");
		$obj_email = GetEmailClass();
		$obj_email->Set('CharSet', GetConfig('CharacterSet'));
		$obj_email->From($email, $name);
		$obj_email->Set("Subject", 'Pedido de Orcamento ID: #ORC'.$ord);
		$obj_email->AddBody("html", $html);
		$obj_email->AddRecipient($email, "", "h");
		$email_result = $obj_email->Send();
		if($email_result['success']) {
			$result = array("outcome" => "success","message" => '<div class="alert alert-success" role="alert"><center><h4>Orçamento enviado com sucesso!</br>Retornaremos em breve.</h4></center></div>');
		} else {
			$result = array("outcome" => "fail","message" => '<div class="alert alert-danger" role="alert"><center>Falha no envio do orçamento!</div>');
		}
		return $result['message'];
	}
	private function Orcamento(){
		$id = $GLOBALS['ISC_CLASS_DB']->Protect($_GET['id']);
		$ler = "SELECT productid,prodname FROM [|PREFIX|]products WHERE productid = '".$id."'";
		$resultado = $GLOBALS['ISC_CLASS_DB']->Query($ler);
		$linhas = $GLOBALS['ISC_CLASS_DB']->Fetch($resultado);
		$GLOBALS['Produton'] = $linhas['prodname'];
		$GLOBALS['ProdutoIdn'] = $linhas['productid'];
		
		if(empty($_GET['acao'])) {
			if(GetConfig('Attrecaptchav3')){
				$GLOBALS['SiteKey'] = GetConfig('SiteKey');
				$select = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('OrcamentoRecaptcha');
			}else{
				$select = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('Orcamento');
			}
			echo $GLOBALS['ISC_CLASS_TEMPLATE']->ParseSnippets($select, true);
		}else{
			if(GetConfig('Attrecaptchav3')){
				if ($_SERVER["REQUEST_METHOD"] == "POST") {
					$url = "https://www.google.com/recaptcha/api/siteverify";
					$data = [
					    'secret' => GetConfig('SecretKey'),
					    'response' => $_POST['token'],
					    'remoteip' => $_SERVER['REMOTE_ADDR']
					];
					$options = array(
					    'http' => array(
					      'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
					      'method'  => 'POST',
					      'content' => http_build_query($data)
					    )
				    );
				    $context  = stream_context_create($options);
				    $response = file_get_contents($url, false, $context);
				    $res = json_decode($response, true);
				    if ($res['success'] == true && $res['score'] >= 0.5) {
				    	$name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST['nomede'])));
	    				$email = filter_var(trim($_POST['emailde']), FILTER_SANITIZE_EMAIL);
	    				$mess = trim($_POST['obs']);
	    				$emp = trim($_POST['emp']);
	    				$tel = trim($_POST['telefone']);
	    				$cid = trim($_POST['cid']);
	    				$qtd = trim($_POST['qtd']);
	    				if(!empty($name) and filter_var($email, FILTER_VALIDATE_EMAIL) and !empty($mess)and !empty($emp)and !empty($tel)and !empty($cid)and !empty($qtd)){
	    					$dados = $this->EnviaOrcamento($GLOBALS['ProdutoIdn'],$name,$email,$mess,$emp,$tel,$cid,$qtd);
	    					echo '<h1>'.$dados.'</h1>';
	    				}else{
	    					echo '<div class="alert alert-danger" role="alert">E-mail incorreto!</div>';
	    				}
				    }else{
				    	echo '<div class="alert alert-danger" role="alert">Erro! O token de segurança expirou ou você é um Robô.</div>';
				    }
				} 
			}else{
				$name = str_replace(array("\r","\n"),array(" "," ") , strip_tags(trim($_POST['nomede'])));
				$email = filter_var(trim($_POST['emailde']), FILTER_SANITIZE_EMAIL);
				$mess = trim($_POST['obs']);
				$emp = trim($_POST['emp']);
				$tel = trim($_POST['telefone']);
				$cid = trim($_POST['cid']);
				$qtd = trim($_POST['qtd']);
				if(!empty($name) and filter_var($email, FILTER_VALIDATE_EMAIL) and !empty($mess)and !empty($emp)and !empty($tel)and !empty($cid)and !empty($qtd)){
					$dados = $this->EnviaOrcamento($GLOBALS['ProdutoIdn'],$name,$email,$mess,$emp,$tel,$cid,$qtd);
					echo '<h1>'.$dados.'</h1>';
				}else{
					echo '<div class="alert alert-danger" role="alert">E-mail incorreto!</div>';
				}
			}
		}
	}
	public function SimularParcelas2() {
		if (!empty(GetModuleVariable('addon_parcelas','ativodesconto'))){
			if(GetModuleVariable('addon_parcelas','descontohome')>0){
				$porcedesconto = GetModuleVariable('addon_parcelas','descontohome');
				$valordoproduto = $_GET['valor'];
				$valordoproduto = $valordoproduto-(($valordoproduto/100)*$porcedesconto);
				$dep = CurrencyConvertFormatPrice($valordoproduto, 1, 0);
			}else{
				$valordoproduto = ValorProduto($produto);
				$dep = '';
			}
		}
		echo $dep;
	}
	public function SimularParcelas3() {
		$ler = "select * from [|PREFIX|]module_vars where modulename = 'addon_parcelas' and variablename = 'rodape1' order by variablename asc";
		$resultado = $GLOBALS['ISC_CLASS_DB']->Query($ler);
		$parcelador = "";
		$s = $GLOBALS['ISC_CLASS_DB']->Fetch($resultado);
		if(empty($s['variableval'])){
			$s['variableval'] = 'pagseguro';
		}

		switch($s['variableval']) {
			case 'pagseguro':
			$ativo = GetModuleVariable('checkout_psapi','is_setup');
			$juross = GetModuleVariable('checkout_psapi','acrecimo');
			$div = GetModuleVariable('checkout_psapi','dividir');
			$semjuros = GetModuleVariable('checkout_psapi','sem');
			$parcelmin = GetModuleVariable('checkout_psapi','minimo');
			if(!empty($ativo)) {
			$valordoproduto = $_GET['valor'];
			$valor = $valordoproduto;
			if($juross<=0 OR empty($juross)){$valor = $valor;} else {$valor = (($valor/100)*$juross)+$valor;}
			$msg = '';
			$msg1 = '';
			$splitss = (int) ($valor/$parcelmin);
			if($splitss<=$div){
			$div = $splitss;
			}
			if($valor<=$parcelmin){
				$div = 1;
			}
			for($j=1; $j<=$div;$j++) {
			$fator = array('0','0.52255','0.35347','0.26898','0.21830','0.18453','0.16044','0.14240','0.12838','0.11717','0.10802','0.10040');
			$result_array = $fator[$j-1];
			$parcelas = $valor*$result_array;
			$parcelas = number_format($parcelas, 2, '.', '');
			@$valors = number_format($valor, 2, '.', '');
			$op = $semjuros;
			if($div==$j){
			if($j==1 OR $op>=$j) {
			$msg .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i> ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</span><br>
			sem juros no cartão";
			}else{$msg1 .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i>  ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($parcelas, 1, 0)." </span><br> no cartão";
			}}}$parcelador .= $msg.''.$msg1.'';}
			break;

			case 'moip':
			$ativo = GetModuleVariable('checkout_moip','is_setup');
			$juross = GetModuleVariable('checkout_moip','acrecimo');
			$taxa = 0.0199;
			if(!empty($ativo)) {
			$valordoproduto = $_GET['valor'];
			$valor = $valordoproduto;
			if($juross<=0 OR empty($juross)){
			$valor = $valor;
			}else {$valor = (($valor/100)*$juross)+$valor;}
			$msg = '';
			$msg1 = '';
			$splitss = (int) ($valor/5);
			if($splitss<=12){
			$div = $splitss;
			}else{
			$div = GetModuleVariable('checkout_moip','dividir');}
			if($valor<=5){
			$div = 1;
			}
			for($j=1; $j<=$div;$j++) {
			if($div==$j){
			$cf = pow((1 + $taxa), $j);
			$cf = (1 / $cf);
			$cf = (1 - $cf);
			$cf = ($taxa / $cf);
			$parcelas = ($valor*$cf);
			$parcelas = number_format($parcelas, 2, '.', '');
			$valors = number_format($valor, 2, '.', '');
			$op = GetModuleVariable('checkout_moip','semjuros');
			if($j==1 OR $op>=$j) {
			$msg .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i> ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</span><br>
			sem juros no cartão";
			}else{$msg1 .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i>  ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($parcelas, 1, 0)." </span><br> no cartão";}}}$parcelador .= $msg.''.$msg1.'</br>';}
			break;

			case 'picpay':
			$ativo = GetModuleVariable('checkout_picpay','is_setup');
			$juross = '0';
			$taxa = 0.0349;
			if(!empty($ativo)) {
			//verifica o juros
			$valordoproduto = $_GET['valor'];
			$valor = $valordoproduto;
			if($juross<=0 OR empty($juross)){
			$valor = $valor;
			} else {
			$valor = (($valor/100)*$juross)+$valor;
			}

			$msg = '';
			$msg1 = '';
			$splitss = (int) ($valor/5);
			if($splitss<=12){
			$div = $splitss;
			}else{
			$div = 12;
			}
			if($valor<=5){
			$div = 1;
			}
			//echo $div."<br>";
			for($j=1; $j<=$div;$j++) {
			$cf = pow((1 + $taxa), $j);
			$cf = (1 / $cf);
			$cf = (1 - $cf);
			$cf = ($taxa / $cf);
			//echo $cf."<br>";
			$parcelas = ($valor*$cf);
			//echo $parcela."<br>";
			$parcelas = number_format($parcelas, 2, '.', '');
			//echo $parcela."<br>";
			$valors = number_format($valor, 2, '.', '');
			$op = 1;

			if($div==$j){
			if($j==1 OR $op>=$j) {
			$msg .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i> ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</span><br>
			sem juros no cartão";
			}else{
			$msg1 .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i>  ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($parcelas, 1, 0)." </span><br> no cartão";
			}
			}
			}
			//inicio do codigo do parcelamento
			$parcelador .= $msg.''.$msg1.'</br>';
			//fim do codigo de parcelamento
			}
			break;

			case 'mercadopago':
			$ativo = GetModuleVariable('checkout_mplight','is_setup');
			$juross = GetModuleVariable('checkout_mplight','acrescimo');
			$taxa = 0.0199;
			if(!empty($ativo)) {
			//verifica o juros
			$valordoproduto = $_GET['valor'];
			$valor = $valordoproduto;
			if($juross<=0 OR empty($juross)){
			$valor = $valor;
			} else {
			$valor = (($valor/100)*$juross)+$valor;
			}

			$msg = '';
			$msg1 = '';
			$splitss = (int) ($valor/5);
			if($splitss<=12){
			$div = $splitss;
			}else{
			$div = GetModuleVariable('checkout_mplight','dividir');
			}
			if($valor<=5){
			$div = 1;
			}
			//echo $div."<br>";
			for($j=1; $j<=$div;$j++) {
			$cf = pow((1 + $taxa), $j);
			$cf = (1 / $cf);
			$cf = (1 - $cf);
			$cf = ($taxa / $cf);
			//echo $cf."<br>";
			$parcelas = ($valor*$cf);
			//echo $parcela."<br>";
			$parcelas = number_format($parcelas, 2, '.', '');
			//echo $parcela."<br>";
			$valors = number_format($valor, 2, '.', '');
			$op = GetModuleVariable('checkout_mplight','semjuros');

			if($div==$j){
			if($j==1 OR $op>=$j) {
			$msg .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i> ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</span><br>
			sem juros no cartão";
			}else{
			$msg1 .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i>  ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($parcelas, 1, 0)." </span><br> no cartão";
			}
			}
			}
			//inicio do codigo do parcelamento
			$parcelador .= $msg.''.$msg1.'</br>';
			//fim do codigo de parcelamento
			}
			break;

			case 'bcash':
			$ativo = GetModuleVariable('checkout_bcash','is_setup');
			$juross = GetModuleVariable('checkout_bcash','acrecimo');
			$taxa = 0.0289;
			if(!empty($ativo)) {
			//verifica o juros
			$valordoproduto = $_GET['valor'];
			$valor = $valordoproduto;
			if($juross<=0 OR empty($juross)){
			$valor = $valor;
			} else {
			$valor = (($valor/100)*$juross)+$valor;
			}

			$msg = '';
			$msg1 = '';
			$splitss = (int) ($valor/5);
			if($splitss<=12){
			$div = $splitss;
			}else{
			$div = GetModuleVariable('checkout_bcash','dividir');
			}
			if($valor<=5){
			$div = 1;
			}
			//echo $div."<br>";
			for($j=1; $j<=$div;$j++) {
			$cf = pow((1 + $taxa), $j);
			$cf = (1 / $cf);
			$cf = (1 - $cf);
			$cf = ($taxa / $cf);
			//echo $cf."<br>";
			$parcelas = ($valor*$cf);
			//echo $parcela."<br>";
			$parcelas = number_format($parcelas, 2, '.', '');
			//echo $parcela."<br>";
			$valors = number_format($valor, 2, '.', '');
			$op = GetModuleVariable('checkout_bcash','semjuros');

			if($div==$j){
			if($j==1 OR $op>=$j) {
			$msg .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i> ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</span><br>
			sem juros no cartão";
			}else{
			$msg1 .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i>  ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($parcelas, 1, 0)." </span><br> no cartão";
			}
			}
			}
			//inicio do codigo do parcelamento
			$parcelador .= $msg.''.$msg1.'</br>';
			//fim do codigo de parcelamento
			}
			break;

			case 'cielo':
			$ativo = GetModuleVariable('checkout_cielointegrado','is_setup');
			$div = GetModuleVariable('checkout_cielointegrado','dividir');
			$juross = '0';
			$taxa = 1.69;
			$jt = 0;
			$pm = GetModuleVariable('checkout_cielointegrado','min');

			if(!empty($ativo)) {
			//verifica o juros
			$valordoproduto = $_GET['valor'];
			$valor = $valordoproduto;
			if($juross<=0 OR empty($juross)){
			$valor = $valor;
			} else {
			$valor = (($valor/100)*$juross)+$valor;
			}

			$msg = '';
			$msg1 = '';
			$splitss = (int) ($valor/$pm);
			if($splitss<=$div){
			$div = $splitss;
			}else{
			$div = $div;
			}
			if($valor<=$pm){
			$div = 1;
			}

			for($j=1; $j<=$div;$j++) {
			if($div==$j){
			if($jt==0)
			$parcelas = jurosSimples($valor, $taxa, $j);
			else
			$parcelas = jurosComposto($valor, $taxa, $j);

			$parcelas = number_format($parcelas, 2, '.', '');
			$valors = number_format($valor, 2, '.', '');

			$op = GetModuleVariable('checkout_cielointegrado','dividir');
			if($op>=$j) {
			$msg .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i> ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</span><br>
			sem juros no cartão";
			}else{$msg1 .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i>  ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($parcelas, 1, 0)." </span><br> no cartão";

			}
			}
			}
			//inicio do codigo do parcelamento
			$parcelador .= $msg.''.$msg1.'</br>';
			//fim do codigo de parcelamento
			}
			break;

			case 'paypal':
			$ativo = GetModuleVariable('checkout_paypal','is_setup');
			$juross = 0;
			$pm = GetModuleVariable('checkout_paypal','minimo');
			$div2 = GetModuleVariable('checkout_paypal','dividir');

			if(!empty($ativo)) {
			//verifica o juros
			$valordoproduto = $_GET['valor'];
			$valor = $valordoproduto;
			if($juross<=0 OR empty($juross)){
			$valor = $valor;
			} else {
			$valor = (($valor/100)*$juross)+$valor;
			}

			$msg = '';
			$msg1 = '';
			$splitss = (int) ($valor/$pm);
			if($splitss<=$div2){
			$div = $splitss;
			}else{
			$div = GetModuleVariable('checkout_paypal','dividir');
			}

			//echo $div."<br>";
			for($j=1; $j<=$div;$j++) {

			$fator = array('0','0.51875','0.35007','0.26575','0.21518','0.18148','0.15743','0.13941','0.12540','0.11420','0.10505','0.09743');
			$result_array = $fator[$j-1];
			$parcelas = $valor*$result_array;

			//echo $parcela."<br>";
			$parcelas = number_format($parcelas, 2, '.', '');
			//echo $parcela."<br>";
			$valors = number_format($valor, 2, '.', '');
			$op = GetModuleVariable('checkout_paypal','dividir');
			if($div==$j){
			if($j==1 OR $op>=$j) {
			$msg .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i> ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</span><br>
			sem juros no cartão";
			}else{$msg1 .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i>  ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($parcelas, 1, 0)." </span><br> no cartão";

			}
			}
			}
			//inicio do codigo do parcelamento
			$parcelador .= $msg.''.$msg1.'</br>';
			//fim do codigo de parcelamento
			}
			break;

			case 'shopline':
			$ativo = GetModuleVariable('checkout_itaushopline','is_setup');
			$boleto = '';
			$facil = '';
			$finan = '';
			$trans = '';
			if(!empty($ativo)) {
			//verifica o desconto
			$valordoproduto = $_GET['valor'];
			$msg = "";
			$preco = CurrencyConvertFormatPrice($valordoproduto, 1, 0);
			$msg .= "<b>1x</b> de <b> ".$preco."</b> no <b>itau shopline</b>";
			//inicio do codigo do parcelamento
			$parcelador .= $msg.'</fbr>';
			//fim do codigo de parcelamento
			}
			break;

			case 'redecard':
			$ativo = GetModuleVariable('checkout_redecard','is_setup');
			$div = GetModuleVariable('checkout_redecard','div');
			$juross = '0';
			$taxa = GetModuleVariable('checkout_redecard','juros');
			$jt = 1;
			$pm = GetModuleVariable('checkout_redecard','parcelamin');
			if(!empty($ativo)) {
			//verifica o juros
			$valordoproduto = $_GET['valor'];
			$valor = $valordoproduto;
			if($juross<=0 OR empty($juross)){
			$valor = $valor;
			}else{$valor = (($valor/100)*$juross)+$valor;}
			$msg = '';
			$msg1 = '';
			$splitss = (int) ($valor/$pm);
			if($splitss<=$div){
			$div = $splitss;
			}else{$div = $div;}
			if($valor<=$pm){$div = 1;}
			for($j=1; $j<=$div;$j++) {
			if($div==$j){
			if($jt==0)
			$parcelas = jurosSimples($valor, $taxa, $j);
			else
			$parcelas = jurosComposto($valor, $taxa, $j);
			$parcelas = number_format($parcelas, 2, '.', '');
			$valors = number_format($valor, 2, '.', '');
			$op = GetModuleVariable('checkout_redecard','jurosde');
			if($op>=$j) {
			$msg .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i> ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</span><br>
			sem juros no cartão";
			}else{$msg1 .="<span class=LinhaPreco><span class=BlocoMenor><i class='fa fa-credit-card'></i>  ".$j."x de</span> <span class=cartao>".CurrencyConvertFormatPrice($parcelas, 1, 0)." </span><br> no cartão";}}}$parcelador .= $msg.''.$msg1.'</br>';}
			break;
		}
		//echo '<center> '.$dep.' '.$parcelador.'</center>';
		echo '<center> '.$parcelador.'</center>';
	}
	public function SimularParcelas() {
		$ler = "SELECT variableval FROM [|PREFIX|]module_vars WHERE modulename = 'addon_parcelas' AND variablename = 'parcelaproducts' ORDER BY variableval ASC";
		$resultado = $GLOBALS['ISC_CLASS_DB']->Query($ler);
		$i = 1;
		$li= '';
		$fade= '';
		$GLOBALS['Formas'] = "";
		$GLOBALS['Parcelas'] = "";
		while ($s = $GLOBALS['ISC_CLASS_DB']->Fetch($resultado)) {
			switch($s['variableval']) {
			case 'a':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_deposito','is_setup');
				$desc = GetModuleVariable('checkout_deposito','desconto');
				if(!empty($ativo)) {
					$pro = $_GET['valor'];
					if($desc<=0){
						$preco = CurrencyConvertFormatPrice($pro, 1, 0);
						$msg = "<b> ".$preco."</b> a vista.";
					} else {
						$valven = ($pro/100)*$desc;
						$preco = CurrencyConvertFormatPrice($pro-$valven, 1, 0);
						$msg = "<b> ".$preco."</b> a vista com <b>".$desc."%</b> de desconto via depósito.";
					}
					$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/bank.png" /></a></li>';
					$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msg.'</div>';
				}
			break;

			case 'ca':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_naloja','is_setup');
				$desc = GetModuleVariable('checkout_naloja','desconto');
				if(!empty($ativo)) {
					$pro = $_GET['valor'];
					if($desc<=0){
						$preco = CurrencyConvertFormatPrice($pro, 1, 0);
						$msg = "<b> ".$preco."</b> a vista.";
					} else {
						$valven = ($pro/100)*$desc;
						$preco = CurrencyConvertFormatPrice($pro-$valven, 1, 0);
						$msg = "<b> ".$preco."</b> a vista com <b>".$desc."%</b> de desconto.";
					}
					$msgs ="<b>Pagamento ao retirar na loja!</b><br>";
					$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/naloja.png" /></a></li>';
					$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msgs.''.$msg.'</div>';
				}
			break;

			case 'c':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_cheque','is_setup');
				$desc = GetModuleVariable('checkout_cheque','desconto');
				if(!empty($ativo)) { 
					$pro = $_GET['valor'];
					if($desc<=0){
						$preco = CurrencyConvertFormatPrice($pro, 1, 0);
						$msg = "<b> ".$preco."</b> a vista.";
					} else {
						$valven = ($pro/100)*$desc;
						$preco = CurrencyConvertFormatPrice($pro-$valven, 1, 0);
						$msg = "<b> ".$preco."</b> a vista com <b>".$desc."%</b> de desconto no cheque.";
					}					
					$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/cheque.png" /></a></li>';
					$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msg.'</div>';
				}
			break;

			case 'b':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$desc = GetModuleVariable('addon_parcelas','descontohome');
				$pro = $_GET['valor'];
				if($desc<=0){
					$preco = CurrencyConvertFormatPrice($pro, 1, 0);
					$msg = "<b> ".$preco."</b> a vista no boleto bancário.";
				} else {
					$valven = ($pro/100)*$desc;
					$preco = CurrencyConvertFormatPrice($pro-$valven, 1, 0);
					$msg = "<b> ".$preco."</b> à vista com <b>".$desc."%</b> de desconto no boleto bancário.";
				}
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/boleto.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msg.'</div>';
			break;

			case 'p':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$desc = GetModuleVariable('checkout_pix','desconto');
				$pro = $_GET['valor'];
				if($desc<=0){
					$preco = CurrencyConvertFormatPrice($pro, 1, 0);
					$msg = "<b> ".$preco."</b> a vista no Pix.";
				} else {
					$valven = ($pro/100)*$desc;
					$preco = CurrencyConvertFormatPrice($pro-$valven, 1, 0);
					$msg = "<b> ".$preco."</b> à vista com <b>".$desc."%</b> de desconto no pix.";
				}
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/pix.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msg.'</div>';
			break;

			case 'pagseguro':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_psapi','is_setup');
				if(!empty($ativo)) {
					$juross = GetModuleVariable('checkout_psapi','acrecimo');
					$div = GetModuleVariable('checkout_psapi','dividir');
					$semjuros = GetModuleVariable('checkout_psapi','sem');
					$parcelmin = GetModuleVariable('checkout_psapi','minimo');
				}else{
					$juross = 	'0';
					$div = '12';
					$semjuros = '1';
					$parcelmin = '5';
				}
				$pro = $_GET['valor'];
				$valor = $pro;
				if($juross<=0 OR empty($juross)){
					$valor = $valor;
				} else {
					$valor = (($valor/100)*$juross)+$valor;
				}

				$msg = '';
				$msg1 = '';
				$splitss = (int) ($valor/$parcelmin);
				if($splitss<=$div){
					$div = $splitss;
				}
				for($j=1; $j<=$div;$j++) {
					$splitss = $j;
					if($splitss<=12){
						if($splitss==0 OR $splitss==1 OR $splitss==2){
							$juros = 1;
							$divs = 1;
						}
						if($splitss==2){
							$juros = 0.52255;
							$divs = 2;
						}
						if($splitss==3){
							$juros = 0.35347;
							$divs = 3;
						}
						if($splitss==4){
							$juros = 0.26898;
							$divs = 4;
						}
						if($splitss==5){
							$juros = 0.21830;
							$divs = 5;
						}
						if($splitss==6){
							$juros = 0.18453;
							$divs = 6;
						}
						if($splitss==7){
							$juros = 0.16044;
							$divs = 7;
						}
						if($splitss==8){
							$juros = 0.14240;
							$divs = 8;
						}
						if($splitss==9){
							$juros = 0.12838;
							$divs = 9;
						}
						if($splitss==10){
							$juros = 0.11717;
							$divs = 10;
						}
						if($splitss==11){
							$juros = 0.10802;
							$divs = 11;
						}
						if($splitss==12){
							$juros = 0.10040;
							$divs = 12;
						}
					}else{
						$juros = 0.10040;
						$divs = 12;
					}
					@$valors = number_format($valor, 2, '.', '');
					$op = $semjuros;
					$msgs ="<b>Parcelamento via Pagseguro</b><br>";
					if($j==1 OR $op>=$j) {
						$msg .="<b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</b> sem juros.<br>";
					}else{
						$msg1 .="<b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($valors*$juros, 1, 0)."</b> com juros.<br>";
					}					
				}
				$msgs ="<b>Parcelamento via Pagseguro</b><br>";
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/pg.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msgs.''.$msg.''.$msg1.'</div>';
				//}
			break;

			case 'cielo':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_cielointegrado','is_setup');
				$div = GetModuleVariable('checkout_cielointegrado','dividir');
				$juross = '0';
				$taxa = 1.69;
				$jt = 0;
				$pm = GetModuleVariable('checkout_cielointegrado','min');
				if(!empty($ativo)) {
				//verifica o juros
				$pro = $_GET['valor'];
				$valor = $pro;
				if($juross<=0 OR empty($juross)){
				$valor = $valor;
				} else {
				$valor = (($valor/100)*$juross)+$valor;
				}
				$msg = '';
				$msg1 = '';
				$splitss = (int) ($valor/$pm);
				if($splitss<=$div){
				$div = $splitss;
				}else{
				$div = $div;
				}
				for($j=1; $j<=$div;$j++) {

				if($jt==0)
				$parcelas = $this->jurosSimples($valor, $taxa, $j);
				else
				$parcelas = $this->jurosComposto($valor, $taxa, $j);

				$parcelas = number_format($parcelas, 2, '.', '');
				$valors = number_format($valor, 2, '.', '');

				$op = GetModuleVariable('checkout_cielointegrado','dividir');
				$msgs ="<b>Parcelamento via Cielo</b><br>";
				if($op>=$j) {
				$msg .="<font size='2'><b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</b><b>sem juros</b>.</font><br>";
				}else{
				$msg1 .="<font size='2'><b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($parcelas, 1, 0)."</b><b>com juros</b>.</font><br>";
				}

				}
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/cartao.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msgs.''.$msg.''.$msg1.'</div>';
			}
			break;

			case 'bcash':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_bcash','is_setup');
				$juross = GetModuleVariable('checkout_bcash','acrecimo');
				$pm = 5.00;
				$taxa = 0.0289;
				if(!empty($ativo)) {
				//verifica o juros
				$pro = $_GET['valor'];
				$valor = $pro;
				if($juross<=0 OR empty($juross)){
				$valor = $valor;
				} else {
				$valor = (($valor/100)*$juross)+$valor;
				}

				$msg = '';
				$msg1 = '';
				$splitss = (int) ($valor/$pm);
				if($splitss<=12){
				$div = $splitss;
				}else{
				$div = GetModuleVariable('checkout_bcash','dividir');
				}
				//echo $div."<br>";
				for($j=1; $j<=$div;$j++) {
				$cf = pow((1 + $taxa), $j);
				$cf = (1 / $cf);
				$cf = (1 - $cf);
				$cf = ($taxa / $cf);
				//echo $cf."<br>";
				$parcelas = ($valor*$cf);
				//echo $parcela."<br>";
				$parcelas = number_format($parcelas, 2, '.', '');
				//echo $parcela."<br>";
				$valors = number_format($valor, 2, '.', '');
				$op = GetModuleVariable('checkout_bcash','semjuros');
				$msgs ="<b>Parcelamento via Bcash</b><br>";
				if($j==1 OR $op>=$j) {
				$msg .="<b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</b> sem juros.<br>";
				}else{
				$msg1 .="<b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($parcelas, 1, 0)."</b> com juros.<br>";
				}

				}
				//inicio do codigo do parcelamento
				$msgs ="<b>Parcelamento via Bcash</b><br>";
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/cartao.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msgs.''.$msg.''.$msg1.'</div>';
			}
			break;

			case 'moip':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_moip','is_setup');
				$juross = GetModuleVariable('checkout_moip','acrecimo');
				$pm = GetModuleVariable('checkout_moip','minimo');
				$taxa = 0.0199;
				if(!empty($ativo)) {
				//verifica o juros
				$pro = $_GET['valor'];
				$valor = $pro;
				if($juross<=0 OR empty($juross)){
				$valor = $valor;
				} else {
				$valor = (($valor/100)*$juross)+$valor;
				}

				$msg = '';
				$msg1 = '';
				$splitss = (int) ($valor/$pm);
				if($splitss<=12){
				$div = $splitss;
				}else{
				$div = 12;
				}
				//echo $div."<br>";
				for($j=1; $j<=$div;$j++) {
				$cf = pow((1 + $taxa), $j);
				$cf = (1 / $cf);
				$cf = (1 - $cf);
				$cf = ($taxa / $cf);
				//echo $cf."<br>";
				$parcelas = ($valor*$cf);
				//echo $parcela."<br>";
				$parcelas = number_format($parcelas, 2, '.', '');
				//echo $parcela."<br>";
				$valors = number_format($valor, 2, '.', '');
				$op = GetModuleVariable('checkout_checkout_moip','minimo');
				$msgs ="<b>Parcelamento via Moip</b><br>";
				if($j==1 OR $op>=$j) {
				$msg .="<b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</b> sem juros.<br>";
				}else{
				$msg1 .="<b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($parcelas, 1, 0)."</b> com juros.<br>";
				}

				}
				//inicio do codigo do parcelamento
				$msgs ="<b>Parcelamento via Moip</b><br>";
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/cartao.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msgs.''.$msg.''.$msg1.'</div>';
			}
			break;

			case 'picpay':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_picpay','is_setup');
				$juross = '0';
				$taxa = 0.0349;
				if(!empty($ativo)) {
				$pro = $_GET['valor'];
				$valor = $pro;
				if($juross<=0 OR empty($juross)){
				$valor = $valor;
				} else {
				$valor = (($valor/100)*$juross)+$valor;
				}

				$msg = '';
				$msg1 = '';
				$splitss = (int) ($valor/5);
				if($splitss<=12){
				$div = $splitss;
				}else{
				$div = 12;
				}
				//echo $div."<br>";
				for($j=1; $j<=$div;$j++) {
				$cf = pow((1 + $taxa), $j);
				$cf = (1 / $cf);
				$cf = (1 - $cf);
				$cf = ($taxa / $cf);
				//echo $cf."<br>";
				$parcelas = ($valor*$cf);
				//echo $parcela."<br>";
				$parcelas = number_format($parcelas, 2, '.', '');
				//echo $parcela."<br>";
				$valors = number_format($valor, 2, '.', '');
				$op = 1;//sem juros
				$msgs ="<b>Parcelamento via PicPay</b><br>";
				if($j==1 OR $op>=$j) {
				$msg .="<b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</b> sem juros.<br>";
				}else{
				$msg1 .="<b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($parcelas, 1, 0)."</b> com juros.<br>";
				}

				}
				//inicio do codigo do parcelamento
				$msgs ="<b>Parcelamento via PicPay</b><br>";
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/picpay.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msgs.''.$msg.''.$msg1.'</div>';
			}
			break;

			case 'mercadopago':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_mplight','is_setup');
				$juross = GetModuleVariable('checkout_mplight','acrescimo');
				$pm = 5.00;
				$taxa = 0.0199;
				if(!empty($ativo)) {
				$pro = $_GET['valor'];
				$valor = $pro;
				if($juross<=0 OR empty($juross)){
				$valor = $valor;
				} else {
				$valor = (($valor/100)*$juross)+$valor;
				}

				$msg = '';
				$msg1 = '';
				$splitss = (int) ($valor/$pm);
				if($splitss<=12){
				$div = $splitss;
				}else{
				$div = GetModuleVariable('checkout_mplight','dividir');
				}
				for($j=1; $j<=$div;$j++) {
				$cf = pow((1 + $taxa), $j);
				$cf = (1 / $cf);
				$cf = (1 - $cf);
				$cf = ($taxa / $cf);
				$parcelas = ($valor*$cf);
				$parcelas = number_format($parcelas, 2, '.', '');
				$valors = number_format($valor, 2, '.', '');

				$op = GetModuleVariable('checkout_mplight','semjuros');
				$msgs ="<b>Parcelamento via Mercadopago</b><br>";
				if($j==1 OR $op>=$j) {
				$msg .="<b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</b> sem juros.<br>";
				}else{
				$msg1 .="<b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($parcelas, 1, 0)."</b> com juros.<br>";
				}
				}
				//inicio do codigo do parcelamento
				$msgs ="<b>Parcelamento via Mercadopago</b><br>";
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/mp.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msgs.''.$msg.''.$msg1.'</div>';
			}
			break;

			case 'paypal':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_paypal','is_setup');
				$div = GetModuleVariable('checkout_paypal','dividir');
				$juross = '0';
				$taxa = 0;
				$jt = 1;
				$pm = GetModuleVariable('checkout_paypal','minimo');
				if(!empty($ativo)) {
				//verifica o juros
				$pro = $_GET['valor'];
				$valor = $pro;
				if($juross<=0 OR empty($juross)){
				$valor = $valor;
				} else {
				$valor = (($valor/100)*$juross)+$valor;
				}
				$msg = '';
				$msg1 = '';
				$splitss = (int) ($valor/$pm);
				if($splitss<=$div){
				$div = $splitss;
				}else{
				$div = $div;
				}
				for($j=1; $j<=$div;$j++) {
				if($jt==0)
				$parcelas = $this->jurosSimples($valor, $taxa, $j);
				else
				$parcelas = $this->jurosComposto($valor, $taxa, $j);
				$parcelas = number_format($parcelas, 2, '.', '');
				$valors = number_format($valor, 2, '.', '');
				$op = GetModuleVariable('checkout_paypal','dividir');
				$msgs ="<b>Parcelamento via Paypal</b><br>";
				if($op>=$j) {
				$msg .="<font size='2'><b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</b> sem juros.</font><br>";
				}else{
				$msg1 .="<font size='2'><b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($parcelas, 1, 0)."</b> (<u>".$parcelas*$j."</u>) com juros.</font><br>";
				}
				}
				//inicio do codigo do parcelamento
				$msgs ="<b>Parcelamento via Paypal</b><br>";
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/paypal.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msgs.''.$msg.''.$msg1.'</div>';
			}
			break;

			case 'shopline':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_itaushopline','is_setup');
				$desc = GetModuleVariable('checkout_itaushopline','desconto');
				$boleto = '';
				$facil = '';
				$finan = '';
				$trans = '';
				if(!empty($ativo)) {
				//verifica o desconto
				$pro = $_GET['valor'];
				$msg = "";
				if($boleto=="") 
				$preco = CurrencyConvertFormatPrice($pro, 1, 0);
				$msg .= "<b> ".$preco."</b> a vista no boleto.<br>";

				if($facil=="") {
				$preco = CurrencyConvertFormatPrice($pro, 1, 0);
				$msg .= "<b> ".$preco."</b> a vista por cartão de debito.<br>";
				}
				if($trans=="") {
				$preco = CurrencyConvertFormatPrice($pro, 1, 0);
				$msg .= "<b> ".$preco."</b> a vista por transferência bancaria.<br>";

				}
				//inicio do codigo do parcelamento
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/itaushopline.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msg.'</div>';
			}
			break;

			case 'visacredito':
				$li= '';
				$fade= '';
				if($i=='1'){
					$li= 'active';
					$fade= 'fade in active';
				}
				$ativo = GetModuleVariable('checkout_cartaodecreditomanual','is_setup');
				$div = GetModuleVariable('checkout_cartaodecreditomanual','dividir');
				$juross = '0';
				$taxa = GetModuleVariable('checkout_cartaodecreditomanual','juros');
				$jt = GetModuleVariable('checkout_cartaodecreditomanual','tipojuros');
				$pm = GetModuleVariable('checkout_cartaodecreditomanual','minimo');
				if(!empty($ativo)) {
				//verifica o juros
				$pro = $_GET['valor'];
				$valor = $pro;
				if($juross<=0 OR empty($juross)){
				$valor = $valor;
				} else {
				$valor = (($valor/100)*$juross)+$valor;
				}
				$msg = '';
				$msg1 = '';
				$splitss = (int) ($valor/$pm);
				if($splitss<=$div){
				$div = $splitss;
				}else{
				$div = $div;
				}
				for($j=1; $j<=$div;$j++) {
				if($jt==0)
				$parcelas = $this->jurosSimples($valor, $taxa, $j);
				else
				$parcelas = $this->jurosComposto($valor, $taxa, $j);
				$parcelas = number_format($parcelas, 2, '.', '');
				$valors = number_format($valor, 2, '.', '');
				$op = GetModuleVariable('checkout_cartaodecreditomanual','semjuros');
				$msgs ="<b>Parcelamento via cartão de crédito!</b><br>";
				if($op>=$j) {
				$msg .="<font size='2'><b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($valors/$j, 1, 0)."</b> sem juros.</font><br>";
				}else{
				$msg1 .="<font size='2'><b>".$j."x</b> de <b>".CurrencyConvertFormatPrice($parcelas, 1, 0)."</b>  com juros.</font><br>";
				}
				}
				//inicio do codigo do parcelamento
				$msgs ="<b>Parcelamento via cartão de crédito!</b><br>";
				$GLOBALS['Formas'] .= '<li class="'.$li.'"><a data-toggle="tab" href="#forma'.$i.'"><img src="'.$GLOBALS['ShopPath'].'/modificacoes/fp/cartao.png" /></a></li>';
				$GLOBALS['Parcelas'] .= '<div id="forma'.$i.'" class="tab-pane '.$fade.'">'.$msgs.''.$msg.''.$msg1.'</div>';
			}
			break;
		}
		$i++;
		//fim do switch
		}
		//aplica no template
		$select = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('SimularParcela');
		echo $GLOBALS['ISC_CLASS_TEMPLATE']->ParseSnippets($select, true);
	}

	public function DisableDesignMode(){
		isc_unsetCookie('designModeToken');
		exit;
	}

	public function DeleteUploadedFileInCart(){
		if(!isset($_REQUEST['item']) || !isset($_REQUEST['field'])) {
			return false;
		}

		$itemId = $_REQUEST['item'];

		$quote = getCustomerQuote();
		$item = $quote->getItemById($itemId);
		if(!$item) {
			return false;
		}

		$item->deleteConfigurableFile($_REQUEST['field']);
	}

	public function EditConfigurableFieldsInCart(){
		$quote = getCustomerQuote();
		if(!isset($_REQUEST['itemid']) || !$quote->hasItem($_REQUEST['itemid'])) {
			return false;
		}
		$output = '';
		$item = $quote->getItemById($_REQUEST['itemid']);
		$existingConfiguration = $item->getConfiguration();
		$GLOBALS['ItemId'] = $item->getId();
		$GLOBALS['ISC_CLASS_PRODUCT'] = GetClass('ISC_PRODUCT');
		$GLOBALS['CartProductName'] = isc_html_escape($item->getName());
		$fields = $item->getConfigurableOptions();
		foreach($fields as $field) {
			$GLOBALS['ProductFieldType'] = isc_html_escape($field['fieldtype']);
			$GLOBALS['ProductFieldId'] = (int)$field['productfieldid'];
			$GLOBALS['ProductFieldName'] = isc_html_escape($field['fieldname']);
			$GLOBALS['ProductFieldRequired'] = '';
			$GLOBALS['FieldRequiredClass'] = '';
			$GLOBALS['ProductFieldValue'] = '';
			$GLOBALS['ProductFieldFileValue'] = '';
			$GLOBALS['HideCartFileName'] = 'display: none';
			$GLOBALS['CheckboxFieldNameLeft'] = '';
			$GLOBALS['CheckboxFieldNameRight'] = '';
			$GLOBALS['HideDeleteFileLink'] = 'display: none';
			$GLOBALS['HideFileHelp'] = "display:none";

			$configurableField = array(
				'type'				=> '',
				'name'				=> '',
				'fileType'			=> '',
				'fileOriginalName'	=> '',
				'value'				=> '',
				'selectOptions'		=> '',
			);

			if(isset($existingConfiguration[$field['productfieldid']])) {
				$configurableField = $existingConfiguration[$field['productfieldid']];
			}

			$snippetFile = 'ProductFieldInput';
			switch ($field['fieldtype']) {
				case 'textarea': {
					$GLOBALS['ProductFieldValue'] = isc_html_escape($configurableField['value']);
					$snippetFile = 'ProductFieldTextarea';
					break;
				}
				case 'file': {
					$fieldValue = isc_html_escape($configurableField['fileOriginalName']);
					$GLOBALS['HideDeleteCartFieldFile'] = '';
					$GLOBALS['CurrentProductFile'] = $fieldValue;
					$GLOBALS['ProductFieldFileValue'] = $fieldValue;
					$GLOBALS['HideFileHelp'] = "";
					$GLOBALS['FileSize'] = Store_Number::niceSize($field['fieldfilesize']*1024);

					if($fieldValue != '') {
						$GLOBALS['HideCartFileName'] = '';
					}

					if(!$field['fieldrequired']) {
						$GLOBALS['HideDeleteFileLink'] = '';
					}
					$GLOBALS['FileTypes'] = isc_html_escape($field['fieldfiletype']);
					break;
				}
				case 'checkbox': {
					$GLOBALS['CheckboxFieldNameLeft'] = $GLOBALS['ProductFieldName'];
					if($configurableField['value'] == 'on') {
						$GLOBALS['ProductFieldValue'] = 'checked';
					}
					$snippetFile = 'ProductFieldCheckbox';
					break;
				}
				case 'select':
					$options = explode(',', $configurableField['selectOptions']);
					$optionStr = '<option value="">' . GetLang('PleaseChooseAnOption') . '</option>';
					foreach ($options as $option) {
						$option = trim($option);

						$selected = '';
						if ($option == $configurableField['value']) {
							$selected = 'selected="selected"';
						}

						$optionStr .= "<option value=\"" . isc_html_escape($option) . "\" " . $selected . ">" . isc_html_escape($option) . "</option>\n";
					}
					$GLOBALS['SelectOptions'] = $optionStr;
					$snippetFile = 'ProductFieldSelect';
					break;
				default: {
					$GLOBALS['ProductFieldValue'] = isc_html_escape($configurableField['value']);
					break;
				}
			}

			if($field['fieldrequired']) {
				$GLOBALS['ProductFieldRequired'] = '<span class="Required">*</span>';
				$GLOBALS['FieldRequiredClass'] = 'FieldRequired';
			}
			$output .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('Cart'.$snippetFile);
		}
		$GLOBALS['SNIPPETS']['ProductFieldsList'] = $output;

		$editProductFields = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('CartEditProductFieldsForm');
		echo $GLOBALS['ISC_CLASS_TEMPLATE']->ParseSnippets($editProductFields, $GLOBALS['SNIPPETS']);
	}

	public function SelectGiftWrapping(){
		$quote = getCustomerQuote();
		if(!isset($_REQUEST['itemId']) || !$quote->hasItem($_REQUEST['itemId'])) {
			exit;
		}

		$item = $quote->getItemById($_REQUEST['itemId']);

		$GLOBALS['GiftWrappingTitle'] = sprintf(GetLang('GiftWrappingForX'), isc_html_escape($item->getName()));
		$GLOBALS['ProductName'] = $item->getName();
		$GLOBALS['ItemId'] = $item->getId();

		// Get the available gift wrapping options for this product
		$wrappingOptions = $item->getGiftWrappingOptions();
		if($wrappingOptions === false) {
			exit;
		}

		if(empty($wrappingOptions) || in_array(0, $wrappingOptions)) {
			$giftWrapWhere = "wrapvisible='1'";
		}
		else {
			$wrappingOptions = implode(',', array_map('intval', $wrappingOptions));
			$giftWrapWhere = "wrapid IN (".$wrappingOptions.")";
		}
		$query = "
			SELECT *
			FROM [|PREFIX|]gift_wrapping
			WHERE ".$giftWrapWhere."
			ORDER BY wrapname ASC
		";
		$wrappingOptions = array();
		$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
		while($wrap = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			$wrappingOptions[$wrap['wrapid']] = $wrap;
		}

		// This product is already wrapped, select the existing value
		$GLOBALS['GiftWrapMessage'] = '';

		$selectedWrapping = 0;
		$existingWrapping = $item->getGiftWrapping();
		if($existingWrapping !== false) {
			$selectedWrapping = $existingWrapping['wrapid'];
			$GLOBALS['GiftWrapMessage'] = isc_html_escape($existingWrapping['wrapmessage']);
		}

		$GLOBALS['HideGiftWrapMessage'] = 'display: none';

		// Build the list of wrapping options
		$GLOBALS['WrappingOptions'] = '';
		$GLOBALS['GiftWrapPreviewLinks'] = '';
		foreach($wrappingOptions as $option) {
			$sel = '';
			if($selectedWrapping == $option['wrapid']) {
				$sel = 'selected="selected"';
				if($option['wrapallowcomments']) {
					$GLOBALS['HideGiftWrapMessage'] = '';
				}
			}
			$classAdd = '';
			if($option['wrapallowcomments']) {
				$classAdd = 'AllowComments';
			}

			if($option['wrappreview']) {
				$classAdd .= ' HasPreview';
				$previewLink = GetConfig('ShopPath').'/'.GetConfig('ImageDirectory').'/'.$option['wrappreview'];
				if($sel) {
					$display = '';
				}
				else {
					$display = 'display: none';
				}
				$GLOBALS['GiftWrapPreviewLinks'] .= '<a id="GiftWrappingPreviewLink'.$option['wrapid'].'" class="GiftWrappingPreviewLinks" target="_blank" href="'.$previewLink.'" style="'.$display.'">'.GetLang('Preview').'</a>';
			}

			$GLOBALS['WrappingOptions'] .= '<option class="'.$classAdd.'" value="'.$option['wrapid'].'" '.$sel.'>'.isc_html_escape($option['wrapname']).' ('.CurrencyConvertFormatPrice($option['wrapprice']).')</option>';
		}

		$quantity = $item->getQuantity();
		if($quantity > 1) {
			$GLOBALS['ExtraClass'] = 'PL40';
			$GLOBALS['GiftWrapModalClass'] = 'SelectGiftWrapMultiple';
			$GLOBALS['SNIPPETS']['GiftWrappingOptions'] = '';
			for($i = 1; $i <= $quantity; ++$i) {
				$GLOBALS['GiftWrappingId'] = $i;
				$GLOBALS['SNIPPETS']['GiftWrappingOptions'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('GiftWrappingWrapOptions');
			}
		}
		else {
			$GLOBALS['HideSplitWrappingOptions'] = 'display: none';
		}

		$GLOBALS['HideWrappingTitle']		= 'display: none';
		$GLOBALS['HideWrappingSeparator']	= 'display: none';
		$GLOBALS['GiftWrappingId'] = 'all';
		$GLOBALS['SNIPPETS']['GiftWrappingOptionsSingle'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('GiftWrappingWrapOptions');

		$selectWrapping = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('SelectGiftWrapping');
		echo $GLOBALS['ISC_CLASS_TEMPLATE']->ParseSnippets($selectWrapping, $GLOBALS['SNIPPETS']);
	}

	/**
	 * Check a customers entered credentials when logging in via the express checkout.
	 */
	private function ExpressCheckoutLogin()
	{
		// Attempt to log the customer in
		$GLOBALS['ISC_CLASS_CUSTOMER'] = GetClass('ISC_CUSTOMER');
		if(!$GLOBALS['ISC_CLASS_CUSTOMER']->CheckLogin(true)) {
			$loginLink = '#';
			$onClick = '$("#checkout_type_register").click(); $("#CreateAccountButton").click(); return false;';
			$errorMessage = sprintf(GetLang('CheckoutBadLoginDetails'), $loginLink, $onClick);
			$response = array(
				'status' => 0,
				'errorMessage' => $errorMessage,
				'errorContainer' => '#CheckoutLoginError',
			);
			echo isc_json_encode($response);
			exit;
		}

		$response = array(
			'status' => 1,
			'resetSteps' => true,
			'changeStep' => 'BillingAddress',
			'completedSteps' => array(
				array(
					'id' => 'AccountDetails',
					'message' => getLang('CheckingOutAs').' '.$_POST['login_email']
				),
			),
			'stepContent' => array(
				array(
					'id' => 'BillingAddress',
					'content' => getClass('ISC_CHECKOUT')->expressCheckoutChooseAddress('billing', true)
				),
				array(
					'id' => 'ShippingAddress',
					'content' => getClass('ISC_CHECKOUT')->expressCheckoutChooseAddress('shipping', true)
				),
			)
		);
		echo isc_json_encode($response);
		exit;
	}

	/**
	 * Generate the payment form for a payment provider (credit card manual, etc) and display it for the express checkout.
	 */
	private function GetExpressCheckoutPaymentForm()
	{
		// Attempt to create the pending order with the selected details
		$pendingResult = getClass('ISC_CHECKOUT')->savePendingOrder();

		// There was a problem creating the pending order
		if(!is_array($pendingResult)) {
			$response = array(
				'status' => 0,
				'errorMessage' => getLang('ProblemCreatingOrder'),
				'changeStep' => 'Confirmation'
			);
			echo isc_json_encode($response);
			exit;
		}

		// There was a problem creating the pending order but we have an actual error message
		if(isset($pendingResult['error'])) {
			$response = array(
				'status' => 0,
				'errorMessage' => $pendingResult['error'],
				'changeStep' => 'Confirmation'
			);
			echo isc_json_encode($response);
			exit;
		}

		// Otherwise, the gateway want's to do something
		if($pendingResult['provider']->GetPaymentType() == PAYMENT_PROVIDER_ONLINE || method_exists($pendingResult['provider'], 'ShowPaymentForm')) {
			if($pendingResult['provider']->GetPaymentType() !== PAYMENT_PROVIDER_ONLINE) {
				$pendingResult['showPaymentForm'] = $pendingResult['provider']->ShowPaymentForm();
			}

			// If we have a payment form to show then show that
			if(isset($pendingResult['showPaymentForm']) && $pendingResult['showPaymentForm']) {
				$response = array(
					'status' => 1,
					'stepContent' => array(
						array(
							'id' => 'PaymentDetails',
							'content' => $pendingResult['provider']->showPaymentForm()
						),
					),
					'changeStep' => 'PaymentDetails',
					'completeSteps' => array(
						array(
							'id' => 'Confirmation',
							'message' => $pendingResult['provider']->getDisplayName()
						),
					),
				);
				echo isc_json_encode($response);
			}
		}
		exit;
	}

	/**
	 * Generate the order confirmation message and save the pending order for a customer checking out via the
	 * express checkout
	 */
	private function GetExpressCheckoutConfirmation($completedSteps = array())
	{


		$confirmation = getClass('ISC_CHECKOUT')->GenerateExpressCheckoutConfirmation();
		if(!$confirmation) {
			$response = array(
				'status' => 0,
				'changeStep' => 'BillingAddress',
			);
			echo isc_json_encode($response);
			exit;
		}

		$response = array(
			'status' => 1,
			'changeStep' => 'Confirmation',
			'resetSteps' => true,
			'stepContent' => array(
				array(
					'id' => 'Confirmation',
					'content' => $confirmation
				),
			),
			'completedSteps' => $completedSteps,
		);
		echo isc_json_encode($response);
		exit;
	}

	public function getCheckoutAddressPreview(ISC_QUOTE_ADDRESS $address)
	{
		$addressPieces = array(
			$address->getFirstName().' '.$address->getLastName(),
			$address->getCompany(),
			$address->getAddress1(),
			$address->getAddress2(),
                            $address->getAddress3(),
			$address->getAddress4(),
			$address->getCity(),
			$address->getStateName(),
			$address->getCountryName(),
			$address->getZip()
		);
		foreach($addressPieces as $k => $piece) {
			if(!trim($piece)) {
				unset($addressPieces[$k]);
			}
		}

		$addressString = implode(', ', $addressPieces);
		if(isc_strlen($addressString) > 60) {
			$addressString = substr($addressString, 0, 57).'...';
		}

		return $addressString;
	}

	/**
	 * Save the billing address for a customer checking out via express checkout.
	 */
	public function saveExpressCheckoutBillingAddress()
	{
		// If the customer is not logged in and guest checkout is enabled, then don't go any further
		if(!customerIsSignedIn() && !getConfig('GuestCheckoutEnabled') &&
			empty($_POST['createAccount'])) {
				$response = array(
					'status' => 0,
					'changeStep' => 'AccountDetails',
					'errorMessage' => getLang('GuestCheckoutDisabledError')
				);
				echo isc_json_encode($response);
				exit;
		}

		$addressDetails =  null;
		$shipToBilling = false;

		// If the customer isn't signed in then they've just entered an address that we need to validate
		if(isset($_REQUEST['BillingAddressType']) && $_REQUEST['BillingAddressType'] == 'new') {
			$errors = array();
			// An invalid address was entered, show the form again
			$addressDetails = getClass('ISC_CHECKOUT')->validateGuestCheckoutAddress('billing', $errors);
			if(!$addressDetails) {
				$response = array(
					'status' => 0,
					'changeStep' => 'BillingAddress',
					'errorMessage' => implode("\n", $errors)
				);
				echo isc_json_encode($response);
				exit;
			}

			// Make sure the email address isn't already in use if the customer is
			// creating a new account.
			// Plus if it's guess checkout and creation of account after the checkout process is enabled
			if(!customerIsSignedIn() && (!empty($_POST['createAccount']) || (getConfig('GuestCheckoutEnabled') && getConfig('GuestCheckoutCreateAccounts')))) {
				$emailField = $GLOBALS['ISC_CLASS_FORM']->getFormField(FORMFIELDS_FORM_ACCOUNT, '1', '', true);
				$email = $emailField->getValue();

				// Check that this email address isn't already in use by a customer
				$customer = GetClass('ISC_CUSTOMER');
				if($customer->AccountWithEmailAlreadyExists($email)) {
					$response = array(
						'status' => 0,
						'changeStep' => 'BillingAddress',
						'errorMessage' => getLang('CheckoutEmailAddressInUseAjax'),
						'focus' => '#'.$emailField->getFieldId(),
					);
					echo isc_json_encode($response);
					exit;
				}
			}

			if(!empty($_POST['ship_to_billing_new'])) {
				$shipToBilling = true;
			}
		}
		else {
			// We've just selected an address
			if(isset($_POST['sel_billing_address'])) {
				$addressDetails = (int)$_POST['sel_billing_address'];
			}

			if(!empty($_POST['ship_to_billing_existing'])) {
				$shipToBilling = true;
			}
		}

		// There was a problem saving the selected billing address
		if(!getClass('ISC_CHECKOUT')->setOrderBillingAddress($addressDetails)) {
			$response = array(
				'status' => 0,
				'changeStep' => 'BillingAddress',
				'errorMessage' => getLang('UnableSaveOrderBillingAddress'),
			);

			echo isc_json_encode($response);
			exit;
		}

		if(!empty($_POST['save_billing_address'])) {
			getCustomerQuote()->getBillingAddress()->setSaveAddress(true);
		}

		$completedSteps = array(
			array(
				'id' => 'BillingAddress',
				'message' => $this->getCheckoutAddressPreview(
					getCustomerQuote()->getBillingAddress()
				),
			)
		);

		// If creating an account, store the account creation fields
		unset($_SESSION['CHECKOUT']['CREATE_ACCOUNT']);
		if(!empty($_POST['createAccount'])) {
			$accountFields = $GLOBALS['ISC_CLASS_FORM']->getFormFields(FORMFIELDS_FORM_ACCOUNT, true);
			$accountSession = array(
				'customFields' => array()
			);
			foreach($accountFields as $fieldId => $formField) {
				if($formField->record['formfieldprivateid'] == 'Password') {
					$accountSession['password'] = $formField->getValue();
				}
				// Apart from the password, only interested in CUSTOM fields
				else if(!$formField->record['formfieldprivateid']) {
					$accountSession['customFields'][$fieldId] = $formField->getValue();
				}
			}
			$_SESSION['CHECKOUT']['CREATE_ACCOUNT'] = $accountSession;
		}

		// If a digital order, skip right to the order confirmation
		if(getCustomerQuote()->isDigital()) {
			$this->getExpressCheckoutConfirmation($completedSteps);
			exit;
		}

		// Otherwise, proceed with shipping

		// Shipping to the billing address so save it as well
		if($shipToBilling) {
			if(!getClass('ISC_CHECKOUT')->setOrderShippingAddress($addressDetails, true)) {
				$response = array(
					'status' => 0,
					'changeStep' => 'ShippingAddress',
					'errorMessage' => getLang('UnableSaveOrderShippingAddress'),
				);

				echo isc_json_encode($response);
				exit;
			}

			// If we're shipping to the billing address, then reload the shipping address
			// quote block, because it could contain updated values.
			$stepContent = array(array(
				'id' => 'ShippingAddress',
				'content' => getClass('ISC_CHECKOUT')->expressCheckoutChooseAddress('shipping', true),
			));
			$this->getExpressCheckoutShippers($completedSteps, $stepContent);
			exit;
		}

		$response = array(
			'status' => 1,
			'changeStep' => 'ShippingAddress',
			'completedSteps' => $completedSteps,
			'resetSteps' => true,
		);
		echo isc_json_encode($response);
		exit;
	}

	public function saveExpressCheckoutShippingAddress()
	{
		$quote = getCustomerQuote();
		if($quote->isDigital()) {
			exit;
		}

		$addressDetails = null;

		if(isset($_REQUEST['ShippingAddressType']) && $_REQUEST['ShippingAddressType'] == 'new') {
			$errors = array();
			// An invalid address was entered, show the form again
			$addressDetails = getClass('ISC_CHECKOUT')->validateGuestCheckoutAddress('shipping', $errors);
			if(!$addressDetails) {
				$response = array(
					'status' => 0,
					'changeStep' => 'ShippingAddress',
					'errorMessage' => implode("\n", $errors)
				);
				echo isc_json_encode($response);
				exit;
			}
		}
		else {
			// We've just selected an address
			if(isset($_POST['sel_shipping_address'])) {
				$addressDetails = (int)$_POST['sel_shipping_address'];
			}
		}

		if(!getClass('ISC_CHECKOUT')->setOrderShippingAddress($addressDetails)) {
			$response = array(
				'status' => 0,
				'changeStep' => 'ShippingAddress',
				'errorMessage' => getLang('UnableSaveOrderShippingAddress'),
			);

			echo isc_json_encode($response);
			exit;
		}

		$this->getExpressCheckoutShippers();
	}

	public function saveExpressCheckoutShippingProvider()
	{
		$quote = getCustomerQuote();
		if($quote->isDigital()) {
			exit;
		}

		// If the shipping provider couldn't be saved with the order show an error message
		// For each shipping address in the order, the shipping provider now needs to be saved
		$success = true;
		$shippingAddresses = getClass('ISC_CHECKOUT')->getQuote()->getShippingAddresses();
		foreach($shippingAddresses as $shippingAddress) {
			$shippingAddressId = $shippingAddress->getId();
			if(!isset($_POST['selectedShippingMethod'][$shippingAddressId])) {
				$success = false;
				break;
			}

			$id = $_POST['selectedShippingMethod'][$shippingAddressId];
			$cachedShippingMethod = $shippingAddress->getCachedShippingMethod($id);
			if(empty($cachedShippingMethod)) {
				$success = false;
				break;
			}

			$shippingAddress->setShippingMethod(
				$cachedShippingMethod['price'],
				$cachedShippingMethod['description'],
				$cachedShippingMethod['module']
			);
			$shippingAddress->setHandlingCost($cachedShippingMethod['handling']);
		}

		if(!$success) {
			$response = array(
				'success' => 0,
				'changeStep' => 'ShippingProvider',
				'errorMessage' => getLang('UnableSaveOrderShippingMethod'),
			);
			echo isc_json_encode($response);
			exit;
		}

		$completedSteps = array(
			array(
				'id' => 'ShippingProvider',
				'message' =>
					$shippingAddress->getShippingProvider() . ' ' .
					getLang('ExpressCheckoutFor') . ' ' .
					currencyConvertFormatPrice($shippingAddress->getShippingCost())
			)
		);
		$this->getExpressCheckoutConfirmation($completedSteps);
	}

	/**
	 * Fetch the address entry fields for a guest when using the express checkout.
	 */
	private function GetExpressCheckoutAddressFields()
	{
		// Make sure the customer is logged out. This is a guest checkout
		getClass('ISC_CUSTOMER')->logout(true);

		if(!empty($_POST['type']) && $_POST['type'] != 'guest') {
			$addressType = 'account';
			$accountDetailsMessage = getLang('ExpressCheckoutCreatingAnAccount');
		}
		else {
			$addressType = 'billing';
			$accountDetailsMessage = getLang('ExpressCheckoutCheckingOutAsGuest');
		}

		$response = array(
			'status' => 1,
			'completedSteps' => array(
				array(
					'id' => 'AccountDetails',
					'message' => $accountDetailsMessage,
				),
			),
			'stepContent' => array(
				array(
					'id' => 'BillingAddress',
					'content' => getClass('ISC_CHECKOUT')->expressCheckoutChooseAddress($addressType, true),
				),
				array(
					'id' => 'ShippingAddress',
					'content' => getClass('ISC_CHECKOUT')->expressCheckoutChooseAddress('shipping', true),
				),
			),
			'changeStep' => 'BillingAddress',
			'resetSteps' => 1,
		);

		echo isc_json_encode($response);
		exit;
	}

	/**
	 * Generate a list of shipping methods/providers for a customer checking out via the express checkout.
	 */
	private function GetExpressCheckoutShippers($completedSteps = array(), $stepContent = array())
	{
		$quote = getCustomerQuote();
		if($quote->isDigital()) {
			exit;
		}

		$shippingAddress = $quote->getShippingAddress();
		if(!$shippingAddress->hasCompleteAddress()) {
			$response = array(
				'status' => 0,
				'changeStep' => 'ShippingAddress',
				'resetSteps' => true,
				'errorMessage' => getLang('UnableToShipToAddressSingle'),
				'stepContent' => $stepContent,
			);
			echo isc_json_encode($response);
			exit;
		}

		$availableMethods = $shippingAddress->getAvailableShippingMethods();
		if(empty($availableMethods)) {
			$response = array(
				'status' => 0,
				'changeStep' => 'ShippingAddress',
				'resetSteps' => true,
				'errorMessage' => getLang('UnableToShipToAddressSingle'),
				'stepContent' => $stepContent,
			);
			echo isc_json_encode($response);
			exit;
		}

		// Keeping for legacy reasons for now
		$GLOBALS['HideVendorTitle'] = 'display: none';
		$GLOBALS['HideVendorItems'] = 'display: none';

		// Because split shipping isn't supported on express checkout:
		$GLOBALS['HideItemList'] = 'display: none';
		$GLOBALS['HideHorizontalRule'] = 'display: none';
		$GLOBALS['HideAddressLine'] = 'display: none';

		$hasTransit = false;
		$GLOBALS['ShippingQuotes'] = '';

		// Now build a list of the actual available quotes
		$GLOBALS['ShippingProviders'] = '';
		$GLOBALS['AddressId'] = $shippingAddress->getId();
		foreach($availableMethods as $quoteId => $method) {
			$price = getClass('ISC_TAX')->getPrice(
				$method['price'],
				getConfig('taxShippingTaxClass'),
				getConfig('taxDefaultTaxDisplayCart'),
				$shippingAddress->getApplicableTaxZone()
			);
			$GLOBALS['ShipperName'] = isc_html_escape($method['description']);
			$GLOBALS['ShippingPrice'] = CurrencyConvertFormatPrice($price);
			$GLOBALS['ShippingQuoteId'] = $quoteId;
			$GLOBALS['ShippingData'] = $GLOBALS['ShippingQuoteId'];

			if(isset($method['transit'])) {
				$hasTransit = true;

				$days = $method['transit'];

				if ($days == 0) {
					$transit = GetLang("SameDay");
				}
				else if ($days == 1) {
					$transit = GetLang('NextDay');
				}
				else {
					$transit = sprintf(GetLang('Days'), $days);
				}

				$GLOBALS['TransitTime'] = $transit;
				$GLOBALS['TransitTime'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('CartShippingTransitTime');
			}
			else {
				$GLOBALS['TransitTime'] = "";
			}
			$GLOBALS['ShippingProviders'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("ExpressCheckoutShippingMethod");
		}
		// Add it to the list
		$GLOBALS['ShippingQuotes'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('ShippingQuote');

		if ($hasTransit) {
			$GLOBALS['DeliveryDisclaimer'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('CartShippingDeliveryDisclaimer');
		}

		$methodList = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('ExpressCheckoutChooseShipper');

		$response = array(
			'status' => 1,
			'changeStep' => 'ShippingProvider',
			'resetSteps' => true,
			'stepContent' => array_merge($stepContent, array(array(
				'id' => 'ShippingProvider',
				'content' => $methodList
			))),
			'completedSteps' => array_merge($completedSteps, array(array(
				'id' => 'ShippingAddress',
				'message' => $this->getCheckoutAddressPreview($shippingAddress),
			))),
		);
		echo isc_json_encode($response);
		exit;
	}

	/**
	 * Retrieve a list of shipping quotes for a customer estimating their shipping on the 'View Cart' page.
	 */
	private function GetShippingQuotes()
	{
		if(empty($_POST['countryId']) || empty($_POST['zipCode'])) {
			exit;
		}

		$statesList = GetStateListAsIdValuePairs((int)$_POST['countryId']);
		if (!empty($statesList) && empty($_POST['stateId'])) {
			exit;
		}

		// Cart page shipping quotes don't support split shipping
		$quote = getCustomerQuote();
		$quote->setIsSplitShipping(false);

		$shippingAddress = $quote->getShippingAddress();
		$billingAddress = $quote->getBillingAddress();

		$shippingAddress->setCountryById($_POST['countryId']);
		$billingAddress->setCountryById($_POST['countryId']);
		if(!empty($_POST['stateId'])) {
			$shippingAddress->setStateById($_POST['stateId']);
			$billingAddress->setStateById($_POST['stateId']);
		}
		if(!empty($_POST['zipCode'])) {
			$shippingAddress->setZip($_POST['zipCode']);
			$billingAddress->setZip($_POST['zipCode']);
		}

		$quote->addShippingAddress($shippingAddress);
		$shippingMethods = $shippingAddress->getAvailableShippingMethods();
		if(empty($shippingMethods)) {
			echo getLang('UnableEstimateShipping');
			exit;
		}

		// Keeping this for legacy purposes for now
		$GLOBALS['HideVendorDetails'] = 'display: none';
		$GLOBALS['ShippingQuotesListNote'] = '';
		$GLOBALS['HideShippingQuotesListNote'] = 'display: none';
		$GLOBALS['VendorShippingQuoteClass'] = '';
		$GLOBALS['HideShippingItemList'] = 'display: none';

		$hasTransit = false;
		$GLOBALS['ShippingQuoteRow'] = '';
		foreach($shippingMethods as $quoteId => $method) {
			$price = getClass('ISC_TAX')->getPrice(
				$method['price'],
				getConfig('taxShippingTaxClass'),
				getConfig('taxDefaultTaxDisplayCart'),
				$shippingAddress->getApplicableTaxZone()
			);
			$GLOBALS['ShipperName'] = isc_html_escape($method['description']);
			$GLOBALS['ShippingPrice'] = CurrencyConvertFormatPrice($price);
			$GLOBALS['ShippingQuoteId'] = $quoteId;

			$GLOBALS['TransitTime'] = "";
			if(isset($method['transit'])) {
				$hasTransit = true;
				$days = $method['transit'];
				if ($days == 0) {
					$transit = GetLang("SameDay");
				}
				else if ($days == 1) {
					$transit = GetLang('NextDay');
				}
				else {
					$transit = sprintf(GetLang('Days'), $days);
				}

				$GLOBALS['TransitTime'] = $transit;
				$GLOBALS['TransitTime'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('CartShippingTransitTime');
			}

			$GLOBALS['ShippingQuoteRow'] .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('CartShippingQuoteRow');
		}

		$GLOBALS['ShippingQuotes'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('EstimatedShippingQuote');

		if ($hasTransit) {
			$GLOBALS['DeliveryDisclaimer'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('CartShippingDeliveryDisclaimer');
		}

		echo $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet('EstimatedShippingQuoteList');
	}

	private function GetCountryStates()
	{
		$country = $_REQUEST['c'];
		echo GetStateList($country);
	}

	private function GetExchangeRate()
	{
		if (!array_key_exists("currencyid", $_REQUEST)
			|| !($result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]currencies WHERE currencyid = " . (int)$_REQUEST['currencyid']))
			|| !($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result))) {
			exit;
		}

		print $row['currencyexchangerate'];
		exit;
	}

	public function GetStateList()
	{
		if (!array_key_exists('countryName', $_POST) || $_POST['countryName'] == '') {
			$tags[] = $this->MakeXMLTag('status', 0);
			$this->SendXMLHeader();
			$this->SendXMLResponse($tags);
			exit;
		}

		$tags[] = $this->MakeXMLTag('status', 1);
		$tags[] = '<options>';

		$query = "SELECT statename
					FROM [|PREFIX|]countries c
						JOIN [|PREFIX|]country_states s ON c.countryid = s.statecountry
					WHERE c.countryname='" . $GLOBALS['ISC_CLASS_DB']->Quote($_POST['countryName']) . "'
					ORDER BY statename ASC";

		$result = $GLOBALS['ISC_CLASS_DB']->Query($query);
		while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			$tags[] = '<option>';
			$tags[] = $this->MakeXMLTag('name', $row['statename'], true);
			$tags[] = '</option>';
		}

		$tags[] = '</options>';
		$this->SendXMLHeader();
		$this->SendXMLResponse($tags);
		exit;
	}

	private function GetCountryList()
	{
		$tags[] = $this->MakeXMLTag('status', 1);
		$tags[] = '<options>';

		$result = $GLOBALS['ISC_CLASS_DB']->Query("SELECT * FROM [|PREFIX|]countries ORDER BY countryname ASC");
		while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
			$tags[] = '<option>';
			$tags[] = $this->MakeXMLTag('name', $row['countryname'], true);
			$tags[] = '</option>';
		}

		$tags[] = '</options>';
		$this->SendXMLHeader();
		$this->SendXMLResponse($tags);
		exit;
	}

	/**
	* Handles adding products from the list display mode
	*
	*/
	private function AddProductsToCart()
	{
		$response = array();

		if (isset($_REQUEST['products'])) {
			/** @var ISC_CART */
			$cart = GetClass('ISC_CART');

			$products = explode("&", $_REQUEST["products"]);

			foreach ($products as $product) {
				list($id, $qty) = explode("=", $product);
				if (!$cart->AddSimpleProductToCart($id, $qty)) {
					$response["error"] = $_SESSION['AddProductErrorMessage'];
				}
			}
		}

		echo isc_json_encode($response);
		exit;
	}


	public function ProcessRemoteActions()
	{

		if(!isset($_REQUEST['provider'])) {
			$tags[] = $this->MakeXMLTag('errorMsg', GetLang('ExpressCheckoutLoadError')."1");
			$this->SendXMLHeader();
			$this->SendXMLResponse($tags);
			exit;
		}
		if(!GetModuleById('checkout', $provider, $_REQUEST['provider'])) {
			$tags[] = $this->MakeXMLTag('errorMsg', GetLang('ExpressCheckoutLoadError')."2");
			$this->SendXMLHeader();
			$this->SendXMLResponse($tags);
			exit;
		}

		// This gateway doesn't support remote actions
		if(!method_exists($provider, 'ProcessRemoteActions')) {
			$tags[] = $this->MakeXMLTag('errorMsg', GetLang('ExpressCheckoutLoadError')."3");
			$this->SendXMLHeader();
			$this->SendXMLResponse($tags);
			exit;
		}

		$result = $provider->ProcessRemoteActions();
		$tags[] = $this->MakeXMLTag('errorMsg', $result['error']);
		$tags[] = $this->MakeXMLTag('data', isc_html_escape($result['data']));
		$this->SendXMLHeader();
		$this->SendXMLResponse($tags);
		exit;
	}

	private function sortAdvanceSearch()
	{
		if (!array_key_exists("section", $_REQUEST) || trim($_REQUEST["section"]) == "") {
			exit;
		}

		if (!array_key_exists("sortBy", $_REQUEST) || trim($_REQUEST["sortBy"]) == "") {
			exit;
		}

		$this->doAdvanceSearch();
	}


	/**
	*
	* @param int The customer group to use to determine the final product price (used when getting variation details from back end quote system)
	*/
	public function GetVariationOptions($customerGroupId = null)
	{
		$productId = (int)$_GET['productId'];
		$optionIds = $_GET['options'];
		$optionIdsArray = array_map('intval', explode(',', $optionIds));

		// We need to find the next type of option that's selectable, so what we do
		// is because the vcoptionids column is in the order that the customer selects
		// the options, we just find a single matching option and then look up values
		// according to the voname.

		$query = "
			SELECT prodvariationid, vnumoptions
			FROM [|PREFIX|]products p
			JOIN [|PREFIX|]product_variations v ON (v.variationid=p.prodvariationid)
			WHERE p.productid='".$productId."'
		";
		$result =$GLOBALS['ISC_CLASS_DB']->query($query);
		$product = $GLOBALS['ISC_CLASS_DB']->fetch($result);

		// Invalid product variation, or product doesn't have a variation
		if(empty($product)) {
			exit;
		}

		// If we received the number of options the variation has in, then the customer
		// has selected an entire row. Find that row.
		if(count($optionIdsArray) == $product['vnumoptions']) {
			$setMatches = array();
			foreach($optionIdsArray as $optionId) {
				$setMatches[] = 'FIND_IN_SET('.$optionId.', vcoptionids)';
			}
			$query = "
				SELECT *
				FROM [|PREFIX|]product_variation_combinations
				WHERE
					vcproductid='".$productId."' AND
					vcenabled=1 AND
					".implode(' AND ', $setMatches)."
				LIMIT 1
			";
			$result = $GLOBALS['ISC_CLASS_DB']->query($query);
			$combination = $GLOBALS['ISC_CLASS_DB']->fetch($result);

			$productClass = new ISC_PRODUCT($productId);
			$combinationDetails = $productClass->getCombinationDetails($combination, $customerGroupId);
			$combinationDetails['comboFound'] = true;

			if ($combinationDetails['sku'] == null) {
				// prevent a blank sku on details page
				$combinationDetails['sku'] = '';
			}

			echo isc_json_encode($combinationDetails);
			exit;
		}

		// Try to find a combination row with the incoming option ID string, to determine
		// which set of options is next.
		$query = "
			SELECT DISTINCT voname
			FROM [|PREFIX|]product_variation_options
			WHERE
				vovariationid='".$product['prodvariationid']."'
			ORDER BY vooptionsort ASC
			LIMIT ".count($optionIdsArray).", 1
		";
		$optionName = $GLOBALS['ISC_CLASS_DB']->fetchOne($query);

		$hasOptions = false;
		$valueHTML = '';

		$setMatches = array();
		foreach($optionIdsArray as $optionId) {
			$setMatches[] = 'FIND_IN_SET('.$optionId.', vcoptionids)';
		}

		$query = "
			SELECT *
			FROM [|PREFIX|]product_variation_options
			WHERE
				vovariationid='".$product['prodvariationid']."' AND
				voname='".$GLOBALS['ISC_CLASS_DB']->quote($optionName)."'
			ORDER BY vovaluesort ASC
		";
		$result = $GLOBALS['ISC_CLASS_DB']->query($query);
		while($option = $GLOBALS['ISC_CLASS_DB']->fetch($result)) {
			$a = "SELECT prodinvtrack FROM [|PREFIX|]products WHERE productid='".$productId."' ";
			$b = $GLOBALS['ISC_CLASS_DB']->Query($a);
			while($dados = $GLOBALS['ISC_CLASS_DB']->Fetch($b)) {
				$tipovar= $dados['prodinvtrack'];
                        }
			if ($tipovar ==2){//oculta variação não disponivel em estoque caso o item seja controlado por estoque na variação.
				$query = " SELECT combinationid FROM [|PREFIX|]product_variation_combinations	WHERE
					vcproductid='".$productId."' AND
					vcenabled=1 AND vcstock > 0 AND
					FIND_IN_SET(".$option['voptionid'].", vcoptionids) > 0 AND
					".implode(' AND ', $setMatches)." LIMIT 1";
			}else{
				$query = " SELECT combinationid FROM [|PREFIX|]product_variation_combinations	WHERE
					vcproductid='".$productId."' AND
					vcenabled=1 AND
					FIND_IN_SET(".$option['voptionid'].", vcoptionids) > 0 AND
					".implode(' AND ', $setMatches)." LIMIT 1";
			}
				
			// Ok, this variation option isn't in use for this product at the moment. Skip it
			if(!$GLOBALS['ISC_CLASS_DB']->fetchOne($query)) {
				continue;
			}

			$option = new Xhtml_Option($option['vovalue'], (int)$option['voptionid']);
			$valueHTML .= $option->render();
			$hasOptions = true;
		}

		$return = array(
			'hasOptions' 	=> $hasOptions,
			'options'		=> $valueHTML
		);

		echo isc_json_encode($return);
		exit;
	}



	/**
	* Updates the language file. Used by design mode
	*
	* @return void
	*/
	private function UpdateLanguage()
	{
		if(!getClass('ISC_ADMIN_AUTH')->isDesignModeAuthenticated()) {
			exit;
		}

		$name	= str_replace("lang_", "", $_REQUEST['LangName']);
		$value	= $_REQUEST['NewValue'];
		/*$value = str_replace(array("\n","\r"), "", $value);*/
		$value = str_replace('"', "&quot;", $value);

		$content = file_get_contents(ISC_BASE_PATH."/language/".GetConfig('Language')."/front_language.ini");
		$frontLang = parse_ini_file(ISC_BASE_PATH."/language/".GetConfig('Language')."/front_language.ini");

		$replacement = $name . ' = "' . str_replace('$', '\$', $value) . '"';
		$replace = preg_replace("#^\s*".preg_quote($name, "#")."\s*=\s*\"".preg_quote(@$frontLang[$name], "#").'"\s*$#im', $replacement, $content);

		if(file_put_contents(ISC_BASE_PATH."/language/".GetConfig('Language')."/front_language.ini", $replace)) {
			$tags[] = $this->MakeXMLTag('status',1);
			$tags[] = $this->MakeXMLTag('newvalue', $value, true);
		}else {
			$langFile = ISC_BASE_PATH.'/language/'.GetConfig('Language').'/admin/common.ini';
			ParseLangFile($langFile);
			$tags[] = $this->MakeXMLTag('status',0);
			$tags[] = $this->MakeXMLTag('message', GetLang('UpdateLanguage'));
		}

		$this->SendXMLHeader();
		$this->SendXMLResponse($tags);
		die();
	}
	public function getNewProducts($page = 1){
        $product = new PRODUCTS_PANEL();
        $GLOBALS['SNIPPETS']['HomeNewProducts'] = '';

        if (GetConfig('HomeNewProducts') <= 0) {
            $this->DontDisplay = true;
            return;
        }
        $GLOBALS['AlternateClass'] = '';
        if (!GetConfig('ShowProductRating')) {
            $GLOBALS['HideProductRating'] = "display: none";
        }
        $start = 0;
        $perPage = 4;

        if($page > 1){
            $start = $perPage * ($page-1);
        }

        $query = $product->getProductQuery('', 'proddateadded DESC', $perPage, $start);
        $result = $GLOBALS['ISC_CLASS_DB']->Query($query);
        $html = '<div class="infinite-container">';
        $countRows = 0;
        while ($row = $GLOBALS['ISC_CLASS_DB']->Fetch($result)) {
            $product->setProductGlobals($row);
            if (isId($row['prodvariationid']) || trim($row['prodconfigfields'])!='' || $row['prodeventdaterequired'] == 1) {
				$GLOBALS['MostrarBTN'] = 'display: block';
				$GLOBALS['MostrarForm'] = 'display: none';
			} else {
				$GLOBALS['MostrarBTN'] = 'display: none';
				$GLOBALS['MostrarForm'] = 'display: block';
			}
           $GLOBALS['ProN'] = simulador_de_rodape($row['productid']);
			$GLOBALS['ProNBoleto'] = simulador_home1($row['productid']);
            $html .= $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("HomeNewProductsItem");
            $countRows++;
        }
        if (!$GLOBALS['SNIPPETS']['HomeNewProducts']) {
            $this->DontDisplay = true;
        }

        // Showing the syndication option?
        if (GetConfig('RSSNewProducts') != 0 && GetConfig('RSSSyndicationIcons') != 0) {
            $GLOBALS['SNIPPETS']['HomeNewProductsFeed'] = $GLOBALS['ISC_CLASS_TEMPLATE']->GetSnippet("HomeNewProductsFeed");
        }
        $html .= '</div>';
        if($countRows == $perPage) {
            $html .= '<a class="infinite-more-link" href="remote.php?w=getnewproducts&page=' . ++$page . '"></a>';
        }
        echo $html;
        exit;
    }
}