<?php

require_once('common/common.php');

ob_start("callback");

require_once 'common/currency.php';
require_once 'classes/cwhois.php';
require_once 'modules/billing/fncInvoiceFunctions.php';

//Initialize Template//
if (isset($_GET['lang'])
    && file_exists(dirname(__FILE__).'/language/'.strtolower($_GET['lang']).'.txt'))
{
    $_SESSION['signupLanguage'] = $_GET['lang'];
}
if (isset($_SESSION['signupLanguage'])) {
    $GLOBALS['user']->setLanguage($_SESSION['signupLanguage']);
}
$tpl->setKey(array(
    'CHARSET'   => $gSettingsArray['Character Set'],
    'LANGUAGE'  => strtolower($GLOBALS['user']->getLanguage()),
    'VERSION'   => $GLOBALS['version'],
));
$ip = getRemoteAddr();
$tpl->assign('LOGGEDIP',$ip);
if($ip){
	$host = @gethostbyaddr($ip);
	$tpl->assign('LOGGEDHOST',$host);
}
$tpl->assign("CLIENTEXECURL",$gSettingsArray["ClientExec URL"]);
$tpl->assign(array("pageTitle" => $gSettingsArray["Title"]));
$tpl->assign("TEMPLATE",$gSettingsArray["Template"]);
$tpl->define(array( "signup_header" => "signup/signup_header.tpl"));
$tpl->define(array( "boxnosubmit"   => "signup/include/boxnosubmit.tpl"));
$tpl->define(array( "progress"      => "signup/include/progress.tpl"));
$tpl->define(array( "boxsubmit"     => "signup/include/boxsubmit.tpl"));
$tpl->define(array( "boxsearch"     => "signup/include/boxsearch.tpl"));
$tpl->define(array( "boxsubmitback" => "signup/include/boxsubmitback.tpl"));
$tpl->define(array( "boxsubmit1"    => "signup/include/boxsubmit.tpl"));
$tpl->define(array( "boxsearch1"    => "signup/include/boxsearch.tpl"));
$tpl->define(array( "boxsubmitback1"=> "signup/include/boxsubmitback.tpl"));
$tpl->define(array( "boxback"       => "signup/include/boxback.tpl"));
$tpl->define(array( "signup_footer" => "signup/signup_footer.tpl"));
$tpl->define(array( "form_hidden_inputs" => "../common/formhiddeninputs.tpl"));
$tpl->define(array( "formstep0"     => "signup/include/formstep0.tpl"));
$tpl->define(array("formstep1"      => "signup/include/formstep1.tpl"));
$tpl->define(array("formstep2"      => "signup/include/formstep2.tpl"));
$tpl->define(array("dropdown"       => "signup/include/dropdown.tpl"));
$tpl->define(array("options_step1"  => "signup/include/options_step1.tpl"));
$tpl->define(array("tables_step2"   => "signup/include/tables_step2.tpl"));
$tpl->define(array("tables2_step2"  => "signup/include/tables2_step2.tpl"));
$tpl->define(array("tables3_step2"  => "signup/include/tables3_step2.tpl"));
$tpl->define(array("tables4_step2"  => "signup/include/tables4_step2.tpl"));
$tpl->define(array("tables_step3"   => "signup/include/tables_step3.tpl"));
$tpl->define(array("custom_fields"  => "signup/include/custom_fields.tpl"));
$tpl->define(array("signupCheckDomain" => "../common/signupCheckDomain.js.tpl"));
$tpl->define(array("signupStepTwo"  => "../common/signupStepTwo.js.tpl"));
$tpl->define(array("noscript"       => "signup/include/noscript.tpl"));

// Add maxmind logo if ccfd or phone verification is on
$tpl->parse("HEADER", "signup_header");
if (($gSettingsArray['Enable MaxMind Fraud Control'] || $gSettingsArray['Enable MaxMind Telephone Verification']) && $gSettingsArray['Show MaxMind Logo']) {
    $tpl->parse('trash', 'maxmind');
}
$tpl->parse("FOOTER", "signup_footer");
//End Initiatize

//Get variables passed via URL
if (isset($_REQUEST['domain'])) $domain = strtolower($_REQUEST['domain']);
else  $domain = "";
$tpl->assign("DOMAIN",$domain);
if (isset($_REQUEST['step'])) $step = $_REQUEST['step'];
else  $step = "";
if (isset($_REQUEST['clienttype'])) $clienttype = $_REQUEST['clienttype'];
else  $clienttype = "";
if (isset($_REQUEST['package'])) $package = $_REQUEST['package'];
else  $package = 0;
if (isset($_REQUEST['transfer'])) $transfer = $_REQUEST['transfer'];
else  $transfer = "";
if (!isset($_REQUEST['paymentterm'])) $_REQUEST['paymentterm']=0;

// If no currency is passed use the default currency
if (!isset($_REQUEST['currency'])) {
    $_REQUEST['currency'] = $GLOBALS['gSettingsArray']['Default Currency'];
}

// make sure that the package isn't set to deny signups
if ($package > 0) {
    require_once 'classes/package.php';
    $myPackage = new Package($package);
    if ($myPackage->GetShow() == -1) redirectPage('signup.php');
}

// paypal subscriptions won't return properly to the thank you page, so we have to do this:
if (    isset($_SERVER['REQUEST_URI'])
        && (strpos($_SERVER['REQUEST_URI'], 'Access+Your+Subscription') !== false || strpos($_SERVER['REQUEST_URI'], 'Return+To+Merchant') !== false))
{
    $step = 6;
    $_REQUEST['pass'] = 1;
}

switch ($step) {
    case 0:
        if ($clienttype>0 || $package>0) {
             $_SESSION['AllowStep0'] = false;
             if($package>0 && $clienttype==0) {
                 if (!$clienttype = GetClientType($package)) {
                     redirectPage('signup.php');
                 }
             }
             if (tempJSCheck()) exit;
             $tpl->FastPrint('HEADER');  //Display Header
             StepOne($domain,$clienttype,$package,false);
        } else {
             if (tempJSCheck()) exit;
             $tpl->FastPrint('HEADER');  //Display Header
             $_SESSION['AllowStep0']=true;
             StepZero($domain,$clienttype,$package);
        }
        $tpl->FastPrint("FOOTER");  //Display Footer
        break;
    case 1:
        if (tempJSCheck()) exit;
        $tpl->FastPrint("HEADER");  //Display Header
        StepOne($domain,$clienttype,$package);
        $tpl->FastPrint("FOOTER");  //Display Footer
        break;
    case 2:
        if (tempJSCheck()) exit;
        $tpl->FastPrint("HEADER");  //Display Header
        StepTwo($domain,$clienttype,$package,$transfer);  
        $tpl->FastPrint("FOOTER");  //Display Footer
        break;
    case 3:
        StepThree($domain);
        break;
    case 4:
        $fraudmsg = "";
        if(isset($_REQUEST['fraudmsg'])) $fraudmsg = $_REQUEST['fraudmsg'];
        StepFour($domain,$fraudmsg);
        break;
    case 5:
        //No header
        StepFive();
        break;
    case 6:
        $tPass=1;
        if ($_REQUEST['pass']==0) $tPass=0;
        $tpl->FastPrint("HEADER");  //Display Header
        StepSix($tPass);
        $tpl->FastPrint("FOOTER");  //Display Footer
        break;
    case 7:
        $fraudmsg = '';
        if(isset($_REQUEST['fraudmsg'])) {
            $fraudmsg = $_REQUEST['fraudmsg'];
        }
        PreStepFour($fraudmsg);
        $tpl->FastPrint("FOOTER");
        break;
}

function ShowProgress($description,$percentage)
{
    global $tpl;
    $tpl->assign("PROGRESSPERCENTAGE",$percentage);
    $tpl->assign("PROGRESSDESCRIPTION",$description);
    $tpl->parse("PROGRESS", "progress");
    $tpl->FastPrint("PROGRESS");
}



//**************************************************************************************
// StepZero
// Show ClientPackage Selection.
// If there is only one package type then move to step 1
//**************************************************************************************
function StepZero($domain,$clienttype = 0, $package = 0,$showbanner = false, $isduplicate = false)
{
    global $tpl;
    global $gSettingsArray;

    if (isset($_REQUEST['currency'])) {
        $tCurrency = $_REQUEST['currency'];
    } else {
        $tCurrency = "";
    }

    $tpl->assign("CLIENTTYPE",$clienttype);
    $tpl->assign("CURRENCY",$tCurrency);
    $tpl->assign("DOMAIN",$domain);

    if ($package > 0) {
        $tpl->assign("INPUTNAME","package");
        $tpl->assign("INPUTVALUE",$package);
        $tpl->parse("FORM_INPUTS", "form_hidden_inputs");
    }

    if ($clienttype == 0 && $package == 0) {
        //First Time through step 0
        require_once 'classes/PackageTypeGateway.php';
        $packageTypes = PackageTypeGateway::getDefaultPackageTypes();
        $plancount = $packageTypes->getNumItems();

        //might change to >1 in the event that I want to automatically forward to the next section
        if ($plancount > 0) {
            ShowProgress(lang('Select hosting type.'),25);
        }

        $count=0;
        $row = 0;

        //Loop through all the packagetypes
        while($packageType = $packageTypes->fetch()) {
            $row++;
            $tpl->assign("SUBMITFUNCTION","SubmitStepZero");
            $tpl->assign("SIZEOFBOX","115");
            $tpl->assign("WIDTHOFBOX","326");
            $tpl->assign("INPUTNAME","clienttype");
            $tpl->assign("INPUTVALUE", $packageType->getId());
            $tpl->assign("SIGNUPBLOCKDESCRIPTION",$packageType->getName());
            $tpl->assign("SIGNUPBLOCKCONTENT",$packageType->getDescription());
            $tpl->parse("BOXSUBMIT", "boxsubmit");
            $tpl->parse("TD_STEP0", ".td_step0");
            if (++$count == 2 || $row == $plancount) { //if true add tr
                $tpl->parse("TR_STEP0", ".tr_step0");
                $tpl->clear_dynamic("td_step0");
                $count = 0;
            }
        }//end while loop

        $tpl->parse("TABLES_STEP0", "tables_step0");
    }

    $tpl->parse("FORMSTEP0", "formstep0");
    $tpl->FastPrint("FORMSTEP0");
}

function StepOne($domain = '', $clienttype = 0, $package = 0, $bolAllowBack = false)  // Domain was passed
{
    require_once 'classes/PackageType.php';
    global $gSettingsArray,$tpl;

    //check to see if clienttype accepts domain functionality
    $packageType = new PackageType($clienttype);
    if (!$packageType->isRegDomain()) {
        $_SESSION['AllowStep1']=false;
        //This clienttype does not support domain functions
        //forward to next step
        StepTwo($domain, $clienttype, $package, 0);
    } else {
        $_SESSION['AllowStep1']=true;
        //call class for JS RPC
        include_once("common/jsrsServer.php");
        //jsfunction to check domain availability
        if ($packageType->allowReg()) {
            $tpl->parse("ALLOWREG", "allowreg");
            $tpl->parse("ALLOWREG1", "allowreg1");
            $tpl->parse("ALLOWREG2", "allowreg2");
            $tpl->parse("ALLOWREG3", "allowreg3");
            $tpl->parse("ALLOWREG4", "allowreg4");
            $tpl->parse("ALLOWREG5", "allowreg5");
            $tpl->parse("ALLOWREG6", "allowreg6");
            $tpl->parse("ALLOWREG7", "allowreg7");
            $tpl->parse("ALLOWREG8", "allowreg8");
        }
        if ($packageType->allowTransfer()) {
            $tpl->parse("ALLOWTRANSFER", "allowtransfer");
            $tpl->parse("ALLOWTRANSFER1", "allowtransfer1");
            $tpl->parse("ALLOWTRANSFER2", "allowtransfer2");
            if ($packageType->allowSelfManage()) {
                $tpl->parse("ALLOWSELFMANAGE3", "allowselfmanage3");
            }
            $tpl->parse("ALLOWTRANSFER3", "allowtransfer3");
            $tpl->parse("ALLOWTRANSFER4", "allowtransfer4");
            $tpl->parse("ALLOWTRANSFER5", "allowtransfer5");
            $tpl->parse("ALLOWTRANSFER6", "allowtransfer6");
            $tpl->parse("ALLOWTRANSFER7", "allowtransfer7");
            $tpl->parse("ALLOWTRANSFER8", "allowtransfer8");
            $tpl->parse("ALLOWTRANSFER9", "allowtransfer9");
        }
        if ($packageType->allowSelfManage()) {
            $tpl->parse("ALLOWSELFMANAGE", "allowselfmanage");
            $tpl->parse("ALLOWSELFMANAGE1", "allowselfmanage1");
            if (!$packageType->allowReg()) {
                $tpl->parse("ALLOWSELFMANAGE2b", "allowselfmanage2b");
                $tpl->parse("ALLOWSELFMANAGE4", "allowselfmanage4");
            } else {
                $tpl->parse("ALLOWSELFMANAGE2", "allowselfmanage2");
            }
            $tpl->parse("ALLOWSELFMANAGE5", "allowselfmanage5");
            $tpl->parse("ALLOWSELFMANAGE6", "allowselfmanage6");
            $tpl->parse("ALLOWSELFMANAGE7", "allowselfmanage7");
            $tpl->parse("ALLOWSELFMANAGE8", "allowselfmanage8");
            $tpl->parse("ALLOWSELFMANAGE9", "allowselfmanage9");
            $tpl->parse("ALLOWSELFMANAGE10", "allowselfmanage10");
            $tpl->parse("ALLOWSELFMANAGE10", "allowselfmanage11");
        }
        $tpl->assign("ERROR", lang("Error"));
        $tpl->assign('FUSE_CLIENTS', cCLIENTS);
        $tpl->assign('ACTION_CHECKDOMAIN', cCLIENTS_CHECKDOMAIN);
        $tpl->assign('ACTION_CHECKDOMAINEXISTS', cCLIENTS_CHECKDOMAINEXISTS);
        $tpl->assign("COMPANYNAME", $gSettingsArray['Company Name']);
        $tpl->assign("MAINDOMAIN", $packageType->getMainDomain());

        if ($packageType->allowTransfer() || $packageType->allowSelfManage()) {
            $tpl->parse("ALLOWSELFMANAGETRANSFER", "allowselfmanagetransfer");
        }

        //Get list of supported domains
        //Also populate strpopup to be used to show supported domains

        $query="SELECT DISTINCT(name) FROM tld";
        $result = $GLOBALS['db']->query($query);
        $strPopUp = "";
        $jsArraySupportedDomains = "";

        while(list($tldname) = $result->fetch()) {
            $strPopUp .= " .".$tldname. ",";
            $jsArraySupportedDomains .= "'".$tldname."',";
        }

        $jsArraySupportedDomains = substr($jsArraySupportedDomains,0,strlen($jsArraySupportedDomains)-1);
        $strPopUp = substr($strPopUp,0,strlen($strPopUp)-1);
        $tpl->assign("JSARRAYSUPPORTEDDOMAINS", $jsArraySupportedDomains);
        $tpl->assign('REGEXDOMAIN', DOMAIN_REGEXDOMAIN);
        $tpl->assign('REGEXSUBDOMAIN', DOMAIN_REGEXSUBDOMAIN);
        $tpl->assign("STRPOPUP", $strPopUp);
        $tpl->parse("SIGNUPCHECKDOMAIN", "signupCheckDomain");
        $tpl->FastPrint("SIGNUPCHECKDOMAIN");

        ShowProgress(lang('Select domain.'),50);

        $tpl->assign("CLIENTTYPE",$clienttype);
        $tpl->assign("CURRENCY",@$_REQUEST['currency']);
        $tpl->assign("DOMAIN",$domain);
        $tpl->assign("PACKAGE", @$_REQUEST['package']);

        $tpl->assign("SIZEOFBOX","70");
        $tpl->define_dynamic('searchBtn', 'boxsearch');
        $tpl->assign("INPUTVALUE","");
        $tpl->assign("INPUTNAME","subdomaincheck");

        if (!$packageType->isSub()) {
             $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang('Enter Your Domain Name.'));
             if ($packageType->allowReg()) {
                $tpl->parse("DROPDOWNONCHANGE",'dropdown_onchange');
            }
            $tpl->parse("DROPDOWN1","dropdown1");
            $tpl->parse("SIGNUPBLOCKCONTENT","dropdown");
        } else {
            $tpl->assign("MAINDOMAIN",$packageType->getMainDomain());
            $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang("Enter Your Subdomain."));
            $tpl->parse("DROPDOWN1","dropdown2");
            $tpl->parse("SIGNUPBLOCKCONTENT","dropdown");
        }

        //only show search if we are allowing one of the registration methods
        //and we are not showing subdomain option
        if ((!$packageType->allowReg() && !$packageType->allowTransfer() && !$packageType->allowSelfManage()) || $packageType->isSub()) {
            $tpl->assign("WIDTHOFBOX","400");
            if($packageType->isSub()) {
                $tpl->assign("SUBMITFUNCTION","SubmitStep2c");
            } else {
                $tpl->assign("SUBMITFUNCTION","SubmitStep2b");
            }
            $tpl->assign("INPUTNAME","transfer");
            $tpl->assign("INPUTVALUE",2);
            $tpl->parse("FORM_INPUTS", "form_hidden_inputs");

            if ($_SESSION['AllowStep0']==true){
                $tpl->assign("BACKFUNCTION","BackStepOne");
                $tpl->assign("BACKINPUTNAME","back");
                $tpl->assign("BACKINPUTVALUE","1");
                $tpl->parse("BOXSUBMIT", "boxsubmitback");
            } else {
                 $tpl->parse("BOXSUBMIT", "boxsubmit");
            }
        } else {
            $tpl->assign("WIDTHOFBOX","326");
            $tpl->assign("SUBMITFUNCTION","CheckDomain");
            $tpl->subst('trash', 'searchBtn');
            $tpl->parse("BOXSUBMIT", "boxsearch");
        }

        $tpl->assign("SUBMITFUNCTION","SubmitStep2");
        $tpl->assign("SIZEOFBOX","200");
        $tpl->assign("WIDTHOFBOX","326");
        $tpl->assign("INPUTVALUE","");
        $tpl->assign("INPUTNAME","submitdomainplan");
        $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang('Choose Domain Plan'));

        $tpl->clear("SIGNUPBLOCKCONTENT");
        //Check to see if registration is allowed
        if ($packageType->allowReg()) {
            //build options for domain registration
            $tpl->assign("OPTIONSTEP1ID", 1);
            $tpl->assign("OPTIONSTEP1VALUE", 0);
            $tpl->assign("DOMAINACTION", lang('Register Domain'));
            $tpl->assign("DOMAINACTIONDESCRIPTION", lang('The domain will be registered on your behalf and directed to your new account with %s. Your domain registration will automatically renew.', $gSettingsArray['Company Name']));
            $tpl->parse("SIGNUPBLOCKCONTENT", ".options_step1");
        }
        if ($packageType->allowTransfer()) {
            $tpl->assign("OPTIONSTEP1ID", 2);
            $tpl->assign("OPTIONSTEP1VALUE", 1);
            $tpl->assign("DOMAINACTION", lang('Transfer My Domain To You'));
            $tpl->assign("DOMAINACTIONDESCRIPTION", lang('Select this option if you would like to make %s your registrar for your existing domain.', $gSettingsArray['Company Name']));
            $tpl->parse("SIGNUPBLOCKCONTENT", ".options_step1");
        }

        if ($packageType->allowSelfManage()) {
            $tpl->assign("OPTIONSTEP1ID",3);
            $tpl->assign("OPTIONSTEP1VALUE",2);
            $tpl->assign("DOMAINACTION", lang('Self-Management (no cost)'));
            $tpl->assign("DOMAINACTIONDESCRIPTION", lang('Select this option if you prefer to handle your registration manually. %s can establish service with any Top-Level Domain (TLD), international or domestic.', $gSettingsArray['Company Name']));
            $tpl->parse("SIGNUPBLOCKCONTENT", ".options_step1");
        }


        if (@$_SESSION['AllowStep0'] == true) {
            $tpl->assign("BACKFUNCTION","BackStepOne");
            $tpl->assign("BACKINPUTNAME","back");
            $tpl->assign("BACKINPUTVALUE","1");
            $tpl->parse("BOXSUBMIT1", "boxsubmitback1");
        } else {
             $tpl->parse("BOXSUBMIT1", "boxsubmit1");
        }
        if ($packageType->isSub()) {
            $tpl->parse("DIVDOMAINWINDOW1","divdomainwindow1");
        } else {
            $tpl->parse("DIVDOMAINWINDOW2","divdomainwindow2");
        }

        //only show registration option if not showing subdomain option and one of the registration options is available
        if (($packageType->allowReg() || $packageType->allowTransfer() || $packageType->allowSelfManage()) && !$packageType->isSub()) {
            $tpl->parse("DOMAINOPTIONS","domainoptions");
        }
        $tpl->parse("FORMSTEP1","formstep1");
        $tpl->FastPrint("FORMSTEP1");
    }
}

function StepTwo($domain, $clienttype, $package, $transfer, $fielderror = '', $billingerror = '')
{
    global $gSettingsArray,$tpl,$arrCustomFields;
    global $bolCountryPresent;

    require_once 'classes/class.PluginInterface.php';
    $plugins = new PluginInterface("plugins/gateways/",array("variables"));
    $plugin_names = $plugins->getFoundPluginNames();

    $bolCountryPresent=false;
    //check to see if currency was passed or not
    if (!isset($_REQUEST['currency'])) {
        $_REQUEST['currency'] = $gSettingsArray['Default Currency'];
    }
    if ($transfer == 1) {
        $transfer=true;
    } else {
        $transfer=false;
    }
    $intColorIndex=1;
    $arrCustomFields = array();
    require_once 'common/jsrsServer.php';
    //Set the saved package to the package passed if it is the first time
    if (!isset($_REQUEST['oldpackage'])) {
        $_REQUEST['oldpackage'] = $package;
    }
    //New customer form
    $tpl->assign('FUSE_CLIENTS', cCLIENTS);
    $tpl->assign('ACTION_VALIDATECOUPON', cCLIENTS_VALIDATECOUPON);
    $tpl->assign('ACTION_GETTAX', cCLIENTS_GETTAX);
    $tpl->assign('ACTION_CONFIRMLOGIN', cCLIENTS_CONFIRMLOGIN);
    if (@$_SESSION['AllowStep1'] == true) {
        $tpl->parse("ALLOWSTEP1","allowstep1");
    } else {
        $tpl->parse("NOTALLOWSTEP1","notallowstep1");
    }
    $tpl->parse("SIGNUPSTEPTWO", "signupStepTwo");
    $tpl->FastPrint("SIGNUPSTEPTWO");

    ShowProgress(lang("Account Information"),75);
    $tpl->assign("CLIENTTYPE",$clienttype);
    $tpl->assign("DOMAIN",$domain);
    $tpl->assign("TRANSFER",isset($_REQUEST['transfer'])? $_REQUEST['transfer'] : '');
    //if error from previous order show in seperate box
    if (is_array($fielderror)) {
        foreach($fielderror as $key => $value) {
            $tpl->assign("STRERRORHTMLVALUE", $value);
            $tpl->parse("STRERRORHTMLVALUE", ".strerrorhtmlvalue");
        }
        $tpl->parse("STRERRORHTML","strerrorhtml");

        //Start Error Block
        $tpl->assign("SIZEOFBOX","40");
        $tpl->assign("WIDTHOFBOX","570");
        $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang("Signup Error"));
        $tpl->assign("SIGNUPBLOCKRIGHTTEXT","");
        $tpl->parse("BOXNOSUBMIT","boxnosubmit");
        $tpl->FastPrint("BOXNOSUBMIT");
        $tpl->clear_dynamic("strerrorhtml");
    }

    //********************************************************
    //***  START POPULATION PACKAGE INFO BOX
    //********************************************************
    if ($package != 0) {
        $clienttype = GetClientType($package);
        $query = "select id,planname,description,price,price3,price6,price12,price1included,price3included,price6included,price12included,setup,planid,taxable from package where (planid=? and showpackage=1) or (id=?) order by price,id";
        $result = $GLOBALS['db']->query($query, $clienttype, $package);
    } else {
        $query = "select id,planname,description,price,price3,price6,price12,price1included,price3included,price6included,price12included,setup,planid,taxable from package where planid=? and showpackage=1 order by price,id";
        $result = $GLOBALS['db']->query($query, $clienttype);
    }
    $bolFirst = true;
    while(list($tID,$tPlanName,$tDescription,$tPrice,$tPrice3,$tPrice6,$tPrice12,$tPrice1included,$tPrice3included,$tPrice6included,$tPrice12included,$tSetup,$clienttype,$taxable) = $result->fetch()) {
        if(($bolFirst) || ($package==$tID)) {
            $firstPackage = $tPlanName;
            if ($package == 0) {
                $package = $tID;
            }
            $firstTaxable   = $taxable;
            $firstPrice     = $tPrice;
            $firstDescription = $tDescription;
            $firstPrice3    = $tPrice3;
            $firstPrice6    = $tPrice6;
            $firstPrice12   = $tPrice12;
            $firstPrice1included = $tPrice1included;
            $firstPrice3included = $tPrice3included;
            $firstPrice6included = $tPrice6included;
            $firstPrice12included= $tPrice12included;
            $firstSetup     = $tSetup;
            $firstClientType= $clienttype;
            $bolFirst       = false;
        }
        $tpl->assign("TID",$tID);
        $tpl->assign("TPLANNAME",$tPlanName);
        if ($package == $tID) {
            $tpl->assign("SELECTED","selected");
        } else {
            $tpl->assign("SELECTED","");
        }
        $tpl->parse("PACKAGEOPTIONS",".packageoptions");
    }

    $tDescription       = @$firstDescription;
    $tPrice1included    = @$firstPrice1included;
    $tPrice3included    = @$firstPrice3included;
    $tPrice6included    = @$firstPrice6included;
    $tPrice12included   = @$firstPrice12included;
    $tPlanName          = @$firstPackage;
    $tSetup             = @$firstSetup;
    $tTaxable           = @$firstTaxable;
    $clienttype         = @$firstClientType;

    $tpl->assign("OLDPACKAGE",$package);
    if ($package!=$_REQUEST['oldpackage']) {
        $_REQUEST['paymentterm']=0;
    }
    if ($tDescription != '') {
        $tpl->assign("TDESCRIPTION", $tDescription);
        $tpl->parse("PACKAGEDESCRIPTION","packagedescription");
    }
    //set the proper payment term
    if ($_REQUEST['paymentterm'] == 0) {
        if ($tPrice1included == 1) {
            $_REQUEST['paymentterm'] = 1;
        } elseif ($tPrice3included == 1) {
            $_REQUEST['paymentterm'] = 3;
        } elseif ($tPrice6included == 1) {
            $_REQUEST['paymentterm'] = 6;
        } elseif ($tPrice12included == 1) {
            $_REQUEST['paymentterm'] = 12;
        }
    }
    //check to see if maybe no terms were set
    //to be visable in the signup
    if ($_REQUEST['paymentterm'] != 0) {
        //Show dropdown list of available payment terms

        $strBillingCycle=GetMonthLabel($_REQUEST['paymentterm']);
        if ($tPrice1included == 1) {
            $selected = '';
            if (!strcmp(1, $_REQUEST['paymentterm'])) {
                $tPrice = $firstPrice;
                $selected = "selected";
            }
            $tpl->assign("PAYMENTTERMSELECTED", $selected);
            $tpl->assign("PAYMENTTERM", lang("Monthly"));
            $tpl->assign("PAYMENTTERMOPTIONVALUE", 1);
            $tpl->parse("OPTIONSPAYMENTTERM", ".optionspaymentterm");
        }
        if ($tPrice3included == 1) {
            $selected = '';
            if (!strcmp(3, $_REQUEST['paymentterm'])) {
                $tPrice = $firstPrice3;
                $selected = "selected";
            }
            $tpl->assign("PAYMENTTERMSELECTED", $selected);
            $tpl->assign("PAYMENTTERM", lang("Quarterly"));
            $tpl->assign("PAYMENTTERMOPTIONVALUE", 3);
            $tpl->parse("OPTIONSPAYMENTTERM", ".optionspaymentterm");
        }
        if ($tPrice6included == 1) {
            $selected = '';
            if (!strcmp(6, $_REQUEST['paymentterm'])) {
                $tPrice = $firstPrice6;
                $selected = "selected";
            }
            $tpl->assign("PAYMENTTERMSELECTED", $selected);
            $tpl->assign("PAYMENTTERM", lang("Semiannually"));
            $tpl->assign("PAYMENTTERMOPTIONVALUE", 6);
            $tpl->parse("OPTIONSPAYMENTTERM", ".optionspaymentterm");
        }
        if ($tPrice12included == 1) {
            $selected = '';
            if (!strcmp(12, $_REQUEST['paymentterm'])) {
                $tPrice = $firstPrice12;
                $selected = "selected";
            }
            $tpl->assign("PAYMENTTERMSELECTED", $selected);
            $tpl->assign("PAYMENTTERM", lang("Annually"));
            $tpl->assign("PAYMENTTERMOPTIONVALUE", 12);
            $tpl->parse("OPTIONSPAYMENTTERM", ".optionspaymentterm");
        }
        if ($_REQUEST['paymentterm'] > 1 && $gSettingsArray['Include Saved Percentage'] == 1  && $firstPrice > 0) {
            $saved = $firstPrice - $tPrice / $_REQUEST['paymentterm'];
            $saved = $saved / $firstPrice * 100;
            if ($saved > 0.0) {
                $tpl->assign("YOUSAVE", lang("You save")." ".sprintf("%01.2f", $saved));
                $tpl->parse("SAVEDPAYMENTTERM", "savedpaymentterm");
            }
        }
        $tpl->parse("PAYMENTTERM","paymentterm");
    }  // If no terms were set to show on signup
    //END PACKAGE SELECTION
    //If domain was passed then show domain information
    if ($domain != '') {
        $tpl->assign("DOMAIN", $domain);
        $domainaction = "";
        if (@$_REQUEST['transfer'] == 1) {
            $domainaction = "- " .lang('Transfer');
        } elseif (@$_REQUEST['transfer'] == 0) {
            $domainaction = "- " .lang("Register");
        }
        $tpl->assign("DOMAINACTION", $domainaction);

        //Only show TLD information if it isn't a transfer
        if (@$_REQUEST['transfer'] == 0 || @$_REQUEST['transfer'] == 1) {
            //Add Domain Regisration Length
            //Get all prices for years for this tld
            $tld = substr(strstr($domain, '.'),1);
            $sqlGetTLDPrices = "SELECT price,period,transferprice FROM tld WHERE name=? ORDER BY period ASC";
            $tldResult = $GLOBALS['db']->query($sqlGetTLDPrices, $tld);
            $bolFirst=true;
            while(list($tTLDPrice,$tPeriod,$tTransferPrice) = $tldResult->fetch()) {
                if ($bolFirst) {
                    $selDomainPrice = $tTLDPrice;
                }
                if ($tPeriod==1) {
                    $strYear = lang("Year");
                } else {
                    $strYear = lang("Years");
                }

                //Format Price
                if (@$_REQUEST['transfer'] == 1) {
                    $tFormattedPrice = ShowCurrencySymbol($_REQUEST['currency'],false).sprintf("%01.2f", $tTransferPrice);
                } else {
                    $tFormattedPrice = ShowCurrencySymbol($_REQUEST['currency'],false).sprintf("%01.2f", $tTLDPrice);
                }

                //Change text for one time domain payments
                if ($tPeriod == 0) {
                    $tText= lang("One time payment of ") .$tFormattedPrice;
                } else {
                    $tText= "$tPeriod $strYear ".lang("for")." $tFormattedPrice";
                }

                if (isset($_REQUEST['domainperiod']) && ($_REQUEST['domainperiod'] == "$tPeriod|$tTLDPrice")) {
                    $selDomainPrice = $tTLDPrice;
                    $tpl->assign("TLDINFOOPTIONSELECTED","selected");
                } else {
                    $tpl->assign("TLDINFOOPTIONSELECTED","");
                }
                if (@$_REQUEST['transfer'] == 1) {
                    $tpl->assign("TLDINFOOPTIONVALUE", "$tPeriod|$tTransferPrice");
                } else {
                    $tpl->assign("TLDINFOOPTIONVALUE", "$tPeriod|$tTLDPrice");
                }
                $tpl->assign("TTEXT","$tText");
                $bolFirst=false;
                $tpl->parse("TLDINFOOPTIONS", ".tldinfooptions");
            }
            $tpl->parse("TLDINFO", "tldinfo");
            //End build year options

            // tld extended attributes
            $pluginsRegistrar = new PluginInterface("plugins/registrars",array('variables'));
            $pluginNames = $pluginsRegistrar->getFoundPluginNames();
            foreach ($pluginNames as $pluginName) {
                if (@$GLOBALS['gSettingsArray']["plugin_{$pluginName}_Use ".ucfirst($pluginName)." to check and register domains"]) {
                    if (!$response = getExtraAttributes($pluginName, $tld)) {
                        continue;
                    }

                    $tpl->define_dynamic(array('tld_extended_attributes', 'domainpassed'));
                    $tpl->define_dynamic(array('tld_extended_attributes_select', 'tld_extended_attributes'));
                    $tpl->define_dynamic(array('tld_extended_attributes_options', 'tld_extended_attributes_select'));
                    $tpl->define_dynamic(array('tld_extended_attributes_inputbox', 'tld_extended_attributes'));
                    $tag1 = 'tld_extended_attributes';
                    foreach ($response as $name => $values) {
                        $tpl->assign('EXT_ATTR_LABEL', $values['description']);
                        $tag2 = 'tld_extended_attributes_options';
                        if ($values['popup']) {
                            $tpl->assign('REQUIREDNOTE', ReturnPopUpString($values['popup']));
                        }
                        if (@$values['options']) {
                            $tpl->clear_dynamic('tld_extended_attributes_select');
                            $tpl->clear_dynamic('tld_extended_attributes_inputbox');
                            $tpl->assign('EXT_ATTR_SELECT_NAME', $name);
                            foreach ($values['options'] as $label => $details) {
                                $tpl->assign('EXT_ATTR_OPTION_VALUE', $details['value']);
                                $tpl->assign('EXT_ATTR_OPTION_LABEL', $label);
                                $tpl->parse('TLD_EXTENDED_ATTRIBUTES_OPTIONS', $tag2);
                                $tag2 = '.tld_extended_attributes_options';
                            }
                            $tpl->parse('TLD_EXTENDED_ATTRIBUTES_SELECT', 'tld_extended_attributes_select');
                        } else {
                            $tpl->clear_dynamic('tld_extended_attributes_select');
                            $tpl->clear_dynamic('tld_extended_attributes_inputbox');
                            $tpl->assign('EXT_ATTR_INPUTBOX_NAME', $name);
                            $tpl->parse('TLD_EXTENDED_ATTRIBUTES_INPUTBOX', 'tld_extended_attributes_inputbox');
                        }
                        $tpl->parse('TLD_EXTENDED_ATTRIBUTES', $tag1);
                        $tag1 = '.tld_extended_attributes';
                    }
                    break;  // use first registrar found
                }
            }
        }
        require_once 'classes/PackageType.php';
        $packageType = new PackageType($clienttype);
	if ($packageType->isRegDomain()) {        
        	$tpl->parse("DOMAINPASSED", "domainpassed");
        }
    }

    //Display Package Custom Fields
    $tpl->assign("DISPLAYPACKAGECUSTOMFIELDS", DisplayCustomFields("Package"));
    $tpl->assign("SIZEOFBOX","40");
    $tpl->assign("WIDTHOFBOX","570");
    $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang("Package Information"));
    $tpl->parse("SIGNUPBLOCKCONTENT","tables_step2");
    $tpl->assign("SIGNUPBLOCKRIGHTTEXT","");
    $tpl->parse("BOXNOSUBMIT1", "boxnosubmit");
    $tpl->parse("PACKAGECUSTOMFIELDS", "packagecustomfields");

    // package addons
    require_once 'classes/packageaddongateway.php';
    $tpl->define(array('addons' => 'signup/include/addons.tpl'));
    $selectedAddons = array();
    if (isset($_GET['addonids'])) {
        $selectedAddons = explode(',', $_GET['addonids']);
    } elseif (isset($_POST['addonChargesStr'])) {
        $selectedAddons = array_keys(_getPriceIds($_POST['addonChargesStr']));
    }
    $addons = PackageAddonGateway::getPackageAddons($package);
    $thereArePackageAddons = false;
    $cycleLang = array(
        1   => lang('monthly'),
        3   => lang('quarterly'),
        6   => lang('semiannually'),
        12  => lang('annually'),
    );
    while ($addon = $addons->fetch()) {
        $thereArePackageAddons = true;
        $tpl->setKey(array(
            'ADDON_DESCRIPTION' => $addon->getDescription(),
            'ADDON_ID'          => $addon->getId(),
        ));

        $lastid = null;
        foreach ($addon->getCyclePrices($_REQUEST['paymentterm']) as $price) {
            $priceOption = $price['detail'];
            if (isset($price['setupFee'])) {
                $priceOption .= ': ' . showCurrencySymbol($_REQUEST['currency'],false).$price['setupFee'].' '.lang('one time fee');
            }
            if (isset($price['cycleFee'])) {
                if (isset($price['setupFee'])) {
                    $priceOption .= ' '.lang('+').' ';
                } else {
                    $priceOption .= ': ';
                }
                $priceOption .= showCurrencySymbol($_REQUEST['currency'],false)."{$price['cycleFee']} ".$cycleLang[$price['cycle']];
            }
            $tpl->setKey(array(
                'ADDON_PRICE_ID'                => $price['id'],
                'ADDON_PRICE'                   => $priceOption,
                'ADDON_PRICE_FLOAT'             => sprintf("%01.2f", $price['cycleFee']),
                'ADDON_PRICE_SELECTED'          => in_array($price['id'], $selectedAddons)? 'selected="true"' : '',
                'ADDON_RECURRINGPRICE_CYCLE'    => $price['cycle'],
                'ADDON_SETUPPRICE_VALUE'        => sprintf("%01.2f", (isset($price['setupFee']) && $price['setupFee'] > 0)? $price['setupFee'] : 0),
            ));

            // prorating for package addons
            list($tAddonPrice, $addonProratedPrice, $addonProratedDays, $addonProIncFollowing, $addonTmpNextBill, $addonProNextBill)
            = processProrating($gSettingsArray['Prorate To Day'], $gSettingsArray['Include Following Payment'], $price['cycle'], $price['cycleFee']);
            if ($_REQUEST['paymentterm'] != 0) {
                $tpl->setKey('ADDON_PRICE_FLOAT_PRORATED', $addonProratedPrice);
            } else {
                $tpl->setKey('ADDON_PRICE_FLOAT_PRORATED', 0);
            }

            // Ensure we don't reinitialize the price array if it already exists
            if ($lastid != $price['id']) {
                $tpl->parse('PACKAGEADDONPRICES', '.packageAddonsPriceItemInit');
                $lastid = $price['id'];
            }

            $tpl->parse('PACKAGEADDONSPRICES', '.packageAddonsPriceArrItemCycle');
            $tpl->parse('PACKAGEADDONSPRICES', '.packageAddonsPrices');

            $tpl->parse('PACKAGEADDONSPRICES', '.packageAddonsPriceArrItem');
            $tpl->clear_dynamic('packageAddonsPriceArrItemCycle');
            $tpl->clear_dynamic('packageAddonsPriceItemInit');
        }
        $tpl->parse('PACKAGEADDONSROW', '.packageAddonsRow');
        $tpl->parse('PACKAGEADDONSPRICEARR', '.packageAddonsPriceArr');
        $tpl->clear_dynamic('packageAddonsPrices');
        $tpl->clear_dynamic('packageAddonsPriceArrItem');
    }

    if ($thereArePackageAddons) {
        $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang("Package Add-ons"));
        $tpl->parse("SIGNUPBLOCKCONTENT","addons");
        $tpl->assign("SIZEOFBOX","20");
        $tpl->assign("WIDTHOFBOX","570");
        $tpl->parse("BOXNOSUBMIT12", "boxnosubmit");
        $tpl->parse("PACKAGEADDONS", "packageAddons");
    }
//End package information

//Sart billing info
    if (isset($_REQUEST['member']) && $_REQUEST['member'] == 'on') {
        $billingblockmember_style = '';
        $billingblock_style = 'none';
    } else {
        $billingblockmember_style = 'none';
        $billingblock_style = '';
    }
    //javascript for credit card
    $arraycount = 0;
    $tmpstr = '';
    while (list($key, $val) = each($plugin_names)) {
        if (@$gSettingsArray["plugin_".$val."_Accept CC Number"] == 1) {
          $tmpstr .= "'$val',";
          $pluginarray[] = $val;
          $arraycount++;
        }
    }
    $tmpstr = substr($tmpstr,0,strlen($tmpstr)-1);
    $tpl->assign("VALIDPLUGINSFORCC", $tmpstr);


    $strAvailableCCArray  =  "pluginsforcc = new Array($arraycount);\n";
    for ($x = 0; $x < $arraycount; $x++) {
          $strAvailableCCArray .= "pluginsforcc['".$pluginarray[$x]."'] = new Array(4);\n";
          $strAvailableCCArray .= "pluginsforcc['".$pluginarray[$x]."'][".cCREDITVISA."] = ".$gSettingsArray["plugin_".$pluginarray[$x]."_Visa"].";\n";
          $strAvailableCCArray .= "pluginsforcc['".$pluginarray[$x]."'][".cCREDITMC."] = ".$gSettingsArray["plugin_".$pluginarray[$x]."_MasterCard"].";\n";
          $strAvailableCCArray .= "pluginsforcc['".$pluginarray[$x]."'][".cCREDITAMEX."] = ".$gSettingsArray["plugin_".$pluginarray[$x]."_AmericanExpress"].";\n";
          $strAvailableCCArray .= "pluginsforcc['".$pluginarray[$x]."'][".cCREDITDISC."] = ".$gSettingsArray["plugin_".$pluginarray[$x]."_Discover"].";\n";
    }
    $tpl->assign("ARRAYCOUNT", $arraycount);
    $tpl->assign("STRAVAILABLECCARRAY", $strAvailableCCArray);
    $tpl->assign("CCREDITVISA", cCREDITVISA);
    $tpl->assign("CCREDITMC", cCREDITMC);
    $tpl->assign("CCREDITAMEX", cCREDITAMEX);
    $tpl->assign("CCREDITDISC", cCREDITDISC);

    if($billingerror != '') {
        $tpl->assign("THEBILLINGERROR",$billingerror);
        $tpl->parse("BILLINGERROR","billingerror");
    }
    $tpl->assign("BILLINGBLOCKSTYLE",$billingblock_style);
    reset($plugin_names);
    //Set paymenttype to the default if passed so that it will be selecteed
    if (isset($_REQUEST['paymenttype']) && $_REQUEST['paymenttype'] != '') {
        $pos = strpos($_REQUEST['paymenttype'],"_");
        if ($pos > 0) {
            $gSettingsArray['Default Gateway'] = substr($_REQUEST['paymenttype'],$pos+1);
        } else {
            $gSettingsArray['Default Gateway'] = $_REQUEST['paymenttype'];
        }
    }
    //Set the first value that is available
    //In case the admin has selected a default
    //that is not available in signup
    $tFirstVal = '';
    $tFirstTime = true;
    $selected = '';
    $recurringVisibility = 'hidden';
    while (list($key, $val) = each($plugin_names)) {
        //If plugin is set to be in signup script then make sure to add
        if ($gSettingsArray["plugin_".$val."_In Signup"] == 1) {
            if ($tFirstTime) {
                $tFirstVal = $val;
                $tFirstTime=false;
            }
            if ($gSettingsArray["plugin_".$val."_Signup Name"] == '') {
                $tSignupName = $val;
            } else {
                $tSignupName = $gSettingsArray["plugin_".$val."_Signup Name"];
            }

            if (@$gSettingsArray["plugin_".$val."_Auto Payment"] == 1) {
                $strValue = "1_".$val;
            } else {
                $strValue = "0_".$val;
            }

            if ($gSettingsArray['Default Gateway'] == $val) {
                $selected = $val;
                if ($val == 'paypal') {
                    $recurringVisibility = 'visible';
                }
                $tpl->assign("GATEWAYSELECTED","selected");
            } else {
                $tpl->assign("GATEWAYSELECTED", '');
            }
            $tpl->assign("GATEWAYVALUE",$strValue);
            $tpl->assign("GATEWAYTSIGNUPNAME",$tSignupName);
            $tpl->parse("PLUGIN_NAMES", ".plugin_names");
        }
    }
    if ($selected == '') {
        $selected=$tFirstVal;
    }
    $checked = isset($_REQUEST['use_paypal_subscriptions'])? 'checked' : '';
    if (!($tPrice1included || $tPrice3included || $tPrice6included || $tPrice12included)
        && (!$_REQUEST['domain']!="" || !(@$_REQUEST['transfer'] == 0 || @$_REQUEST['transfer'] == 1)))
    {
        // don't show paypal subscriptions option if there's no billing cycle for this package and there are no domain fees
        $tpl->parse("NOT_PRICE_INCLUDED", "not_price_included");
    } elseif ($gSettingsArray['plugin_paypal_Force customers to use PayPal subscriptions'] ==  0) {
        $tpl->assign("CHECKED", $checked);
        $tpl->assign("USERECURRINGSUBSCRIPTIONNOTE", ReturnPopUpString(lang("Check to use Paypal Subscriptions, which allow you to automatically make the periodic payments without your intervention")));
        $tpl->parse("PLUGIN_PAYPAL_FORCE", "plugin_paypal_force");
    } else {
        $tpl->parse("USE_PAYPAL_SUBSCRIPTIONS", "use_paypal_subscriptions");
    }
    $tpl->assign("RECURRINGVISIBILITY", $recurringVisibility);

    //enter autopayment for the selected plugin
    if (@$gSettingsArray["plugin_".$selected."_Auto Payment"] == 1) {
        $autopayment = "1";
    } else {
        $autopayment = "0";
    }
    $tpl->assign("AUTOPAYMENT", $autopayment);
    $displaycc = '';
    if (!isset($gSettingsArray["plugin_".$selected."_Accept CC Number"] ) || $gSettingsArray["plugin_".$selected."_Accept CC Number"] == 0) {
        $displaycc="none";
    }
    $tpl->assign("DISPLAYCC", $displaycc);
    $tpl->assign("INTCOLORINDEX", GetAltColor($intColorIndex));
    //credit card information if the select plugin accepts it
    $tpl->assign("CCNUMBER", @$_REQUEST['ccnumber']);

    //determine if selected plugin needs to ensure valid_cc number
    if (in_array($selected, $pluginarray)) {
        $tpl->assign("INVALIDCC", lang("Invalid Credit Card Number"));
        $tpl->assign("REQUIREDCC", lang("Credit Card is Required"));
    } else {
        $tpl->assign("INVALIDCC", '');
        $tpl->assign("REQUIREDCC", '');
    }

    //get the passed ccmonth
    $tempCCMonth = @$_REQUEST['ccmonth'];
    $monthnames = array(lang("January"), lang("February"), lang("March"), lang("April"), lang("May"), lang("June"), lang("July"), lang("August"), lang("September"), lang("October"), lang("November"), lang("December"));
    for ($i = 1;$i <= 12; $i++) {
        if(!(strcmp($i, $tempCCMonth))) {
            $tpl->assign("MONTHSELECTED", " selected");
        } else {
            $tpl->assign("MONTHSELECTED", "");
        }
        $tpl->assign("MONTHNAME", $monthnames[$i-1]);
        $tpl->assign("MONTHVALUE", $i);
        if ($i < 10) {
            $tpl->assign("MONTHNUMBER", "0" . $i);
        } else {
            $tpl->assign("MONTHNUMBER", $i);
        }
        $tpl->parse("MONTHOPTION",".monthoption");
    }
    $tempCCYear = @$_REQUEST['ccyear'];
    $curYear = date("Y");
    for ($i = 0;$i <= 15; $i++) {
        if(!(strcmp($curYear, $tempCCYear))) {
            $tpl->assign("YEARSELECTED", " selected");
        } else {
            $tpl->assign("YEARSELECTED", '');
        }
        $tpl->assign("CCYEAR", $curYear);
        $tpl->parse("YEAROPTION",".yearoption");
        $curYear++;
    }

    $visabit=0; $mcbit=0; $amexbit=0; $discbit=0;
    $visastyle = ''; $mastercardstyle = ''; $americanexpressstyle = ''; $discoverstyle = '';
    //check the cards we are accepting
    if (!isset($gSettingsArray["plugin_".$selected."_Visa"]) || $gSettingsArray["plugin_".$selected."_Visa"] == 0) {
        $visastyle="none";
    } else {
        $visabit=1;
    }
    if (!isset($gSettingsArray["plugin_".$selected."_MasterCard"]) || $gSettingsArray["plugin_".$selected."_MasterCard"] == 0) {
        $mastercardstyle="none";
    } else {
        $mcbit=1;
    }
    if (!isset($gSettingsArray["plugin_".$selected."_AmericanExpress"]) || $gSettingsArray["plugin_".$selected."_AmericanExpress"] == 0) {
        $americanexpressstyle="none";
    } else {
        $amexbit=1;
    }
    if (!isset($gSettingsArray["plugin_".$selected."_Discover"]) || $gSettingsArray["plugin_".$selected."_Discover"] == 0) {
        $discoverstyle="none";
    } else {
        $discbit=1;
    }

    // ****** Coupons **************
    $tpl->define_dynamic(array('coupons' => 'tables2_step2'));
    if ($GLOBALS['gSettingsArray']['Accept Coupons']) {
        if (isset($_POST['coupon_code']) && $_POST['coupon_code']) {
            $tpl->assign('couponCode', $_POST['coupon_code']);
            $tpl->define_dynamic(array('validateCoupon' => 'tables2_step2'));
            $tpl->parse('trash', 'validateCoupon');
        } else {
            $tpl->assign('couponCode', '');
        }
        $tpl->parse('trash', 'coupons');
    }

    $tpl->assign("VISASTYLE", $visastyle);
    $tpl->assign("MASTERCARDSTYLE", $mastercardstyle);
    $tpl->assign("AMEXSTYLE", $americanexpressstyle);
    $tpl->assign("DISCSTYLE", $discoverstyle);
    $tpl->assign("BITVALIDCC", "$visabit$mcbit$amexbit$discbit");
    $tpl->assign("BILLINGBLOCKMEMBER", $billingblockmember_style);
    $tpl->assign("SIZEOFBOX","20");
    $tpl->assign("WIDTHOFBOX","570");
    $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang("Billing Information"));
    $tpl->parse("SIGNUPBLOCKCONTENT","tables2_step2");
    $tpl->assign("SIGNUPBLOCKRIGHTTEXT","");
    $tpl->parse("BOXNOSUBMIT2", "boxnosubmit");
    $tpl->parse("BILLINGINFORMATION", "billinginformation");

    //<!-- ***  END BILLING INFORMATION BLOCK *** -->
    //<!-- ***  BEGIN ACCOUNT INFORMATION BLOCK *** -->

    if (isset($_REQUEST['member'])&&$_REQUEST['member'] == 'on') {
        $strCheckedMemberInput = " CHECKED";
        $memberinfo_style = '';
        $accountinfo_style = 'none';
    } else {
        $strCheckedMemberInput = '';
        $memberinfo_style = 'none';
        $accountinfo_style = '';
    }
    $tpl->assign("MEMBERINFO_STYLE", $memberinfo_style);
    $tpl->assign("MEMBER_EMAIL", @$_REQUEST['member_email']);
    $tpl->assign("MEMBER_PASSWORD", @$_REQUEST['member_password']);
    $tpl->assign("ACCOUNTINFO_STYLE", $accountinfo_style);
    $tpl->assign("DISPLAYPROFILECUSTOMFIELDS", DisplayCustomFields("Profile"));
    //get list of custom fields that are available in signup
    $tpl->assign("NEW_PASSWORD", @$_REQUEST['new_password']);
    if ($gSettingsArray['Request Access Code'] == 1) {
        $tpl->assign("ENTERACCODE", ReturnPopUpString(lang('In order to protect our servers, we have implemented a process that prevents unscrupulous flooders from running scripts that register accounts on our servers.<br><br> The access code you see is provided in graphic format and cannot be read by any scripts.<br><br>By taking a moment to key in the access code you are helping us in providing you with better service.')));
        $tpl->parse("REQUEST_ACCESS_CODE", "request_access_code");
    }
    $tpl->assign("CHECKEDMEMBERINPUT", $strCheckedMemberInput);

    //TODO*****
    $tpl->parse("BOXNOSUBMITACCOUNTINFO","boxnosubmitaccountinfo");

    $tpl->assign("SIZEOFBOX","40");
    $tpl->assign("WIDTHOFBOX","570");
    $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang("Account Information"));
    $tpl->parse("SIGNUPBLOCKCONTENT","tables3_step2");
    $tpl->assign("SIGNUPBLOCKRIGHTTEXT","");
    $tpl->parse("BOXNOSUBMIT3", "boxnosubmit");
    $tpl->parse("ACCOUNTINFORMATION", "accountinformation");

    $tProratedPrice = 0;
    $proratedDays = 0;
    $proIncFollowing = 0;
    $tmpNextBill = 0;
    $proNextBill = 0;

    if (isset($_REQUEST['domain']) && $_REQUEST['domain'] != '' && (@$_REQUEST['transfer'] == 0 || @$_REQUEST['transfer'] == 1)) {
        //do not show domain price if it isn't being passed
        $tpl->assign("DOMAIN",$domain);
        $tpl->parse("SHOWDOMAINPRICE","showdomainprice");
    }

    if ($_REQUEST['paymentterm'] != 0) { //do not show price if no payment methods are set to show in signup
        $tpl->assign("PACKAGE",lang("Package"));
        $tpl->assign("PLANNAME", $tPlanName);
        $tpl->assign("SHOWPROINCFOLLOWING", lang("Billed")." ".$strBillingCycle);

        list($tPrice, $tProratedPrice, $proratedDays, $proIncFollowing, $tmpNextBill, $proNextBill)
        = processProrating($gSettingsArray['Prorate To Day'], $gSettingsArray['Include Following Payment'], $_REQUEST['paymentterm'], $tPrice);

        // Prorating Display
        if ($proratedDays > 0) {
            $tpl->assign(array(
                'PRORATING'                     => 1,
                'PRORATEDDAYS'                  => $proratedDays,
                'SHOWPRORATEDDISPLAY_PACKAGE'   => lang("Prorated")." ".$proratedDays." ".lang("days"),
            ));
           if ($proIncFollowing == 1) {
                $tpl->parse("PROINCFOLLOWING", "proincfollowing");
                $tpl->setKey('INCLUDEFOLLOWINGPAYMENT', 1);
           }
        } else {
            $tpl->assign(array(
                'PRORATING'                     => 0,
                'SHOWPRORATEDDISPLAY_PACKAGE'   => lang("Billed")." ".$strBillingCycle
            ));
        }
        $tpl->parse("ISSETPAYMENTMETHODS", "issetpaymentmethods");
    }

    if ($tTaxable) {
        $tpl->assign('displaySubTotalLabel', 'block');
        $tpl->assign('displaySubTotalValue', 'block');
    } else {
        $tpl->assign('displaySubTotalLabel', 'none');
        $tpl->assign('displaySubTotalValue', 'none');
    }

    // Tell the user when they will next be billed since it isn't just
    // one (month, year, etc) in the future.
    $disableSubscriptionsSet = false;
    if ($proratedDays > 0) {
        $tpl->assign("PRONEXTBILL",date('F jS, Y', $proNextBill));

        // don't allow paypal subscriptions when trial period > 90
        if (($proNextBill - mktime(0, 0, 0)) / 86400 > 90) {
            $disableSubscriptionsSet = true;
            $tpl->parse("PRORATEDDAYSMORETHAN90", "prorateddaysmorethan90");
        }
        $tpl->parse("PRORATEDDAYS", "prorateddays");
    }
    if (!$disableSubscriptionsSet) {
        $tpl->parse("DISABLESUBSCRIPTIONSSET","disablesubscriptionsset");
    }

    //do not show domain price if it isn't being passed
    if (isset($_REQUEST['domain']) && $_REQUEST['domain'] != '' && (@$_REQUEST['transfer'] == 0 || @$_REQUEST['transfer'] == 1)) { 
        $tpl->parse("DOMAINISPASSED","domainispassed");
    }
    if ($_REQUEST['paymentterm'] != 0) { //do not show price if no payment methods are set to show in signup
        // Prorating Display
        if ($proratedDays > 0) {
            $tpl->assign("SHOWCURRENCY", ShowCurrencySymbol($_REQUEST['currency'],false) . " " . sprintf("%01.2f", $tProratedPrice));
            if ($proIncFollowing == 1) {
               $tpl->assign("SHOWCURRENCYPROINCFOL", ShowCurrencySymbol($_REQUEST['currency'],false) . " " . sprintf("%01.2f", $tPrice));
               $tpl->parse("CURRENCYPROINCFOL","currencyproincfol");
           }
        } else {
            $tpl->assign("SHOWCURRENCY", ShowCurrencySymbol($_REQUEST['currency'],false) . " " . sprintf("%01.2f", $tPrice));
        }
        $tpl->parse('SHOWPACKAGEPRICE', 'showpackageprice');
    }

   $tpl->assign("TCURRENCY", $_REQUEST['currency']);

   //place setup price
   $tpl->assign("TSETUP", $tSetup);
   if ($tSetup) {
       $tpl->assign("SHOWCURRENCYSETUP", ShowCurrencySymbol($_REQUEST['currency'],false)." ".sprintf("%01.2f", $tSetup));
       $tpl->parse("SHOWSETUPPRICE", "showsetupprice");
       $tpl->parse("SHOWSETUPPRICE1", "showsetupprice1");
   }

    // Will need these to actually make the invoice later
    if ($proratedDays > 0) {
        $tpl->assign("TPRORATEDPRICE", $tProratedPrice);
        $tpl->assign("PRONEXTBILL", $proNextBill);
        $tpl->assign("TMPNEXTBILL", $tmpNextBill);
        $tpl->assign("PROINCFOLLOWING", $proIncFollowing);
        $tpl->parse("PRORATEDDAYS1", "prorateddays1");
    }

    $tpl->assign("TTAXABLE", $tTaxable);
    $tpl->assign("SUBMITFUNCTION","SubmitStepTwo");
    $tpl->assign("BACKFUNCTION","BackStepTwo");
    $tpl->assign("BACKINPUTNAME","back");
    $tpl->assign("BACKINPUTVALUE","1");
    $tpl->assign("SIZEOFBOX","65");
    $tpl->assign("INPUTNAME","next");
    $tpl->assign("WIDTHOFBOX","570");
    $tpl->assign("INPUTVALUE","1");
    $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang("Checkout"));
    $tpl->parse("SIGNUPBLOCKCONTENT","tables4_step2");
    $tpl->parse("BOXSUBMIT4", "boxsubmitback");
    $tpl->parse("TOTALINFO", "totalinfo");

    $var_querystring = base64_encode(serialize($arrCustomFields));
    $tpl->assign("VARQUERYSTRING", $var_querystring);
    $tpl->assign("CURRENCYSYMBOLVAR", ShowCurrencySymbol($_REQUEST['currency'],false));
    $tpl->assign("TTAXABLE", $tTaxable);
    $tpl->assign("SUBTOTALVAR", $tSetup+$tPrice+$tProratedPrice); //added prorate price

    if ($tTaxable == 1 && $bolCountryPresent) {
        $tpl->parse("GETTAX", "gettax") ;
    }
    $tpl->parse("FORMSTEP2","formstep2");
    $tpl->FastPrint("FORMSTEP2");
    //<!-- ***  END ACCOUNT INFORMATION BLOCK *** -->
}

// After user info has bee submited:
// - Check with MaxMind if enabled
// - Check if customer's e-mail already exists
// - Show terms and conditions if enabled
// - Continue with step four
function StepThree($domain)
{
    require_once 'classes/maxmind/CreditCardFraudDetection.php';

    global $gSettingsArray,$tpl;

    $fraudmsg = '';
    $bolFailedRiskScore = false;

    if (isset($_SESSION['phoneverification'])) {
         unset($_SESSION['phoneverification']); // Generate new phone code and recall them
    }

    if ($gSettingsArray['Enable MaxMind Fraud Control'] == 1 && @!$_REQUEST['member'] == 'on') {
         //return array with the following keys
         //i = ip, city, region, postal, country, domain,  custPhone

         $h = GetRequestDetailsForFraudCheck();
         $h["license_key"] = $gSettingsArray['MaxMind License Key'];

         //use maxmind class
         $ccfs = new CreditCardFraudDetection;
         $ccfs->isSecure = 0;
         $ccfs->timeout = 5;
         $ccfs->input($h);
         $ccfs->query();
         $h = $ccfs->output();
         $outputkeys = array_keys($h);
         $numoutputkeys = count($h);

        for ($i = 0; $i < $numoutputkeys; $i++) {
             $key = $outputkeys[$i];
             $value = $h[$key];
             $fraudmsg .= $key . " = " . $value . "\n";
        }
        // post the fraud score for use in the phone verification step
        $_POST['fraudScore'] = $h['score'];
        //get score and determine if
        //customer has a set score higher then that
        //as threshold
        if ($gSettingsArray['MaxMind Fraud Risk Score'] != 'none') {
            $tScore = floatval($h['score']);

            $tUserScore = floatval($gSettingsArray['MaxMind Fraud Risk Score']);
            if ($tScore>=$tUserScore) {
                $bolFailedRiskScore = true;
            } else {
                $bolFailedRiskScore = false;
            }
        } else {
            $bolFailedRiskScore = false;
        }
    }

    //Check email if duplicate send back to StepTwo
    if (!@$_REQUEST['member'] == 'on'
        && ($bolFailedRiskScore
             || CheckEmailDuplicate(htmlspecialchars($_REQUEST['CT_4'], ENT_QUOTES))
             || (@$h['highRiskCountry']=="Yes" && $gSettingsArray['Reject High Risk Country'] == 1)
             || (@$h['countryMatch']=='No' && $gSettingsArray['Reject Country Mismatch']==1)
             || (@$h['freeMail']=='Yes' && $gSettingsArray['Reject Free E-mail Service']==1)
             || (@$h['anonymousProxy']=='Yes' && $gSettingsArray['Reject Anonymous Proxy']==1)))
    {
        $arrError = Array();
        if ($bolFailedRiskScore) {
             $arrError[]= lang('Your overall risk is too high, please contact our sales office for more information');
        } else {
             if ((@$h['highRiskCountry']=="Yes")&&($gSettingsArray['Reject High Risk Country']==1)) $arrError[]= lang("Sorry we are not accepting orders from your country");
             if ((@$h['countryMatch']=='No')&&($gSettingsArray['Reject Country Mismatch']==1)) $arrError[]= lang("Your country does not match the IP you are currently signing up from");
             if ((@$h['freeMail']=='Yes')&&($gSettingsArray['Reject Free E-mail Service']==1)) $arrError[] = lang("We do not accept signups from free E-mail services");
             if ((@$h['anonymousProxy']=='Yes')&&($gSettingsArray['Reject Anonymous Proxy']==1)) $arrError[] = lang("We do not accept signups from anonymous proxy servers");
             if (CheckEmailDuplicate(htmlspecialchars($_REQUEST['CT_4'], ENT_QUOTES))) $arrError[] = lang("This E-mail address is already in use");
        }
        
        $strMessageOutput = "------------------------------<b>\n";
    	$strMessageOutput .= lang("Reason For Rejection")."\n";
    	$strMessageOutput .= "</b>------------------------------\n";
    	foreach($arrError as $reason) {
    		$strMessageOutput .= $reason."\n";
    	}
    	
    	$strMessageOutput .= "\n------------------------------<b>\n";
        $strMessageOutput .= lang("Customer Details").":\n";
		$strMessageOutput .= "</b>------------------------------\n";
		
		if ($domain != "") {
        	$strMessageOutput .= lang("Domain Name").": $domain";
        	switch ($_REQUEST['transfer']) {
	            case 0:
	                $strMessageOutput .= "\n".lang("Registrar Service Requested: Customer wants host to register domain");
	                break;
	            case 1:
	                $strMessageOutput .= "\n".lang("Registrar Service Requested: Customer wants host to transfer domain");
	                break;
	            case 2:
	                $strMessageOutput .= "\n".lang("Registrar Service Requested: Customer will transfer their own domain");
	                break;
	        }
		}
		
		$customTagsArray = unserialize(base64_decode($_REQUEST['customTagsArray']));
		//Get Custom Tags for profile
        foreach ($customTagsArray as $customTag) {
            $value = htmlspecialchars($_REQUEST[$customTag],ENT_QUOTES);
            //Get Custom Field Name to Use in new account email
            if (substr($customTag,0,2)=="CT") {
                //This is a profile custom tag
                if ($customTag=="CT_1"){$tFirstName=$value;}
                if ($customTag=="CT_2"){$tLastName=$value;}
                $customTag = str_replace("CT_", "", $customTag);
                if (trim($value) != '') {
                     $getCustomNameQuery = "SELECT name, type FROM customuserfields WHERE id=?";
                     $getCustomNameResult = $GLOBALS['db']->query($getCustomNameQuery, $customTag);
                     list($tCustomName, $tType) = $getCustomNameResult->fetch();
                     if ($tType == typeDATE) {
                         $value = form_to_db($value, "/");
                     }
                     $strMessageOutput .= "\n$tCustomName: $value";
                }
            }
        }
        
        //Enter Account Information
	    $query="SELECT planid,planname FROM package WHERE id=?";
	    $result = $GLOBALS['db']->query($query, $_POST['package']);
	    list($promotionid,$planname) = $result->fetch();
	
	    require_once 'classes/PackageType.php';
	    $packageType = new PackageType($promotionid);
	    $strMessageOutput .= "\n".lang("Package Type").": ".$packageType->getName()." ( ".$packageType->getCode()." )";
	    $strMessageOutput .= "\n".lang("Domain Package").": ".$planname;
	
	    if (!@$_REQUEST['member'] == 'on') {
	        //Extra Signup Email Info
	        $strMessageOutput .= "\nRequested Password: ".$_REQUEST['new_password'];
	        $strMessageOutput .= "\nPayment Type: ".substr($_POST['paymenttype'], 2);
	        if ($_POST['paymenttype'] == 'paypal' && isset($_POST['use_paypal_subscriptions']))
	            $strMessageOutput .= ' - '.lang("Subscriptions enabled");
	    }
        
        $strMessageOutput .= "\n\n<b>------------------------------
                             ".lang("Package Variables")."
                             ------------------------------</b>";
	    //Set Custom Tags for package (domain)
	    reset($customTagsArray);
	    foreach ($customTagsArray as $customTag) {
	        $value = htmlspecialchars($_REQUEST[$customTag],ENT_QUOTES);
	        //Get Custom Field Name to Use in new account email
	        if (substr($customTag,0,3) == 'PCT') {
	            //This is a package custom tag
	            $customTag = str_replace("PCT_", "", $customTag);
	            if (trim($value) != '') {
	                 $getCustomNameQuery = "select name, type from customdomainfields where id=?";
	                 $getCustomNameResult = $GLOBALS['db']->query($getCustomNameQuery, $customTag);
	                 list($tCustomName, $tType) = $getCustomNameResult->fetch();
	                 if ($tType == typeDATE) {
	                     $value = form_to_db($value, "/");
	                 }
	                 $strMessageOutput .= "\n$tCustomName: $value";
	            }
	        }
	    }
        $strMessageOutput .= "\n\n------------------------------<b>\n";
        $strMessageOutput .= lang("Signup Environment").":\n";
        $strMessageOutput .= "</b>------------------------------\n";
        //Enter some initial commments for customer
		$ip = getRemoteAddr();
		$host = @gethostbyaddr($ip);
	
	    $agent = $_SERVER['HTTP_USER_AGENT'];
	    $strMessageOutput .= "IP: $ip\n";
	    $strMessageOutput .= "HOSTNAME: $host\n";
	    $strMessageOutput .= "USER AGENT: $agent\n";
		
	    //add fraud message to admin comments
	    if ($fraudmsg!=""){
	        $strMessageOutput .= "\n------------------------------<b>\n";
	        $strMessageOutput .= lang("Fraud Details").": MaxMind Plugin\n";
	        $strMessageOutput .= "</b>------------------------------\n";
	        $strMessageOutput .= $fraudmsg;
	    }
	    
	    $strMessageOutput .= "\n\n".lang("Thank you for using ClientExec!")."\n";
	    $strMessageOutput .= "<b>".lang("The ClientExec Team")."</b>\n";
	    $strMessageOutput .= "http://www.clientexec.com";
	    
	    SendOutNotifications($tFirstName, $tLastName, $domain, $strMessageOutput, false, false);

        $tpl->FastPrint("HEADER");  //Display Header
        StepTwo($domain,$_REQUEST['clienttype'],$_REQUEST['package'],$_REQUEST['transfer'],$arrError);
        $tpl->FastPrint("FOOTER");  //Display Header
        return;
    }

    if ($gSettingsArray['Request Access Code'] == 1) {
        if (!@$_REQUEST['member']=='on') {
            if ((!isset($_SESSION['sessAccessCode'])) || ($_SESSION['sessAccessCode'] != addslashes(strtoupper($_POST['accesscode'])))) {
                $arrError[] = lang("The access code does not match with the one in the image.");
                $tpl->FastPrint("HEADER");  //Display Header
                StepTwo($domain,$_REQUEST['clienttype'],$_REQUEST['package'],$_REQUEST['transfer'],$arrError);
                $tpl->FastPrint("FOOTER");  //Display Header
                return;
            }
        }
    }

    if ($gSettingsArray['Show Terms and Conditions'] == 0) {
        if (!@$_REQUEST['member']=='on'
            && $gSettingsArray['Enable MaxMind Telephone Verification'] == 1
            && $gSettingsArray['Minimum Bill Amount to Trigger Telephone Verification'] <= $_POST['totalBill'])
        {
            PreStepFour($fraudmsg);
        } else {
            StepFour($domain,$fraudmsg);
        }
        return;
    } else {
            $tpl->FastPrint("HEADER");  //Display Header
            ShowProgress(lang('Terms and Conditions'),90);
            $tpl->assign("SUBMITFUNCTION","SubmitStepThree");
            $tpl->assign("BACKFUNCTION","BackStepThree");
            $tpl->assign("BACKINPUTNAME","back");
            $tpl->assign("BACKINPUTVALUE","1");
            $tpl->assign("SIZEOFBOX","65");
            $tpl->assign("INPUTNAME","next");
            $tpl->assign("WIDTHOFBOX","500");
            $tpl->assign("INPUTVALUE","1");
            $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang("Terms and Conditions"));
            //populate all the fields passed from previous step
            if (!isset($_REQUEST['member'])  && $gSettingsArray['Enable MaxMind Telephone Verification']==1) {
                $_POST['step'] = 7;
            } else {
                $_POST['step'] = 4;
            }
            foreach ($_POST as $key=>$val) {
                $tpl->assign("INPUTNAME",$key);
                $tpl->assign("INPUTVALUE",$val);
                $tpl->parse("ALLTHEFIELDS", ".form_hidden_inputs");
            }
            $gSettingsArray['Terms and Conditions'] = str_replace('&quot;','"',$gSettingsArray['Terms and Conditions']);
            $gSettingsArray['Terms and Conditions'] = str_replace('&#039','\'',$gSettingsArray['Terms and Conditions']);
            $gSettingsArray['Terms and Conditions'] = nl2br($gSettingsArray['Terms and Conditions']);
            $tpl->assign("TERMSANDCONDITIONS", $gSettingsArray['Terms and Conditions']);
            $tpl->assign("FRAUDMSG", $fraudmsg);
            $tpl->parse("SIGNUPBLOCKCONTENT","tables_step3");
            $tpl->parse("BOXSUBMIT", "boxsubmitback");
            $tpl->FastPrint("BOXSUBMIT");
            $tpl->FastPrint("FOOTER");  //Display Header
    }
}

//Telephone Verification Step(7)
function PreStepFour($fraudmsg)
{
    global $domain, $gSettingsArray, $tpl;

    if (!$gSettingsArray['Enable MaxMind Telephone Verification'] ||
        ($gSettingsArray['Minimum Bill Amount to Trigger Telephone Verification'] > $_POST['totalBill']
        || ($gSettingsArray['Enable MaxMind Fraud Control'] && $gSettingsArray['Minimum Fraud Score to Trigger Telephone Verification'] > $_POST['fraudScore']))) {
        $fraudmsg = '';
        if(isset($_REQUEST['fraudmsg'])) $fraudmsg = $_REQUEST['fraudmsg'];
        StepFour($domain, $fraudmsg);
        exit;
    }

    require_once 'classes/maxmind/TelephoneVerification.php';

    // Languages currently supported by MaxMind
    $mmLangs = array("English","Spanish","French","German","Japanese");
    $phonenum = "";
    $phoned = 0;
    $verified = 0;
    $phoneLang = "English";
    foreach ($_POST as $key => $val) {
        if ($key == 'phoneField') {
            $phonenum = $_REQUEST[$val];
        }
        if ($key == 'langField' && in_array($_REQUEST[$val], $mmLangs)) {
            $phoneLang = $_REQUEST[$val];
        }
    }

    /* Need to check if we've already called in case they refresh the page
     * Don't want to waste all our phone credits on the same customer.
     * Clicking the back button or closing the browser will clear the session variable
     */
    if (!isset($_SESSION['phoneverification'])) {
        $_SESSION['phoneverification'] = rand(1000, 9999);
        $tv = new TelephoneVerification;
        $h = array();
        $h["l"] = $gSettingsArray['MaxMind License Key'];
        $h["phone"] = $phonenum;
        $h["verify_code"] = $_SESSION['phoneverification'];
        $h["language"] = $phoneLang;

        $tv->isSecure = 0;
        $tv->timeout = 30;
        $tv->useDNS = 0;
        $tv->input($h);
        if (!$tv->query()) {
            $arrError = Array();
            $arrError[]= lang("We're sorry but we are unable to contact your phone number.  Please verify that it is correct or try another number.");
            $tpl->FastPrint("HEADER");  //Display Header
            StepTwo($domain,$_REQUEST['clienttype'],$_REQUEST['package'],$_REQUEST['transfer'],$arrError);
            $tpl->FastPrint("FOOTER");  //Display Header
            exit;
        }
        $h = $tv->output();
        $outputkeys = array_keys($h);
        $numoutputkeys = count($h);
        for ($i = 0; $i < $numoutputkeys; $i++) {
            $key = $outputkeys[$i];
            $value = $h[$key];
            $fraudmsg .= $key . " = " . $value . "\n";
        }
    } else {
        $phoned = 1;
    }

    $tpl->FastPrint("HEADER");
    $tpl->define(array( "phonecode_form"    => "signup/include/phone_verif.tpl"));
    $tpl->assign(array(
        'FUSE'      => cADMIN,
        'ACTION'    => cADMIN_VERIFYPHONECODE,
    ));
    //Testing Only
    //echo $_SESSION['phoneverification'];
    //End Testing Only
    ShowProgress(lang('Phone Verification'),95);
    $tpl->assign("SUBMITFUNCTION","SubmitPreStepFour");
    $tpl->assign("BACKFUNCTION","BackPreStepFour");
    $tpl->assign("BACKINPUTNAME","back");
    $tpl->assign("BACKINPUTVALUE","1");
    $tpl->assign("SIZEOFBOX","65");
    $tpl->assign("INPUTNAME","next");
    $tpl->assign("WIDTHOFBOX","500");
    $tpl->assign("INPUTVALUE","1");
    $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang("Telephone Verification"));

    if (!$phoned) {
        $tpl->assign(array(
            'verifBox1'     => lang("Please wait, you will be called at "),
            'phoneNum'      => $phonenum,
            'verifBox2'     => lang(" within 30 seconds.<br>"),
            'verifBox3'     => lang("Please enter the code given to you by the robotic system below."),
        ));
        $tpl->parse('trash', 'first_verification');
    } else {
        $tpl->assign(array(
            'verifPostCall' => lang("According to our records we have previously phoned you.  If you did not receive a call within 30 seconds please click the back button and verify that your phone number is in the correct format. Please be aware that a new code will be issued"),
        ));
        $tpl->parse('trash', 'already_called');
    }

    //populate all the fields passed from previous step
    $_POST['step'] = 4;
    foreach ($_POST as $key=>$val) {
        $tpl->assign(array(
            'INPUTNAME'     => $key,
            'INPUTVALUE'    => $val,
        ));
        $tpl->parse("HIDDEN_INPUTS", ".form_hidden_inputs");
    }
    $tpl->assign(array(
        'INPUTNAME'     => 'fraudmsg',
        'INPUTVALUE'    => $fraudmsg,
    ));
    $tpl->parse("HIDDEN_INPUTS", ".form_hidden_inputs");

    $tpl->parse('SIGNUPBLOCKCONTENT', 'phonecode_form');
    $tpl->parse("BOXSUBMIT", "boxsubmitback");
    $tpl->FastPrint("BOXSUBMIT");
}

function StepFour($domain,$fraudmsg="")
{
    global $tpl, $gSettingsArray, $database;
    require_once 'classes/maxmind/TelephoneVerification.php';

    // repeat checks
    if (!isset($_POST['package']) || $_POST['package'] <= 0 || !isset($_POST['clienttype']) || $_POST['clienttype'] <= 0) {
        $tpl->FastPrint("HEADER");
        StepZero($domain);
        $tpl->FastPrint("FOOTER");
        exit;
    }
    
    $query = "SELECT regdomain FROM promotion WHERE id = ?";
    $result = $GLOBALS['db']->query($query, $_POST['clienttype']);
    $row = $result->fetch();
    
    if ($row['regdomain'] == 1 && $domain == "") {
        $tpl->FastPrint("HEADER");
        StepOne($domain, $_POST['clienttype'], $_POST['package']);
        $tpl->FastPrint("FOOTER");
        exit;
    }

    $arrError = validateData();

    if ($arrError) {
        $tpl->FastPrint("HEADER");
        StepTwo($domain,$_REQUEST['clienttype'],$_REQUEST['package'],$_REQUEST['transfer'],$arrError);
        $tpl->FastPrint("FOOTER");
        exit;
    }

    // if phone verif is set and it didn't pass, user shouldn't be here
    if (@$_REQUEST['member'] != 'on' && $gSettingsArray['Enable MaxMind Telephone Verification'] == 1
        && !isset($_SESSION['phoneverification_passed'])
        && $gSettingsArray['Minimum Bill Amount to Trigger Telephone Verification'] <= $_POST['totalBill']
        && ($gSettingsArray['Enable MaxMind Fraud Control'] && $gSettingsArray['Minimum Fraud Score to Trigger Telephone Verification'] >= $_POST['fraudScore']))
    {
        header('Location: signup.php?step=7');
        exit;
    }

    $bolEchoOff = true; //variable for autobilling to not display to screen

    if (@$_REQUEST['member']=="on") $bMember=true;
    else $bMember=false;

    //Get ClientType For Package
    $tclienttype = GetClientType($_POST['package']);

    //Create Account
    $tempDateActivated = date("Y-m-d");

    //remove the _ from the payment type
    //_ was used to determine credit card info
    //for the payment types
    $pos = strpos($_POST['paymenttype'],"_");
    if ($pos>0) $_POST['paymenttype'] = substr($_POST['paymenttype'],$pos+1);
    //end payment type formatting

    $tNextBillDate = $tempDateActivated;
    $_POST['dateActivated'] = $tempDateActivated;
    $customTagsArray = unserialize(base64_decode($_REQUEST['customTagsArray']));

    //make recurring for domain = no if no payment cycle was passed.  (Means it should be a one time charge )
    if (isset($_POST['paymentterm'])) {
        $_POST['recurring']=1;
        $tPaymentTerm = $_POST['paymentterm'];
    } else {
        $_POST['recurring']=0;
        $tPaymentTerm = 0;
    }
    unset($_POST['paymentterm']);

    //Enter some initial commments for customer
	$ip = getRemoteAddr();
	$host = @gethostbyaddr($ip);

    $agent = $_SERVER['HTTP_USER_AGENT'];
    $strInitialComments = "IP: $ip\n";
    $strInitialComments .= "HOSTNAME: $host\n";
    $strInitialComments .= "USER AGENT: $agent\n";

    //add fraud message to admin comments
    if ($fraudmsg!=""){
        $strInitialComments .= "\n\n------------------------------\n";
        $strInitialComments .= lang("Fraud Details").": MaxMind Plugin\n";
        $strInitialComments .= "------------------------------\n";
        $strInitialComments .= $fraudmsg;
    }

    //Setup welcome email
    $strMessageOutput = "<b>------------------------------";
    if (!$bMember) {
        $strMessageOutput .= "\n".lang("Customer Details").":";
    } else {
        $_REQUEST['new_password'] = $_REQUEST['member_password'];
        //get userid of existing member
        $tUserID = $_REQUEST['memberuserid'];
        $memberUser =& new User($tUserID);
        $memberUser->PopulateCustomFields();
        $tFirstName = $memberUser->getFirstName();
        $tLastName = $memberUser->getLastName();
        $tOrganization = $memberUser->getOrganization();
        if ($tOrganization) $tLastName .= " - $tOrganization";

        $strMessageOutput .= "\n<font color=red>".lang("Existing Member").": </font>$tFirstName $tLastName";
    }
    $strMessageOutput .= "\n------------------------------</b>\n";
    if ($domain!="") {
        $strMessageOutput .= lang("Domain Name").": $domain";
    }

    if(!$bMember) {
        $p = 0;
        $varnames="";
        $values = "";

        // TODO: prepareForDB to be handled differently
        $tMyUser =& new User;
        $tMyUser->setCurrent(false);
        $tMyUser->setIsOrganization(false);
        $tMyUser->setGroupId(1);
        $tMyUser->setCurrency($_REQUEST['currency']);
        $tMyUser->setPaymentType($_POST['paymenttype']);
        $tMyUser->setCCMonth($_POST['ccmonth']);
        $tMyUser->setCCYear($_POST['ccyear']);
        $tMyUser->setAutopayment(isset($_POST['autopayment']) && $_POST['autopayment'] == 1);
        $tMyUser->setDateCreated($_POST['dateActivated']);
        $tMyUser->setComments(PrepareForDB($strInitialComments));
        $tMyUser->setStatus(0);
        $tMyUser->setRecurring($_POST['recurring']);
        if (!$tMyUser->add()) {
            $tpl->FastPrint("HEADER");
            StepTwo($domain,$_REQUEST['clienttype'],$_REQUEST['package'],$_REQUEST['transfer'],array(lang('This installation has reached its number of users limit')));
            $tpl->FastPrint("FOOTER");
            return;
        }
        $tUserID = $tMyUser->getId();

        if ($gSettingsArray['plugin_paypal_Force customers to use PayPal subscriptions'] == 1) {
            $_POST['use_paypal_subscriptions'] = 1;
        }
        // set paypal subscriptions preference
        if (isset($_POST['use_paypal_subscriptions'])) {
            $query = "SELECT id FROM customuserfields WHERE name='Use Paypal Subscriptions';";
            $result = $GLOBALS['db']->query($query);
            list($customId) = $result->fetch();
            $tMyUser->UpdateCustomTag($customId, 1);
        }

        //Get Custom Tags for profile
        foreach ($customTagsArray as $customTag) {
            $value = htmlspecialchars($_REQUEST[$customTag],ENT_QUOTES);
            //Get Custom Field Name to Use in new account email
            if (substr($customTag,0,2)=="CT") {
                //This is a profile custom tag
                if ($customTag=="CT_1"){$tFirstName=$value;}
                if ($customTag=="CT_2"){$tLastName=$value;}
                $customTag = str_replace("CT_", "", $customTag);
                if (trim($value) != '') {
                     $getCustomNameQuery = "SELECT name, type FROM customuserfields WHERE id=?";
                     $getCustomNameResult = $GLOBALS['db']->query($getCustomNameQuery, $customTag);
                     list($tCustomName, $tType) = $getCustomNameResult->fetch();
                     if ($tType == typeDATE) {
                         $value = form_to_db($value, "/");
                     }
                     $strMessageOutput .= "\n$tCustomName: $value";
                }
                if ($value != '') {
                    $tMyUser->UpdateCustomTag($customTag,$value);
                }
            }
        }

        //Set default HTML Email format to yes
        $getHTMLEmailQuery = "SELECT id FROM customuserfields WHERE name='HTML Email Format';";
        $getHTMLEmailResult = $GLOBALS['db']->query($getHTMLEmailQuery);
        list($tCustomTag) = $getHTMLEmailResult->fetch();
        $tMyUser->UpdateCustomTag($tCustomTag,"1");
        //End Set HTML Email

        //set clientinformation needed
        //for password to get set
        $_SESSION['customerId'] = $tUserID;
        $_SESSION['sessionPassword'] = $_REQUEST['new_password'];
        $tMyUser->setPassword($_POST['new_password']);

        // update user's tax flag
        if ($tMyUser->getTaxRate()) {
            $tMyUser->setTaxable(1);
        }

        $tMyUser->save();
    }

    //Determine what they wanted with the domain name if anything (REGISTRAR)
    if($_REQUEST['domain'] != '') {
        switch ($_REQUEST['transfer']) {
            case 0:
                $strMessageOutput .= "\n".lang("Registrar Service Requested: Customer wants host to register domain");
                break;
            case 1:
                $strMessageOutput .= "\n".lang("Registrar Service Requested: Customer wants host to transfer domain");
                break;
            case 2:
                $strMessageOutput .= "\n".lang("Registrar Service Requested: Customer will transfer their own domain");
                break;
        }
    }
    else {
        $_REQUEST['transfer'] = 2;
    }

    //Enter Account Information
    $query="SELECT planid,planname FROM package WHERE id=?";
    $result = $GLOBALS['db']->query($query, $_POST['package']);
    list($promotionid,$planname) = $result->fetch();

    require_once 'classes/PackageType.php';
    $packageType = new PackageType($promotionid);
    $strMessageOutput .= "\n".lang("Package Type").": ".$packageType->getName()." ( ".$packageType->getCode()." )";
    $strMessageOutput .= "\n".lang("Domain Package").": ".$planname;

    if (!$bMember) {
        //Extra Signup Email Info
        $strMessageOutput .= "\nRequested Password: ".$_REQUEST['new_password'];
        $strMessageOutput .= "\nPayment Type: ".$_POST['paymenttype'];
        if ($_POST['paymenttype'] == 'paypal' && isset($_POST['use_paypal_subscriptions']))
            $strMessageOutput .= ' - '.lang("Subscriptions enabled");
    }

    // Use server that hasn't been used for the longest time and that hasn't filled up his domains quota
    $query = "SELECT s.id, s.sharedip, s.domains_quota FROM server s LEFT JOIN package_server ps ON s.id=ps.server_id "
            ."WHERE ps.package_id=? ORDER BY s.last_utilization ASC, ps.id ASC";
    $result = $GLOBALS['db']->query($query, $_POST['package']);
    $tServerID = 1;
    while ($row = $result->fetch()) {
        $query2 = "SELECT COUNT(id) AS num_domains FROM domains WHERE serverid=?";
        $result2 = $GLOBALS['db']->query($query2, $row['id']);
        $row2 = $result2->fetch();
        if ($row2['num_domains'] >= $row['domains_quota'] && $row['domains_quota'] != 0) {
            continue;
        }
        $tServerID = $row['id'];
        $tServerIP = $row['sharedip'];
        $query = "UPDATE server SET last_utilization=? WHERE id=?";
        $GLOBALS['db']->query($query, date('Y-m-d H:i:s'), $tServerID);
        break;
    }

    //Create domain
    $domainUserName="";
    if ($domain != '') {
        //USERNAME CREATION CODE ADDED VERSION 2.0
        //need to check and see if server has a plugin and call
        //the create username if it does otherwise use this function
        require_once 'classes/class.PluginInterface.php';
        require_once 'classes/server.php';
        $server = New Server($tServerID);
        $pluginName = $server->GetPluginName();
        $domainUserName = substr($domain,0,strpos($domain,".")); // remove the extension of the domain
        if ($pluginName != '') {
            $server_plugins = new PluginInterface("plugins/server",array("CreateUsername"));
            $params = array_merge($server->GetAllServerPluginVariables($pluginName),
                  array("UserID"=>$tUserID,"DomainUsername"=>$domainUserName,"DomainName"=>$domain),
                  $server->GetParams("Create",$pluginName));
            $domainUserName = $server_plugins->callFunction($pluginName,"CreateUsername",$params);
        }
        //END USERNAME CREATION CODE
    }

    //change next invoice date if prorate price was > 0
    if (@$_POST['proratedprice'] > 0) {
        $nextInvoiceDate =  date("Y-m-d",$_POST['proTmpNextBill']);
    } else {
        $nextInvoiceDate =  $tNextBillDate;
    }

    $tPassword = $_REQUEST['new_password'];
    $tDomain = new Domain(array(
        'm_DomainName'  => $domain,
        'm_CustomerID'  => $tUserID,
        'm_UserName'    => $domainUserName,
        'm_Password'    => $tPassword,
        'm_Recurring'   => $_POST['recurring'],
        'm_dateActivated'=> $_POST['dateActivated'],
        'm_PlanID'      => $_POST['package'],
        'm_ServerID'    => $tServerID,
        'm_nextBillDate'=> $nextInvoiceDate,
        'm_paymentterm' => $tPaymentTerm,
        'm_PromotionID' => $tclienttype,
        'm_Current'     => 0,
        'm_Register'    => $_REQUEST['transfer'],
        'm_Signup'      => 1,
    ));
    if (isset($_POST['addonChargesStr'])) {
        $tDomain->setAddons(_getPriceIds($_POST['addonChargesStr']));
    }
    $tDomain->updateRecord();
    $tDomainID = $tDomain->getID();


    $strMessageOutput .= "\n\n<b>------------------------------
                             ".lang("Package Variables")."
                             ------------------------------</b>";
    //Set Custom Tags for package (domain)
    reset($customTagsArray);
    foreach ($customTagsArray as $customTag) {
        $value = htmlspecialchars($_REQUEST[$customTag],ENT_QUOTES);
        //Get Custom Field Name to Use in new account email
        if (substr($customTag,0,3) == 'PCT') {
            //This is a package custom tag
            $customTag = str_replace("PCT_", "", $customTag);
            if (trim($value) != '') {
                 $getCustomNameQuery = "select name, type from customdomainfields where id=?";
                 $getCustomNameResult = $GLOBALS['db']->query($getCustomNameQuery, $customTag);
                 list($tCustomName, $tType) = $getCustomNameResult->fetch();
                 if ($tType == typeDATE) {
                     $value = form_to_db($value, "/");
                 }
                 $strMessageOutput .= "\n$tCustomName: $value";
            }
            if ($value != '') {
                $tDomain->UpdateCustomTag($customTag,$value);
            }
        }
    }

    $query = "INSERT INTO domain_customdomainfields(userid,customid,value) VALUES(?,1,?)";
    $data_insert = $GLOBALS['db']->query($query, $tDomainID, @$tServerIP);

    // serialize extra domain attributes
    $extAttr = array();
    foreach ($_POST as $attrName => $attrValue) {
        if (strpos($attrName, 'ext_attr_') === 0) {
            $extAttr[substr($attrName, 9)] = $attrValue;
        }
    }
    if ($extAttr) {
        $tDomain->setExtAttr($extAttr);
    }

    //check to see if recurring is true ( for recurringfee table synch )
    if ($_POST['recurring'] == 1) {
        //determine if customer has selected to
        //offload recurring process to 3rd party processor
        $tDomain->SetRecurring(1);
    }

    $tMyUser =& new User($tUserID);
    $tMyUser->PopulateCustomFields();
    //check to see if new cc info
    if (!$bMember && $_REQUEST['ccnumber'] != '') {
        $tMyUser->StoreCreditCardInfo($_REQUEST['ccnumber']);
        $tMyUser->save();
    }

    //Delete Cache for Customer Summary
    $tCache = new Cache("ADMINSUMMARY");
    $tCache->SetContent(''); $tCache->Update();

    //if domain was passed determine how much to charge and create charge
    //If customer is going to transfer then this charge does not get added
    if($domain != '' && (($_REQUEST['transfer']==0)||($_REQUEST['transfer']==1))) {
         $aTLDInfo = explode("|", $_REQUEST['domainperiod']);
         $tPaymentTerm = $aTLDInfo[0] * 12;
         $tRegAction = "";
         //check to see if it is one time payment
         if ($aTLDInfo[0] == 0) {
            if ($_REQUEST['transfer'] == 1) {
                $tRegAction = "Domain Transfer";
                $tempDomainDetails = $tRegAction." for Domain: $domain (one time payment)";
            } else {
                $tRegAction = "Domain Registration";
                $tempDomainDetails = $tRegAction." for Domain: $domain (one time payment)";
            }
            //Create One time payment for single domain registration
            $tParams = array(
                'm_CustomerID'        => $tUserID,
                'm_Description'       => "$tRegAction - $domain",
                'm_Detail'            => $tempDomainDetails,
                'm_invoiceid'         =>  0,
                'm_Date'              => $_POST['dateActivated'],
                'm_BillingTypeID'     => -2,
                'm_Price'             => $aTLDInfo[1],
                'm_Recurring'         => 0,
                'm_IncludeNextPayment'=> 1,
                'm_AppliesToID'       => $tDomainID,
                'm_Setup'             => 0,
            );
            $domainRegInvEntry = new InvoiceEntry($tParams);
            $domainRegInvEntry->updateRecord();
        } else {
            $regAppliesTo = $tDomainID;
            // If it's a transfer insert an invoice entry for the transfer and setup a recurring domain registration for future renewals
            if ($_REQUEST['transfer'] == 1) {
                $tRegAction = "Domain Transfer";
                $tempDomainDetails = $tRegAction." for Domain: $domain x ".$aTLDInfo[0]." Years";
                //Create One time payment for single domain transfer
                $tParams = array(
                'm_CustomerID'        => $tUserID,
                'm_Description'       => "$tRegAction - $domain",
                'm_Detail'            => $tempDomainDetails,
                'm_invoiceid'         =>  0,
                'm_Date'              => $_POST['dateActivated'],
                'm_BillingTypeID'     => -2,
                'm_Price'             => $aTLDInfo[1],
                'm_Recurring'         => 0,
                'm_IncludeNextPayment'=> 1,
                'm_AppliesToID'       => $tDomainID,
                'm_Setup'             => 0,
                );
                $domainRegInvEntry = new InvoiceEntry($tParams);
                $domainRegInvEntry->updateRecord();

                // Update the values for the recurring domain registration
                $_POST['dateActivated'] = date("Y") + $aTLDInfo[0]."-".date("m-d");
                $domainExt = substr($domain,strpos($domain,".") + 1);
                $sql = "SELECT price FROM tld WHERE name = ? AND period = ?";
                $result = $GLOBALS['db']->query($sql, $domainExt, $aTLDInfo[0]);
                list($aTLDInfo[1]) = $result->fetch();
                // Need to set this or the registration fee gets included in the first invoice as well as the transfer fee.
                $regAppliesTo = '';
            }

            $tRegAction = "Domain Registration";
            $tempDomainDetails = $tRegAction." for Domain: $domain x ".$aTLDInfo[0]." Years";


            if ($tMyUser->getUsePaypalSubscriptions()) {
                // For domains registrations with package fees, disablegenerate=-1, so that the subscription for the domain registration is generated when
                // the user manually pays the second domain registration charge (usually the following year).
                // If it's only a domain charge disablegenerate=1 because the subscription can be generated immediately (there's no conflict with a package
                // billing cycle).
                if (@$_POST['proratedprice'] > 0 || $tDomain->GetPrice() > 0) $disableGenerate = -1;
                else $disableGenerate = 1;
            } else {
                $disableGenerate = 0;
            }
            $tParams = array(
                'customerid'      => $tUserID,
                'paymentterm'     => $tPaymentTerm,
                'description'     => "$tRegAction - $domain",
                'detail'          => $tempDomainDetails,
                'billingtypeid'   => -2,
                'nextbilldate'    => $_POST['dateActivated'],
                'appliestoid'     => $regAppliesTo,
                'amount'          => $aTLDInfo[1],
                'disablegenerate' => $disableGenerate,
            );
            require_once 'classes/recurringwork.php';
            $domainRegRecurringEntry = new RecurringWork($tParams);
            $domainRegRecurringEntry->update();
            $tDomain->setRegistrationYears($aTLDInfo[0]);
         }
    }

    //Generate Invoice
    if ($_POST['setup'] > 0) {
         //Create InvoiceEntry For Setup
         $tParams = array(
            'm_CustomerID'        => $tUserID,
            'm_Description'       => 'Account Setup',
            'm_Detail'            => 'Initial setup charges',
            'm_invoiceid'         =>  0,
            'm_Date'              => $_POST['dateActivated'],
            'm_BillingTypeID'     => -1,
            'm_Price'             => $_POST['setup'],
            'm_Recurring'         => 0,
            'm_IncludeNextPayment'=> 1,
            'm_AppliesToID'       => $tDomainID,
            'm_Setup'             => 1,
         );
         $setupInvEntry = new InvoiceEntry($tParams);
         $setupInvEntry->updateRecord();
         //$tInvoiceEntryID = mysql_insert_id();
         //if it is a one time charge make sure
         //that we process the invoice now
         /*
         if ($_POST['recurring']==0){
             CreateInvoiceWithEntries($tInvoiceEntryID);
         }
         */
    }

    // Make the prorated charge if needed
    if (@$_POST['proratedprice'] > 0) {
         // Grab the name of the package they just signed up for
         $package = PrepareForDB($_POST['package']);
         $query="select planname from package where id=?";
         $result = $GLOBALS['db']->query($query, $package);
         list($pkgName) = $result->fetch();

         // Pgkname: # mm/dd/yyyy thru mm/dd/yyyy
         if($domain != '') {
            $description = "$pkgName: $domain, " . date($gSettingsArray['Date Format']). ' thru ' . date($gSettingsArray['Date Format'], $_POST['proTmpNextBill']);
         } else {
            $description = "$pkgName ($tDomainID), " . date($gSettingsArray['Date Format']). ' thru ' . date($gSettingsArray['Date Format'], $_POST['proTmpNextBill']);
         }
         $description = PrepareForDB($description);
         $tParams = array(
            'm_CustomerID'        => $tUserID,
            'm_Description'       => $description,
            'm_Detail'            => 'Prorated signup charge',
            'm_invoiceid'         =>  0,
            'm_Date'              => $_POST['dateActivated'],
            'm_BillingTypeID'     => 0,
            'm_Price'             => round($_POST['proratedprice'] + 0.00001, 2),
            'm_Recurring'         => 0,
            'm_IncludeNextPayment'=> 1,
            'm_AppliesToID'       => $tDomainID,
         );
         $proratedInvEntry = new InvoiceEntry($tParams);
         $proratedInvEntry->updateRecord();
    }

    // Revalidate coupon and create discount negative charge
    if ($_POST['discount']) {
         require_once 'classes/coupon.php';
         if ($coupon = Coupon::validate($_REQUEST['coupon_code'], $_REQUEST['clienttype'], $_REQUEST['package'], $_REQUEST['paymentterm'])) {
             $coupon = explode('|', $coupon);
             $strMessageOutput .= "\n\n<b>------------------------------\n"
                             .lang("Discount Coupon")
                             ."\n------------------------------</b>\n"
                             .lang("Code").": ".$_REQUEST['coupon_code']."\n"
                             .lang("Amount").": ".$_POST['discount']."\n\n";
             if ($coupon[4]) {
                 // create recurring entry
                 require_once 'classes/recurringwork.php';
                 $recurringEntry = new RecurringWork(array(
                    'description'       => lang('Discount coupon'),
                    'detail'            => '',
                    'billingtypeid'     => -3,
                    'amount'            => $_POST['discount'],
                    'disablegenerate'   => $tMyUser->getUsePaypalSubscriptions()? 1 : 0,
                    'customerid'        => $tUserID,
                    'paymentterm'       => $tDomain->m_paymentterm,
                    'nextbilldate'      => $tDomain->m_nextBillDate,
                    'appliestoid'       => $tDomain->m_ID));
                 $recurringEntry->update();
             } else {
                 $discountInvEntry = new InvoiceEntry(array(
                    'm_CustomerID'        => $tUserID,
                    'm_Description'       => lang('Discount coupon'),
                    'm_Detail'            => '',
                    'm_invoiceid'         =>  0,
                    'm_Date'              => $_POST['dateActivated'],
                    'm_BillingTypeID'     => -3,
                    'm_Price'             => $_POST['discount'],
                    'm_Recurring'         => 0,
                    'm_IncludeNextPayment'=> 1,
                    'm_AppliesToID'       => $tDomainID,
                 ));
                 $discountInvEntry->updateRecord();
             }

             Coupon::updateQuantity($_REQUEST['coupon_code']);
         }
    }

    // Process Package Add-ons
    if ($_POST['addonChargesStr'] != '') {
    	$strMessageOutput .= "\n\n<b>------------------------------
                             ".lang("Package Add-ons")."
                             ------------------------------</b>\n";
        require_once 'classes/packageaddon.php';
        foreach (_getPriceIds($_POST['addonChargesStr']) as $selectedPriceId => $selectedPriceAttribs) {
            $addon = new PackageAddon($selectedPriceAttribs['addonId']);
            $tPrices = $addon->getPrices();

            $strMessageOutput .= "\n".$addon->getDescription().": "
            	.$tPrices[$selectedPriceId]['detail']. " ("
            	.ShowCurrencySymbol($_REQUEST['currency'],false)
            	.sprintf("%01.2f", $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']])." "
            	.lang("every %s month(s)", $selectedPriceAttribs['cycle']).")";

            if ($tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']] < 0
                || ($selectedPriceAttribs['cycle'] != $tDomain->m_paymentterm && !$tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle'].'Force']))
            {
                continue;
            }

            if ($tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']] >0) {
                require_once 'classes/recurringwork.php';
                if ($tMyUser->getUsePaypalSubscriptions() && $selectedPriceAttribs['cycle'] != $tDomain->m_paymentterm) {
                    $disableGenerate = -1;
                } elseif ($tMyUser->getUsePaypalSubscriptions()) {
                    $disableGenerate = 1;
                } else {
                    $disableGenerate = 0;
                }
                $recurringEntry = new RecurringWork(array(
                   'description'           => $addon->getDescription() . ': ' . $tPrices[$selectedPriceId]['detail'],
                   'detail'                => '',
                   'billingtypeid'         => -4,
                   'packageAddonPricesId'  => $selectedPriceId,
                   'amount'                => $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']],
                   'disablegenerate'       => $disableGenerate,
                   'customerid'            => $tUserID,
                   'paymentterm'           => $selectedPriceAttribs['cycle'],
                   'nextbilldate'          => $tDomain->m_nextBillDate,
                   'appliestoid'           => $tDomain->m_ID));
                $recurringEntry->update();

                // prorated portion
                if ($_POST['prorating'] == 1) {
                    list($tAddonPrice, $addonProratedPrice, $addonProratedDays, $addonProIncFollowing, $addonTmpNextBill, $addonProNextBill)
                    = processProrating($gSettingsArray['Prorate To Day'], $gSettingsArray['Include Following Payment'], $selectedPriceAttribs['cycle'], $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']]);

                    $proratedAddonInvEntry = new InvoiceEntry(array(
                        'm_CustomerID'        => $tUserID,
                        'm_Description'       => $addon->getDescription() . ': ' . $tPrices[$selectedPriceId]['detail']
                                                 . ', ' . date($gSettingsArray['Date Format']). ' thru ' . date($gSettingsArray['Date Format'], $_POST['proTmpNextBill']),
                        'm_Detail'            => 'Prorated signup charge',
                        'm_invoiceid'         =>  0,
                        'm_Date'              => $_POST['dateActivated'],
                        'm_BillingTypeID'     => -4,
                        'm_Price'             => $addonProratedPrice,
                        'm_Recurring'         => 0,
                        'm_IncludeNextPayment'=> 1,
                        'm_AppliesToID'       => $tDomainID,
                    ));
                    $proratedAddonInvEntry->updateRecord();
                }
            }

            // setup portion
            if ($tPrices[$selectedPriceId]['price0'] > 0) {
                $addonInvEntry = new InvoiceEntry(array(
                    'm_CustomerID'        => $tUserID,
                    'm_Description'       => $addon->getDescription() . ': ' . $tPrices[$selectedPriceId]['detail'],
                    'm_Detail'            => '',
                    'm_invoiceid'         =>  0,
                    'm_Date'              => $_POST['dateActivated'],
                    'm_BillingTypeID'     => -4,
                    'm_Price'             => $tPrices[$selectedPriceId]['price0'],
                    'm_Recurring'         => 0,
                    'm_IncludeNextPayment'=> 1,
                    'm_AppliesToID'       => $tDomainID,
                ));
                $addonInvEntry->updateRecord();
            }
        }
    }

    $strMessageOutput .= "\n\n<b>------------------------------
                             ".lang("Signup Environment")."
                             ------------------------------</b>\n";
    $strMessageOutput .= $strInitialComments;

    $strMessageOutput .= "\n\n".lang("Thank you for using ClientExec!")."\n";
    $strMessageOutput .= "<b>".lang("The ClientExec Team")."</b>\n";
    $strMessageOutput .= "http://www.clientexec.com";
    
    StepFive($tUserID,$domain,$tDomainID,$strMessageOutput,$_POST['autopayment'],$tFirstName, $tLastName, $bMember);
}

function SendOutNotifications($firstname, $lastname, $domain, $strMessageOutput, $isMember = false, $success = true)
{
    global $gSettingsArray;

    if ($success) {
	    //Get all the emails I need to send out an email for (emails in settings->admin->signup->email for new templates
	    $strMessage = lang("Dear Support Member,\n\nThis E-mail confirms that there has been a new signup via the ClientExec signup script.\n\nView the details of this signup online at")." ".$gSettingsArray['ClientExec URL']."\n\n".$strMessageOutput;
    } else {
    	$strMessage = lang("Dear Support Member,\n\nThis E-mail confirms that there has been a rejected signup via the ClientExec signup script.")."\n\n".$strMessageOutput;
    }
    if ($gSettingsArray['E-mail For New Signups'] != '') {
        if ($success) {
	    	if ($isMember) {
	            $subject = lang("Existing Customer Signup").": ".$firstname." ".$lastname;
	        } else {
	            $subject = lang("New Customer Signup").": ".$firstname." ".$lastname;
	        }
        } else {
        	$subject = lang("Rejected Customer Signup").": ".$firstname." ".$lastname;
        }
        $aSupportEmail = explode(",", $gSettingsArray['E-mail For New Signups']);
        foreach ($aSupportEmail as $email)
        {
            $email = trim($email);
            if ($email!="") MailMessageEmail($strMessage,$gSettingsArray['Support E-mail'],$gSettingsArray['Support E-mail'],$email,"",$subject,3,0);
        }
    }
}

function StepFive($tUserID,$domain,$domainID,$strMessageOutput,$autopayment, $tFirstName, $tLastName, $bMember)
{
    global $gSettingsArray, $database,$tpl;
    //Forward to Thank you page or Gateway
    $myUser =& new User($tUserID);
    $myUser->PopulateCustomFields();

    if (@$_POST['proratedprice'] > 0 && !$_POST['proIncFollowing']) {
        // when we're prorating and not including the following payment we must skip processing of the package recurring charges
        // to avoid the inclusion of the following payment (otherwise is may get included when the invoice generation offset is small)
        $returnArray = ProcessCustomerBilling($myUser->getId(),$myUser->isAutoPayment(),1,$domainID,1);
    } else {
        // specifying which package we're talking about avoids mixing with other recurring entries from other packages of this
        // same customer.
        $returnArray = ProcessCustomerBilling($myUser->getId(),$myUser->isAutoPayment(),1,$domainID,0);
    }

    //Get invoiceid and price ( should have ProcessCustomerBilling ) return the these values in its returnArray **
    $query="SELECT id,amount FROM invoice WHERE paid=0 AND customerid=? ORDER BY id DESC";
    $result = $GLOBALS['db']->query($query, $tUserID);
    list($tinvoiceid,$invoiceamount) = $result->fetch();

    // If invoice amount is 0 mark it paid so the order processor can do it's work.
    $processInvoice = true;
    if ($invoiceamount == 0) {
		$today = strftime("%Y-%m-%d",mktime (0,0,0,date("m"),date("d"),  date("Y")));
        $query = "UPDATE `invoice` SET paid = 1, datepaid= ? WHERE id = ?";
        $result = $GLOBALS['db']->query($query, $today, $tinvoiceid);

        // process invoice if user has recurring entries with subscriptions that'll generate
        // a non null payment in the future
        $query = "SELECT nextbilldate, paymentterm, SUM(amount) FROM recurringfee "
                ."WHERE customerid=? AND disablegenerate != 0 "
                ."GROUP BY nextbilldate, paymentterm HAVING SUM(amount) > 0";
        $result = $GLOBALS['db']->query($query, $tUserID);
        if (!$result->getNumRows()) {
            $processInvoice = false;
        }
    }

    //Only Send invoice if not forwarding to invoice
    if (($gSettingsArray['Forward To Gateway']==1) && $processInvoice) {
        //Need to get invoice and then forward to gateway
        //prep variables needed for sendToBill
        $tSendToBill_CustomerID=$myUser->getId();
        $tSendToBill_InvoiceID=$tinvoiceid;
        $tSendToBill_Signup=true;
        $tSendToBill_FirstTime=true;
        $tSendToBill_CreditCardNumber = $_REQUEST['ccnumber'];
        $tSendToBill_CreditCardExp = sprintf("%02d", $_REQUEST['ccmonth'])."/".$_REQUEST['ccyear'];
        $tSendToBill_CreditCardCode = @$_REQUEST['cccode'];
        require_once 'modules/billing/actSendToBill.php';
        if ($tError != '') {
            // ** don't delete client if he's an existing member !! **
            if (!isset($_POST['member'])) {
                $tUser =& new User($tUserID);
                $tUser->delete();
            }

            $tpl->FastPrint("HEADER");  //Display Header
            StepTwo($domain,$_REQUEST['clienttype'],$_REQUEST['package'],$_REQUEST['transfer'],"",$tError);
            $tpl->FastPrint("FOOTER");  //Display Header
            return;
        }else{
            SendOutNotifications($tFirstName,$tLastName,$domain,$strMessageOutput,$bMember);
        }
    }

    header("Location: signup.php?step=6&pass=1");
}

function StepSix($tPass=1)
{
    global $gSettingsArray,$tpl;

    if ($tPass == 1) {
        $strDisplay = $gSettingsArray['Signup Completion Template'];
        $strTitle = lang("Your order has completed successfully");
    } else {
        //enter text that payment was rejected
        $strDisplay = $gSettingsArray['Signup Rejection Template'];
        $strTitle = lang("Your order was rejected");
    }
    $strDisplay = str_replace("[COMPANYNAME]", $gSettingsArray["Company Name"], $strDisplay);
    $strDisplay = str_replace("[SUPPORTEMAIL]", $gSettingsArray["Support E-mail"], $strDisplay);
    $strDisplay = str_replace("[CLIENTAPPLICATIONURL]", $gSettingsArray["ClientExec URL"], $strDisplay);
    $strDisplay = str_replace("[COMPANYURL]", $gSettingsArray["Company URL"], $strDisplay);


    ShowProgress(lang('Order Complete'),100);
    $tpl->assign("SIZEOFBOX","40");
    $tpl->assign("WIDTHOFBOX","570");
    $tpl->assign("SIGNUPBLOCKDESCRIPTION",$strTitle);
    $tpl->assign("SIGNUPBLOCKCONTENT",$strDisplay);
    $tpl->assign("SIGNUPBLOCKRIGHTTEXT","");
    $tpl->parse("BOXNOSUBMIT", "boxnosubmit");
    $tpl->FastPrint("BOXNOSUBMIT");

}

function GetRequestDetailsForFraudCheck()
{
        global $gSettingsArray;

		$ip = getRemoteAddr();
        //get email custom id for user
        $query = "SELECT id FROM customuserfields WHERE type=".typeEMAIL;
        $result = $GLOBALS['db']->query($query);
        list($tEmailID) = $result->fetch();
        //get city custom id for user
        $query = "SELECT id FROM customuserfields WHERE type=".typeCITY;
        $result = $GLOBALS['db']->query($query);
        list($tCityID) = $result->fetch();
        //get state custom id for user
        $query = "SELECT id FROM customuserfields WHERE type=".typeSTATE;
        $result = $GLOBALS['db']->query($query);
        list($tStateID) = $result->fetch();
        //get country custom id for user
        $query = "SELECT id FROM customuserfields WHERE type=".typeCOUNTRY;
        $result = $GLOBALS['db']->query($query);
        list($tCountryID) = $result->fetch();
        //get zipcode custom id for user
        $query = "SELECT id FROM customuserfields WHERE type=".typeZIPCODE;
        $result = $GLOBALS['db']->query($query);
        list($tZipcodeID) = $result->fetch();
        //get phone custom id for user
        $query = "SELECT id FROM customuserfields WHERE type=".typePHONENUMBER;
        $result = $GLOBALS['db']->query($query);
        list($tPhoneNumberID) = $result->fetch();

        //$h["license_key"] = "YOUR_LICENSE_KEY_HERE";
        $h["i"] = $ip;             // set the client ip address
        $h["city"] = $_REQUEST['CT_'.$tCityID];             // set the billing city
        $h["region"] = $_REQUEST['CT_'.$tStateID];                 // set the billing state
        $h["postal"] = $_REQUEST['CT_'.$tZipcodeID];              // set the billing zip code
        $h["country"] = $_REQUEST['CT_'.$tCountryID];                // set the billing country
        $h["domain"] = substr(strstr($_REQUEST['CT_'.$tEmailID],'@'),1);
        $h["custPhone"] = $_REQUEST['CT_'.$tPhoneNumberID];
        $h["emailMD5"] = $_REQUEST['CT_'.$tEmailID];
        if (isset($gSettingsArray["plugin_".substr($_POST['paymenttype'],2)."_Accept CC Number"]) 
                && $gSettingsArray["plugin_".substr($_POST['paymenttype'],2)."_Accept CC Number"]) {
            $h["bin"] = substr($_REQUEST["ccnumber"],0,6);
        }
        $h["usernameMD5"] = md5(strtolower($_REQUEST['CT_'.$tEmailID]));
        $h["passwordMD5"] = md5(strtolower($_REQUEST['new_password']));

        return $h;
}


function DisplayCustomFields($fieldtype)
{
    $field = '';
    global $tpl;
    global $arrCustomFields;
    global $gSettingsArray;
    if ($fieldtype == "Profile") {
        global $bolStatePresent;
        global $bolCountryPresent;
        $query = "SELECT id, name, type, isrequired, width, dropdownoptions FROM customuserfields WHERE insignup=1 AND inSettings=1 ORDER BY myOrder";
    } else {
        $query = "SELECT id, name, type, isRequired, width, dropdownoptions FROM customdomainfields WHERE insignup=1 AND inSettings=1 ORDER BY myOrder";
    }
    $result = $GLOBALS['db']->query($query);

    while(list($tID,$tName,$tType,$tRequired,$tWidth,$dropdownoptions) = $result->fetch())
    {
        $tpl->assign("TID", $tID);
        $tpl->assign("TNAME", $tName);
        $tpl->assign("TTYPE", $tType);
        $tpl->assign("TREQUIRED", $tRequired);
        $tpl->assign("TWIDTH", $tWidth);
        $tpl->assign("DROPDOWNOPTIONS", $dropdownoptions);
        $savedValue="";
        $bolSavedData = false;

        if ($fieldtype == "Profile") {
            $tpl->assign("P","");
            $tpl->parse("GETTAX","gettaxCountry");
            if ((isset($_REQUEST['CT_'.$tID]))&&($_REQUEST['CT_'.$tID]!="")){
                $savedValue=htmlspecialchars($_REQUEST['CT_'.$tID], ENT_QUOTES);
                $bolSavedData = true;
            }
        }
        if ($fieldtype == "Package") {
            $tpl->assign("P","P");
            if ((isset($_REQUEST['PCT_'.$tID]))&&($_REQUEST['PCT_'.$tID]!="")) {
                $savedValue=$_REQUEST['PCT_'.$tID];
                $bolSavedData = true;
            }
        }

        if ($tRequired) {
            $class="required";
        } else {
            $class="txtbox";
        }
        $tpl->assign("CLASS", $class);
        $tpl->assign("SAVEDVALUE", $savedValue);
        //check type
         if ($tType == typeLANGUAGE) {
            $d = dir("language");
            while (false !== ($entry = $d->read())) {
               if ($entry!="." && $entry!=".." &&  $entry != 'CVS' && strpos($entry, '.txt') !== false) {
                     $entry = ucfirst(strtolower(substr($entry, 0, -4)));
                     $tValue = $gSettingsArray["Language"];
                  if ($tValue==$entry) {
                    $selected = "selected";
                  } else {
                    $selected = "";
                  }
                  $tpl->assign("ENTRY", $entry);
                  $tpl->assign("SELECTED", $selected);
                  $tpl->parse("OPTIONS", ".options");
               }
            }
            $d->close();
            $arrRemove[] = 'langField';
            $tpl->parse("TYPELANGUAGE", "typelanguage");
        } elseif ($tType == typeSTATE) {
            $tpl->parse("GETTAXSTATE", "gettaxState");
            $tpl->parse("TYPESTATE", "typestate");
        } elseif ($tType == typeTEXTAREA) {
            $tpl->parse("TYPETEXTAREA", "typetextarea");
        } elseif ($tType == typeDROPDOWN) {
            //drop down options
            $script_name_array = explode(",", trim($dropdownoptions));
            $ii = count($script_name_array);
            for($i=0;$i<$ii;$i++){
                $tpl->assign("SCRIPTNAMEARRAY", $script_name_array[$i]);
                if ($savedValue==$script_name_array[$i]){
                    $selected = "selected";
                } else {
                    $selected = "";
                }
                $tpl->assign("SELECTED", $selected);
                $tpl->parse("OPTIONS1", ".options1");
            }
            $tpl->parse("TYPEDROPDOWN", "typedropdown");
        } elseif ($tType == typeCOUNTRY) {
            $bolCountryPresent=true;
            if ($bolSavedData){
                $tCountryCode = $savedValue;
            } else {
                $tCountryCode = $gSettingsArray["Default Country"];
            }
            $tpl->assign("DISPLAYCOUNTRYCODES", DisplayCountryCodes($tCountryCode,true));
            $tpl->parse("TYPECOUNTRY", "typecountry");
        } elseif ($tType == typeYESNO || $tType == typeALLOWEMAIL) {
                if ($savedValue=="1") {
                $selectedyes = "SELECTED";
                $selectedno = "";
            } else {
                $selectedyes = "";
                $selectedno = "SELECTED";
            }
            if ($tType == typeALLOWEMAIL) {
                $tpl->assign("ANNOUNCE_HELP", returnPopupString(lang("We urge you to subscribe to our E-mail announcements, however, if you do not wish to receive them you may opt out by selecting NO.")));
                $tpl->parse("trash", "announcementoptout");
            }
            $tpl->assign("SELECTEDYES", $selectedyes);
            $tpl->assign("SELECTEDYES", $selectedno);
            $tpl->parse("TYPEYESNO", "typeyesno");
        } elseif ($tType == typeDATE) {
            if ($GLOBALS['gSettingsArray']['Date Format'] == 'm/d/Y') {
                $tpl->assign("DATEFORMAT", '%m/%d/%Y');
            } else {
                $tpl->assign("DATEFORMAT", '%d/%m/%Y');
            }
            $tpl->parse('TYPEDATE', 'typedate');
        } else {
            $tpl->parse("TYPEOTHER", "typeother");
            if ($tType == typePHONENUMBER && $gSettingsArray['Enable MaxMind Telephone Verification']==1) {
                $tpl->assign('PHONEFIELD', $tID);
                $tpl->parse('trash', 'phonefield');
            }
        }
        if ($fieldtype == "Profile") {
            $arrCustomFields[]="CT_$tID";
            if ($tName=="Email"){
                $tpl->parse("TNAMEEMAIL", "tnameemail");
            }
            if($tRequired==1){
                $tpl->parse("TREQUIRED", "trequired");
            }

            $field .= $tpl->parse("CUSTOM_FIELDS", "custom_fields");
        } elseif ($fieldtype == "Package") {
            $arrCustomFields[]="PCT_$tID";
            if($tRequired==1){
                $tpl->parse("TREQUIRED", "trequired");
            }
            $field .= $tpl->parse("CUSTOM_FIELDS", "custom_fields");
        }
        $tpl->clear_dynamic('gettax');
        $tpl->clear_dynamic('tnameemail');
        $tpl->clear_dynamic('typelanguage');
        $tpl->clear_dynamic('typestate');
        $tpl->clear_dynamic('typetextarea');
        $tpl->clear_dynamic('options1');
        $tpl->clear_dynamic('options');
        $tpl->clear_dynamic('typedropdown');
        $tpl->clear_dynamic('typecountry');
        $tpl->clear_dynamic('typeyesno');
        $tpl->clear_dynamic('typeother');
        $tpl->clear_dynamic('phonefield');
        $tpl->clear_dynamic('typedate');
        $tpl->clear_dynamic('custom_fields');
    }

    return $field;
}

function GetClientType($package)
{
    $clienttype = false;

    $query = "SELECT planid FROM package WHERE id=?";
    $result = $GLOBALS['db']->query($query, $package);
    if ($row = $result->fetch()) {
        $clienttype = $row['planid'];
    }

    return $clienttype;
}

function _getPriceIds($str)
{
    static $priceIds = array();
    if (count($priceIds)) {
        return $priceIds;
    }

    $packageaddonsStr = explode('|', $str);
    foreach ($packageaddonsStr as $packageAddonStr) {
        if (!$packageAddonStr) {
            continue;
        }
        list($addonId, $priceId, $cycle) = explode('_', $packageAddonStr);
        $priceIds[$priceId] = array(
            'addonId'   => $addonId,
            'cycle'     => $cycle,
        );
    }

    return $priceIds;
}

function tempJSCheck() {
    global $gSettingsArray;
    global $tpl;
    // Do a check for javascript (temporary)
    // This will be removed when we add server side validation.
    if (!isset($_GET['noscript'])) {
        echo "<noscript>";
        echo "<meta http-equiv=\"refresh\" content=\"0;url=".$gSettingsArray['ClientExec URL']."/signup.php?noscript=1\" />";
        echo "</noscript>";
        return false;
    } else {
        $tpl->FastPrint('HEADER');
        ShowProgress(lang('Javascript Disabled'),0);
        $tpl->assign("SIZEOFBOX","65");
        $tpl->assign("WIDTHOFBOX","500");
        $tpl->assign("SIGNUPBLOCKDESCRIPTION",lang("Javascript Disabled"));
        $tpl->parse('SIGNUPBLOCKCONTENT', 'noscript');
        $tpl->parse("BOXSUBMIT", "boxnosubmit");
        $tpl->FastPrint("BOXSUBMIT");
        $tpl->FastPrint('FOOTER');
        return true;
    }
    // End temporary javascript check
}

function validateData() {
    $arrErrors = array();
    
    // Only check the profile custom fields and duplicate email if not an existing member
    if (!isset($_REQUEST['member']) || $_REQUEST['member'] != 'on') {
        $query = "SELECT * FROM customuserfields WHERE insignup=1 AND isrequired=1";
        $result = $GLOBALS['db']->query($query);
        while ($row = $result->fetch()) {
            if (!isset($_POST['CT_'.$row['id']]) || $_POST['CT_'.$row['id']] == '') {
                $arrErrors[] = $row['name'].' '.lang('cannot be blank');
            }
        }
        
        if (CheckEmailDuplicate(htmlspecialchars($_REQUEST['CT_4'], ENT_QUOTES))) {
            $arrErrors[] = lang('This E-mail address is already in use');
        }
    }
    
    $query = "SELECT * FROM customdomainfields WHERE insignup=1 AND isrequired=1";
    $result = $GLOBALS['db']->query($query);
    while ($row = $result->fetch()) {
        if (!isset($_POST['PCT_'.$row['id']]) || $_POST['PCT_'.$row['id']] == '') {
            $arrErrors[] = $row['name'].' '.lang('cannot be blank');
        }
    }
    
    if (isset($domain) && $domain != '' && !preg_match(DOMAIN_REGEXDOMAIN, $domain)) {
        $arrErrors[] = lang('invalid domain name');
    }
    
    return $arrErrors;
}

@ob_end_flush();
?>
