<?php

require_once 'modules/admin/views/SignupView.php';
require_once 'newedge/classes/NE_PluginCollection.php';
require_once 'modules/billing/models/Currency.php';
require_once 'modules/admin/models/Countries.php';
require_once 'modules/clients/models/ObjectCustomFields.php';

/**
* @package Admin
*/
class Signup_2_OrderForm extends SignupView
{
    var $permission     = '';
    
    function preHeaders()
    {
        $this->initialize();
    }
    
    function dispatch($fieldError = '', $billingError = '')
    {
        if(isset($_SESSION['phoneverification'])){
            unset($_SESSION['phoneverification']); // Generate new phone code and recall them
        }
        
        $this->templateInit();
        
        global $arrCustomFields;
        global $bolCountryPresent;
        
        $plugins = new NE_PluginCollection("gateways", $this->user);
        $currency = new Currency($this->user);
        
        $bolCountryPresent=false;
        
        // Added by Dixon to get the current packageid to check with the package_tld table for a free domain checking!! 
        $myPackageId = 0;
        
        $intColorIndex=1;
        $arrCustomFields = array();
        
        //Set the saved package to the package passed if it is the first time
        if(!isset($_REQUEST['oldpackage'])){
            $_REQUEST['oldpackage'] = $this->package;
        }
        
        $this->tpl->assign("CLIENTTYPE",$this->clienttype);
        $this->tpl->assign("DOMAIN",$this->domain);
        $this->tpl->assign("TRANSFER", $this->transfer);
        $this->tpl->assign("DOMAINTAXABLE", $this->settings->get('Domains Taxable')? 1 : 0);
       
        //affliates
        if(isset($_REQUEST['affcode'])){
            $this->tpl->assign("AFFCODE",$_REQUEST['affcode']);
        }else{
            $this->tpl->assign("AFFCODE","0");
        }
        
        //if error from previous order show in seperate box
        if(is_array($fieldError)){
            foreach($fieldError as $key => $value){
                $this->tpl->assign("STRERRORHTMLVALUE", $value);
                $this->tpl->parse("STRERRORHTMLVALUE", ".strerrorhtmlvalue");
            }
            
            $this->tpl->parse("STRERRORHTML","strerrorhtml");
        }
        
        //********************************************************
        //***  START POPULATION PACKAGE INFO BOX
        //********************************************************
        if($this->package != 0){
            $this->clienttype = $this->GetClientType($this->package);
            $query = "SELECT id, planname, description, price, price3, price6, price12, price24, price1included, price3included, price6included, price12included, price24included, setup, planid, taxable FROM package WHERE (planid=? AND showpackage=1) OR (id=?) ORDER BY price, id";
            $result = $this->db->query($query, $this->clienttype, $this->package);
        }else{
            $query = "SELECT id, planname, description, price, price3, price6, price12, price24, price1included, price3included, price6included, price12included, price24included, setup, planid, taxable FROM package WHERE planid=? AND showpackage=1 ORDER BY price, id";
            $result = $this->db->query($query, $this->clienttype);
        }
        
        $bolFirst = true;
        while(list($tID,$tPlanName,$tDescription,$tPrice,$tPrice3,$tPrice6,$tPrice12,$tPrice24,$tPrice1included,$tPrice3included,$tPrice6included,$tPrice12included,$tPrice24included,$tSetup,$this->clienttype,$taxable) = $result->fetch()){
            if(($bolFirst) || ($this->package==$tID)){
                $firstPackage = $tPlanName;
                
                if($this->package == 0){
                    $this->package = $tID;
                }
                
                $firstTaxable         = $taxable;
                $firstPrice           = $tPrice;
                $firstDescription     = $tDescription;
                $firstPrice3          = $tPrice3;
                $firstPrice6          = $tPrice6;
                $firstPrice12         = $tPrice12;
                $firstPrice24         = $tPrice24;
                $firstPrice1included  = $tPrice1included;
                $firstPrice3included  = $tPrice3included;
                $firstPrice6included  = $tPrice6included;
                $firstPrice12included = $tPrice12included;
                $firstPrice24included = $tPrice24included;
                $firstSetup           = $tSetup;
                $firstClientType      = $this->clienttype;
                $bolFirst             = false;
            }
            
            $this->tpl->assign("TID",$tID);
            $this->tpl->assign("TPLANNAME",$tPlanName);
            if($this->package == $tID){
                $this->tpl->assign("SELECTED","selected");
                $myPackageId  = $tID;
            }else{
                $this->tpl->assign("SELECTED","");
            }
            
            $this->tpl->parse("PACKAGEOPTIONS",".packageoptions");
        }
        
        $tDescription       = @$firstDescription;
        $tPrice1included    = @$firstPrice1included;
        $tPrice3included    = @$firstPrice3included;
        $tPrice6included    = @$firstPrice6included;
        $tPrice12included   = @$firstPrice12included;
        $tPrice24included   = @$firstPrice24included;
        $tPlanName          = @$firstPackage;
        $tSetup             = @$firstSetup;
        $tTaxable           = @$firstTaxable;
        $this->clienttype   = @$firstClientType;
        
        $this->tpl->assign("OLDPACKAGE",$this->package);
        
        if($this->package!=$_REQUEST['oldpackage']){
            $this->paymentterm = 0;
        }
        
        if((trim($tDescription) != '')
          && (trim($tDescription) != "<br>")
          && (trim($tDescription) != "<HTML><head></head><body><br></body></HTML>")){
            $this->tpl->assign("TDESCRIPTION", $tDescription);
            $this->tpl->parse("PACKAGEDESCRIPTION","packagedescription");
        }
        
        //set the proper payment term
        if($this->paymentterm == 0){
            if($tPrice1included == 1){
                $this->paymentterm = 1;
            }elseif($tPrice3included == 1){
                $this->paymentterm = 3;
            }elseif($tPrice6included == 1){
                $this->paymentterm = 6;
            }elseif($tPrice12included == 1){
                $this->paymentterm = 12;
            }elseif($tPrice24included == 1){
                $this->paymentterm = 24;
            }
        }
        
        //check to see if maybe no terms were set
        //to be visable in the signup
        if($this->paymentterm != 0){
            //Show dropdown list of available payment terms
            $strBillingCycle = NE_Lib::GetMonthLabel($this->paymentterm, $this->user);
            if($tPrice1included == 1){
                $selected = '';
                
                if(!strcmp(1, $this->paymentterm)){
                    $tPrice = $firstPrice;
                    $selected = "selected";
                }
                
                $this->tpl->assign("PAYMENTTERMSELECTED", $selected);
                $this->tpl->assign("PAYMENTTERM", $this->lang("Monthly"));
                $this->tpl->assign("PAYMENTTERMOPTIONVALUE", 1);
                $this->tpl->parse("OPTIONSPAYMENTTERM", ".optionspaymentterm");
            }
            
            if($tPrice3included == 1){
                $selected = '';
                
                if(!strcmp(3, $this->paymentterm)){
                    $tPrice = $firstPrice3;
                    $selected = "selected";
                }
                
                $this->tpl->assign("PAYMENTTERMSELECTED", $selected);
                $this->tpl->assign("PAYMENTTERM", $this->lang("Quarterly"));
                $this->tpl->assign("PAYMENTTERMOPTIONVALUE", 3);
                $this->tpl->parse("OPTIONSPAYMENTTERM", ".optionspaymentterm");
            }
            
            if($tPrice6included == 1){
                $selected = '';
                
                if(!strcmp(6, $this->paymentterm)){
                    $tPrice = $firstPrice6;
                    $selected = "selected";
                }
                
                $this->tpl->assign("PAYMENTTERMSELECTED", $selected);
                $this->tpl->assign("PAYMENTTERM", $this->lang("Semiannually"));
                $this->tpl->assign("PAYMENTTERMOPTIONVALUE", 6);
                $this->tpl->parse("OPTIONSPAYMENTTERM", ".optionspaymentterm");
            }
            
            if($tPrice12included == 1){
                $selected = '';
                
                if(!strcmp(12, $this->paymentterm)){
                    $tPrice = $firstPrice12;
                    $selected = "selected";
                }
                
                $this->tpl->assign("PAYMENTTERMSELECTED", $selected);
                $this->tpl->assign("PAYMENTTERM", $this->lang("Annually"));
                $this->tpl->assign("PAYMENTTERMOPTIONVALUE", 12);
                $this->tpl->parse("OPTIONSPAYMENTTERM", ".optionspaymentterm");
            }
            
            if($tPrice24included == 1){
                $selected = '';
                
                if(!strcmp(24, $this->paymentterm)){
                    $tPrice = $firstPrice24;
                    $selected = "selected";
                }
                
                $this->tpl->assign("PAYMENTTERMSELECTED", $selected);
                $this->tpl->assign("PAYMENTTERM", $this->lang("Every 2 Years"));
                $this->tpl->assign("PAYMENTTERMOPTIONVALUE", 24);
                $this->tpl->parse("OPTIONSPAYMENTTERM", ".optionspaymentterm");
            }
            
            if($this->paymentterm > 1
              && $this->settings->get('Include Saved Percentage') == 1
              && $firstPrice > 0){
                $saved = $firstPrice - $tPrice / $this->paymentterm;
                $saved = $saved / $firstPrice * 100;
                
                if($saved > 0.0){
                    $this->tpl->assign("YOUSAVE", $this->lang("You save")." ".$currency->format($this->currency, $saved));
                    $this->tpl->parse("SAVEDPAYMENTTERM", "savedpaymentterm");
                }
            }
            
            $this->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($this->domain != ''){
            $this->tpl->assign("DOMAIN", $this->domain);
            $domainaction = "";
            
            if($this->transfer == 1){
                $domainaction = "- " .$this->lang('Transfer');
            }elseif($this->transfer == 0){
                $domainaction = "- " .$this->lang("Register");
            }
            
            $this->tpl->assign("DOMAINACTION", $domainaction);
            
            if($this->transfer == 0 || $this->transfer == 1){
                //Add Domain Regisration Length
                //Get all prices for years for this tld
                $tld = mb_substr(strstr($this->domain, '.'),1);
                $sqlGetTLDPrices = "SELECT * FROM tld WHERE name=? ";
                $tldResult = $this->db->query($sqlGetTLDPrices, $tld);
                $bolFirst=true;
                
                $results = $tldResult->fetch();
                $tldArray = array();

                // Unserialize the pricing
                $tldPricing = unserialize($results['pricing']);
                foreach($tldPricing AS $key) {

                	$working = array(
                						'id' => $results['id'],
                						'price' => $key['price'],
					                	'period' => $key['period'],
					                	'transfer' => $key['transfer'],
					                	'renew' => $key['renew']
                	);
                	
                	$tldArray[] = $working;
                }
                
                foreach($tldArray AS $key){
                    if($bolFirst){
                        $selDomainPrice = $key['price'];
                    }
                    
                    if($key['period']==1){
                        $strYear = $this->lang("Year");
                    }else{
                        $strYear = $this->lang("Years");
                    }
                    
                    // Added by Dixon for free domain option
                    $pkgtldQuery = "SELECT COUNT(*) FROM `package_tld` WHERE tld_id =? AND package_id =?";
                    $pkgtldResult = $this->db->query($pkgtldQuery, $key['id'], $myPackageId);
                    list($isTldFree) = $pkgtldResult->fetch(); 
                    // echo $isTldFree;
                    
                    // Added by Dixon to modify the text displayed for Free Domain option enabled TLD + PACKAGE
                    if($isTldFree < 1){
                        //Format Price
                        if($this->transfer == 1){
                            $tFormattedPrice = $currency->format($this->currency, $key['transfer'], true, false, "NONE", true);
                        }else{
                            $tFormattedPrice = $currency->format($this->currency, $key['price'], true, false, "NONE", true);
                        }
                        
                        $tFormattedRenewal = $currency->format($this->currency, $key['renew'], true, false, "NONE", true);
                    }else{
                        //Format Price
                        $key['transfer'] = 0;
                        $key['price'] = 0;
                        $key['renew'] = 0;
                        
                        if($this->transfer == 1){
                            $tFormattedPrice = $currency->format($this->currency, $key['transfer'], true, false, "NONE", true);
                        }else{
                            $tFormattedPrice = $currency->format($this->currency, $key['price'], true, false, "NONE", true);
                        }
                        
                        $tFormattedRenewal = $currency->format($this->currency, $key['renew'], true, false, "NONE", true);
                    }
                    
                    //Format Price
                    if($this->transfer == 1){
                        $tFormattedPrice = $currency->format($this->currency, $key['transfer'], true, false, "NONE", true);
                    }else{
                        $tFormattedPrice = $currency->format($this->currency, $key['price'], true, false, "NONE", true); 
                    }
                    
                    $tFormattedRenewal = $currency->format($this->currency, $key['renew'], true, false, "NONE", true);
                    
                    //Change text for one time domain payments
                    if($key['period'] == 0){
                        // Added by Dixon to modify the text displayed for Free Domain option enabled TLD + PACKAGE
                        if($isTldFree < 1){
                            $tText= $this->lang("One time payment of").' '.$tFormattedPrice;
                        }else{
                            $tText= $this->lang("One time payment of Free Domain").' '.$tFormattedPrice; 
                        }
                    }else{
                        // Added by Dixon to modify the text displayed for Free Domain option enabled TLD + PACKAGE
                        if($isTldFree < 1){
                            $tText= $key['period']." ".$strYear."  ".$this->lang("@")." $tFormattedPrice";
                            
                            //Add renewal price when be different
                            if($key['price'] != $key['renew']){
                                $tText .= " ".$this->lang("Renewal @")." $tFormattedRenewal";
                            }
                        }else{
                            $tText= $key['period']." ".$strYear." ".$this->lang("for")." $tFormattedPrice (".$this->lang("Free Domain").")";
                            
                            //Add renewal price when be different
                            if($key['price'] != $key['renew']){
                                $tText .= " ".$this->lang("Renewal for")." $tFormattedRenewal (".$this->lang("Free Domain").")";
                            }
                        }
                    }
                    
                    if(isset($_REQUEST['domainperiod'])
                      && ($_REQUEST['domainperiod'] == $key['period']."|".$key['price']."")){
                        $selDomainPrice = $key['price'];
                        $this->tpl->assign("TLDINFOOPTIONSELECTED","selected");
                    }else{
                        $this->tpl->assign("TLDINFOOPTIONSELECTED","");
                    }
                    
                    if($this->transfer == 1){
                        $this->tpl->assign("TLDINFOOPTIONVALUE", $key['period']."|".$key['transfer']."|".$key['renew']);
                    }else{
                        $this->tpl->assign("TLDINFOOPTIONVALUE", $key['period']."|".$key['price']."|".$key['renew']);
                    }
                    
                    $this->tpl->assign("TTEXT","$tText");
                    $bolFirst=false;
                    $this->tpl->parse("TLDINFOOPTIONS", ".tldinfooptions");
                }
                
                
                
                
                
                
                $this->tpl->parse("TLDINFO", "tldinfo");
                //End build year options
                
                // tld extended attributes
                $query = "SELECT plugin FROM tld WHERE name = ?";
                $result = $this->db->query($query, $tld);
                list ($pluginName) = $result->fetch();
                
                if($pluginName != ''){
                    $pluginsRegistrar = new NE_PluginCollection("registrars", $this->user);
                    
                    while($plugin = $pluginsRegistrar->getNext()){
                        if($plugin->getInternalName() == $pluginName){
                            if(!$response = $plugin->getExtraAttributes($tld)){
                                continue;
                            }
                            
                            $this->tpl->define_dynamic(array('tld_extended_attributes', 'domainpassed'));
                            $this->tpl->define_dynamic(array('tld_extended_attributes_select', 'tld_extended_attributes'));
                            $this->tpl->define_dynamic(array('tld_extended_attributes_options', 'tld_extended_attributes_select'));
                            $this->tpl->define_dynamic(array('tld_extended_attributes_inputbox', 'tld_extended_attributes'));
                            $tag1 = 'tld_extended_attributes';
                            
                            foreach($response as $name => $values){
                                $this->tpl->assign('EXT_ATTR_LABEL', $values['description']);
                                $tag2 = 'tld_extended_attributes_options';
                                
                                if($values['popup']){
                                    $this->tpl->assign('REQUIREDNOTE', NE_Lib::returnPopUpString($values['popup'], $this->settings));
                                }
                                
                                if(@$values['options']){
                                    $this->tpl->clear_dynamic('tld_extended_attributes_select');
                                    $this->tpl->clear_dynamic('tld_extended_attributes_inputbox');
                                    $this->tpl->assign('EXT_ATTR_SELECT_NAME', $name);
                                    
                                    foreach($values['options'] as $label => $details){
                                        $this->tpl->assign('EXT_ATTR_OPTION_VALUE', $details['value']);
                                        $this->tpl->assign('EXT_ATTR_OPTION_LABEL', $label);
                                        
                                        if(isset($_POST['ext_attr_'.$name])
                                          && $_POST['ext_attr_'.$name] == $details['value']){
                                            $this->tpl->assign('EXT_ATTR_INPUTBOX_SELECTED', 'selected');
                                        }else{
                                            $this->tpl->assign('EXT_ATTR_INPUTBOX_SELECTED', '');
                                        }
                                        
                                        $this->tpl->parse('TLD_EXTENDED_ATTRIBUTES_OPTIONS', $tag2);
                                        $tag2 = '.tld_extended_attributes_options';
                                    }
                                    
                                    $this->tpl->parse('TLD_EXTENDED_ATTRIBUTES_SELECT', 'tld_extended_attributes_select');
                                }else{
                                    $this->tpl->clear_dynamic('tld_extended_attributes_select');
                                    $this->tpl->clear_dynamic('tld_extended_attributes_inputbox');
                                    $this->tpl->assign('EXT_ATTR_INPUTBOX_NAME', $name);
                                    $this->tpl->assign('EXT_ATTR_INPUTBOX_VALUE', isset($_POST['ext_attr_'.$name])? $_POST['ext_attr_'.$name] : '');
                                    $this->tpl->parse('TLD_EXTENDED_ATTRIBUTES_INPUTBOX', 'tld_extended_attributes_inputbox');
                                }
                                
                                $this->tpl->parse('TLD_EXTENDED_ATTRIBUTES', $tag1);
                                $tag1 = '.tld_extended_attributes';
                            }
                            
                            break;  // use first registrar found
                        }
                    }
                }
            }
            
            require_once 'modules/admin/models/PackageType.php';
            
            $packageType = new PackageType($this->clienttype);
            if($packageType->isTypeDomain()){
                $this->tpl->parse("DOMAINPASSED", "domainpassed");
                
                if($this->settings->get('Prompt for domain username and password')){
                    $this->tpl->assign("NEW_DOMAIN_USERNAME", $this->domain_username);
                    $this->tpl->assign("NEW_DOMAIN_PASSWORD", $this->domain_password);
                    $this->tpl->parse("DOMAINDATA", "domaindata");
                }
            }
        }
        
        //Display Package Custom Fields
        $this->tpl->assign("DISPLAYPACKAGECUSTOMFIELDS", $this->displayCustomFields("Package"));
        $this->tpl->assign("SIGNUPBLOCKDESCRIPTION",$this->lang("Package Information"));
        $this->tpl->parse("SIGNUP_2_PACKAGEINFO","signup_2_packageinfo");
        $this->tpl->assign("SIGNUPBLOCKRIGHTTEXT","");
        $this->tpl->parse("PACKAGECUSTOMFIELDS", "packagecustomfields");
        
        // package addons
        $selectedAddons = array();
        //bug223 radio button selection
        if(isset($_POST['addonChargesStr'])){
            $selectedAddons = $this->_getPriceIds($_POST['addonChargesStr']);
        }
        
        require_once 'modules/admin/models/PackageAddonGateway.php';
        
        $packageAddonGateway = new PackageAddonGateway();
        $addons = $packageAddonGateway->getPackageAddons($this->package);
        $thereArePackageAddons = false;
        $cycleLang = array(
            1  => $this->lang('monthly'),
            3  => $this->lang('quarterly'),
            6  => $this->lang('semiannually'),
            12 => $this->lang('annually'),
            24 => $this->lang('every 2 years'),
        );
        
        while($addon = $addons->fetch()){
            $lastid = null;
            
            $query = "SELECT style FROM package WHERE id=?";
            $result = $this->db->query($query, $this->package);
            list($existStyle) = $result->fetch();
            
            $firstIteration = true;
            
            $thereAreAddonsOptions = false;
            
            foreach($addon->getCyclePrices($this->paymentterm) as $price){
                $priceOption = $price['detail'];
                
                if(!isset($price['setupFee'])){
                    $price['setupFee'] = 0;
                }
                
                if(!isset($price['cycleFee'])){
                    $price['cycleFee'] = 0;
                }
                
                if($price['setupFee'] != 0 || $price['cycleFee'] != 0){
                    $priceOption .= ': ';
                    
                    if($price['setupFee'] != 0){
                        $priceOption .= $currency->format($this->currency, $price['setupFee'], true, false, "NONE", true).' '.$this->lang('one time fee');
                        
                        if($price['cycleFee'] != 0){
                            $priceOption .= ' '.$this->lang('+').' ';
                        }
                    }
                    
                    if($price['cycleFee'] != 0){
                        $priceOption .= $currency->format($this->currency, $price['cycleFee'], true, false, "NONE", true)." ".$cycleLang[$price['cycle']];
                    }
                }
                
                $thereAreAddonsOptions = true;
                
                $this->tpl->setKey(array(
                    'ADDON_ID'          => $addon->getId(),
                    'ADDON_TAXABLE'     => $addon->getTaxable(),
                    'ADDON_NAME'        => $addon->getName(),
                    'ADDON_DESCRIPTION' => $addon->getDescription() != ''? NE_Lib::returnPopupString($addon->getDescription(), $this->settings) : '',
                    'ADDON_TAXABLE'     => $addon->getTaxable()? 1 : 0,
                ));
                
                $this->tpl->setKey(array(
                    'ADDON_PRICE_ID'             => $price['id'],
                    'ADDON_PRICE'                => $priceOption,
                    'ADDON_PRICE_FLOAT'          => $currency->format($this->currency, $price['cycleFee']),
                    'ADDON_RECURRINGPRICE_CYCLE' => $price['cycle'],
                    'ADDON_SETUPPRICE_VALUE'     => $currency->format($this->currency, (isset($price['setupFee']) && $price['setupFee'] > 0)? $price['setupFee'] : 0),
                    'ADDON_ITEM_NAME'            => $price['detail'],
                    'ADDON_ITEM_PRICE'           => $price['cycleFee'],
                    'ADDON_ITEM_SETUP'           => $price['setupFee'],
                ));
                
                // prorating for package addons
                list($tAddonPrice, $addonProratedPrice, $addonProratedDays, $addonProIncFollowing, $addonTmpNextBill, $addonProNextBill)
                  = $this->processProrating($this->settings->get('Prorate To Day'), $this->settings->get('Include Following Payment'), $price['cycle'], $price['cycleFee']);
                
                if($this->paymentterm != 0){
                    $this->tpl->setKey('ADDON_PRICE_FLOAT_PRORATED', $addonProratedPrice);
                }else{
                    $this->tpl->setKey('ADDON_PRICE_FLOAT_PRORATED', 0);
                }
                
                // Ensure we don't reinitialize the price array if it already exists
                if($lastid != $price['id']){
                    $this->tpl->parse('PACKAGEADDONPRICES', '.packageAddonsPriceItemInit');
                    $lastid = $price['id'];
                }
                
                $this->tpl->parse('PACKAGEADDONSPRICES', '.packageAddonsPriceArrItemCycle');
                
                if(!(isset($existStyle)) || ($existStyle == 0)){//dropdown
                    if($selectedAddons){
                        if(in_array($price['id'], array_keys($selectedAddons))){
                            $selArr=$selectedAddons[$price['id']];
                            $this->tpl->setKey('ADDON_PRICE_SELECTED', in_array($price['cycle'], $selArr)? 'selected = "true"' : '');
                        }else {
                            $this->tpl->setKey('ADDON_PRICE_SELECTED', $firstIteration ? 'selected = "true"' : '');
                        }
                    }else{
                        $this->tpl->setKey('ADDON_PRICE_SELECTED', $firstIteration ? 'selected = "true"' : '');
                    }
                    
                    $this->tpl->parse('PACKAGEADDONSPRICES', '.packageAddonsPrices');
                }else{//for radio button
                    if($selectedAddons){
                        if(in_array($price['id'], array_keys($selectedAddons))){
                            $selArr=$selectedAddons[$price['id']];
                            $this->tpl->setKey('ADDON_PRICE_SELECTED', in_array($price['cycle'], $selArr)? 'checked = "true"' : '');
                        }else {
                            $this->tpl->setKey('ADDON_PRICE_SELECTED', $firstIteration ? 'checked = "true"' : '');
                        }
                    }else{
                        $this->tpl->setKey('ADDON_PRICE_SELECTED', $firstIteration ? 'checked = "true"' : '');
                    }
                    
                    $this->tpl->parse('PACKAGEADDONSPRICES', '.packageAddonsPrices2');
                }
                
                $this->tpl->parse('PACKAGEADDONSPRICES', '.packageAddonsPriceArrItem');
                $this->tpl->clear_dynamic('packageAddonsPriceArrItemCycle');
                $this->tpl->clear_dynamic('packageAddonsPriceItemInit');
                $firstIteration = false;
            }
            
            if($thereAreAddonsOptions){
                $thereArePackageAddons = true;
                
                if(!(isset($existStyle)) || ($existStyle == 0)){
                    $this->tpl->setKey('ADDONS_RADIOBUTTONS', '0');
                    $this->tpl->parse('PACKAGEADDONSROW', '.packageAddonsRow');
                }else{
                    $this->tpl->setKey('ADDONS_RADIOBUTTONS', '1');
                    $this->tpl->parse('PACKAGEADDONSROW', '.packageAddonsRow2');	
                }
                
                $this->tpl->parse('PACKAGEADDONSPRICEARR', '.packageAddonsPriceArr');
                $this->tpl->clear_dynamic('packageAddonsPrices');
                $this->tpl->clear_dynamic('packageAddonsPrices2');
                $this->tpl->clear_dynamic('packageAddonsPriceArrItem');
            }
        }
        
        if($thereArePackageAddons){
            $this->tpl->assign("SIGNUPBLOCKDESCRIPTION",$this->lang("Package Add-ons"));
            
            $this->tpl->parse("SIGNUP_2_PACKAGEADDONS", "signup_2_packageaddons");
            $this->tpl->parse("SIGNUPBLOCKCONTENT","packageAddons");
        }
        //End package information
        
        //Sart billing info
        if((isset($_REQUEST['member']) && $_REQUEST['member'] == 'on')
          || ($this->user->getEmail() != '' && !$this->user->isAdmin())){
            $billingblockmember_style = '';
            $billingblock_style = 'none';
        }else{
            $billingblockmember_style = 'none';
            $billingblock_style = '';
        }
        
        //javascript for credit card
        $arraycount = 0;
        $tmpstr = '';
        $pluginarray = array();
        
        while($plugin = $plugins->getNext()){
            if(@$this->settings->get("plugin_".$plugin->getInternalName()."_Accept CC Number") == 1){
                $tmpstr .= "'".$plugin->getInternalName()."',";
                $pluginarray[] = $plugin->getInternalName();
                $arraycount++;
            }
        }
        
        $tmpstr = mb_substr($tmpstr,0,strlen($tmpstr)-1);
        $this->tpl->assign("VALIDPLUGINSFORCC", $tmpstr);
        
        $strAvailableCCArray  =  "pluginsforcc = new Array($arraycount);\n";
        $strAvailableCCArray  .=  "pluginsforcvv = new Array($arraycount);\n";
        
        for($x = 0; $x < $arraycount; $x++){
            if($this->settings->get('plugin_'.$pluginarray[$x].'_Check CVV2')
              && $this->settings->get('Forward To Gateway')){
                $useCVV = 1;
            }else{
                $useCVV = 0;
            }
            
            $strAvailableCCArray .= "pluginsforcc['".$pluginarray[$x]."'] = new Array(4);\n";
            $strAvailableCCArray .= "pluginsforcc['".$pluginarray[$x]."'][".cCREDITVISA."] = ".$this->settings->get("plugin_".$pluginarray[$x]."_Visa").";\n";
            $strAvailableCCArray .= "pluginsforcc['".$pluginarray[$x]."'][".cCREDITMC."] = ".$this->settings->get("plugin_".$pluginarray[$x]."_MasterCard").";\n";
            $strAvailableCCArray .= "pluginsforcc['".$pluginarray[$x]."'][".cCREDITAMEX."] = ".$this->settings->get("plugin_".$pluginarray[$x]."_AmericanExpress").";\n";
            $strAvailableCCArray .= "pluginsforcc['".$pluginarray[$x]."'][".cCREDITDISC."] = ".$this->settings->get("plugin_".$pluginarray[$x]."_Discover").";\n";
            $strAvailableCCArray .= "pluginsforcvv['".$pluginarray[$x]."'] = $useCVV;\n";
        }
        
        $this->tpl->assign("ARRAYCOUNT", $arraycount);
        $this->tpl->assign("STRAVAILABLECCARRAY", $strAvailableCCArray);
        $this->tpl->assign("CCREDITVISA", cCREDITVISA);
        $this->tpl->assign("CCREDITMC", cCREDITMC);
        $this->tpl->assign("CCREDITAMEX", cCREDITAMEX);
        $this->tpl->assign("CCREDITDISC", cCREDITDISC);
        
        if($billingError != ''){
            $this->tpl->assign("THEBILLINGERROR",$billingError);
            $this->tpl->parse("BILLINGERROR","billingerror");
        }
        
        $this->tpl->assign("BILLINGBLOCKSTYLE",$billingblock_style);
        reset($plugins);
        
        //Set paymenttype to the default if passed so that it will be selecteed
        if($this->paymenttype != ''){
            $pos = strpos($this->paymenttype,"_");
            
            if($pos > 0){
                $this->settings->set('Default Gateway', mb_substr($this->paymenttype, $pos+1));
            }else{
                $this->settings->set('Default Gateway', $this->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 = 'none';
        $plugins->reset();
        
        while($plugin = $plugins->getNext()){
            //If plugin is set to be in signup script then make sure to add
            if($this->settings->get("plugin_".$plugin->getInternalName()."_In Signup") == 1){
                if($tFirstTime){
                    $tFirstVal = $plugin->getInternalName();
                    $tFirstTime=false;
                }
                
                if($this->settings->get("plugin_".$plugin->getInternalName()."_Signup Name") == ''){
                    $tSignupName = $plugin->getInternalName();
                }else{
                    $tSignupName = $this->settings->get("plugin_".$plugin->getInternalName()."_Signup Name");
                }
                
                if(@$this->settings->get("plugin_".$plugin->getInternalName()."_Auto Payment") == 1){
                    $strValue = "1_".$plugin->getInternalName();
                }else{
                    $strValue = "0_".$plugin->getInternalName();
                }
                
                if($this->paymenttype != ''){
                    $paymenttype = mb_substr($this->paymenttype, 2);
                }else{
                    $paymenttype = $this->settings->get('Default Gateway');
                }
                
                if($paymenttype == $plugin->getInternalName()){
                    $selected = $plugin->getInternalName();
                    
                    if($plugin->getInternalName() == 'paypal'){
                        $recurringVisibility = 'visible';
                    }
                    
                    $this->tpl->assign("GATEWAYSELECTED","selected");
                }else{
                    $this->tpl->assign("GATEWAYSELECTED", "");
                }
                
                $this->tpl->assign("GATEWAYVALUE",$strValue);
                $this->tpl->assign("GATEWAYTSIGNUPNAME",$tSignupName);
                $this->tpl->parse("PLUGIN_NAMES", ".plugin_names");
            }
        }
        
        if($tFirstTime){
            die("<div style=\"color:red; font-weight:bold; font-size:12px; text-align:center\">CONFIGURATION ERROR:<br /><br />Please set up at least one payment gateway under System Setup -> Plugins -> Payment Processors to enable the sign up section</div>");
        }
        
        if($selected == ''){
            $selected=$tFirstVal;
        }
        
        $checked = isset($_REQUEST['use_paypal_subscriptions'])? 'checked' : '';
        
        if(!($tPrice1included || $tPrice3included || $tPrice6included || $tPrice12included || $tPrice24included)
          && ($this->domain =="" || !($this->transfer == 0 || $this->transfer == 1))){
            // don't show paypal subscriptions option if there's no billing cycle for this package and there are no domain fees
            $this->tpl->parse("NOT_PRICE_INCLUDED", "not_price_included");
        }elseif(!is_null($this->settings->get('plugin_paypal_Paypal Subscriptions Option In Signup'))
          && $this->settings->get('plugin_paypal_Paypal Subscriptions Option In Signup') ==  0){
            $this->tpl->assign("CHECKED", $checked);
            $this->tpl->assign("USERECURRINGSUBSCRIPTIONNOTE", NE_Lib::returnPopUpString($this->lang("Check to use PayPal Subscriptions, which allow you to automatically make the periodic payments without your intervention"), $this->settings));
            $this->tpl->parse("PLUGIN_PAYPAL_FORCE", "plugin_paypal_force");
        }elseif(!is_null($this->settings->get('plugin_paypal_Paypal Subscriptions Option In Signup'))
          && $this->settings->get('plugin_paypal_Paypal Subscriptions Option In Signup') ==  1){
            $this->tpl->parse("USE_PAYPAL_SUBSCRIPTIONS", "use_paypal_subscriptions");
        }
        
        $this->tpl->assign("RECURRINGVISIBILITY", $recurringVisibility);
        
        //enter autopayment for the selected plugin
        if(@$this->settings->get("plugin_".$selected."_Auto Payment") == 1){
            $autopayment = "1";
        }else{
            $autopayment = "0";
        }
        
        $this->tpl->assign("AUTOPAYMENT", $autopayment);
        $displaycc = $displaycvv2 = '';
        
        if(is_null($this->settings->get("plugin_".$selected."_Accept CC Number"))
          || $this->settings->get("plugin_".$selected."_Accept CC Number") == 0){
            $displaycc = $displaycvv2 = "none";
        }elseif(!$this->settings->get('plugin_'.$selected.'_Check CVV2')
          || !$this->settings->get('Forward To Gateway')){
            $displaycvv2 = 'none';
        }
        
        $this->tpl->assign("DISPLAYCC", $displaycc);
        $this->tpl->assign("DISPLAYCVV2", $displaycvv2);
        $this->tpl->assign("INTCOLORINDEX", NE_Lib::getAltColor($intColorIndex));
        
        //credit card information if the select plugin accepts it
        $this->tpl->assign("CCNUMBER", $this->ccnumber);
        $this->tpl->assign("CVV2", isset($_POST['cvv2'])? htmlspecialchars($_POST['cvv2']) : '');
        $cvv2help = $this->user->lang("<u>Visa/MasterCard/Discover:</u><br />The CVV2 number is the 3 digit value printed on the back of the card.  It follows the credit card number in the signature area of the card.")."<br /><center><img src='images/cvv2.jpg' /></center><br /><br />";
        $cvv2help .= $this->user->lang("<u>American Express:</u><br />The CVV2 number is the 4 digit value printed on the front of the card above the credit card number.")."<br /><center><img src='images/cvv2amex.jpg' /></center>";
        $this->tpl->assign("CVV2HELP" , NE_Lib::returnPopUpString($cvv2help, $this->settings));
        
        //determine if selected plugin needs to ensure valid_cc number
        if(in_array($selected, $pluginarray)){
            $this->tpl->assign("INVALIDCC", $this->lang("Invalid Credit Card Number"));
            $this->tpl->assign("REQUIREDCC", $this->lang("Credit Card is Required"));
            
            if($this->settings->get('plugin_'.$selected.'_Check CVV2')
              && $this->settings->get('Forward To Gateway')){
                $this->tpl->assign("REQUIREDCVV2", $this->lang("CVV2 number is required"));
            }else{
                $this->tpl->assign("REQUIREDCVV2", '');
            }
        }else{
            $this->tpl->assign("INVALIDCC", '');
            $this->tpl->assign("REQUIREDCC", '');
            $this->tpl->assign("REQUIREDCVV2", '');
        }
        
        //get the passed ccmonth
        $tempCCMonth = $this->ccmonth;
        
        $monthnames = array(
            $this->lang("January"),
            $this->lang("February"),
            $this->lang("March"),
            $this->lang("April"),
            $this->lang("May"),
            $this->lang("June"),
            $this->lang("July"),
            $this->lang("August"),
            $this->lang("September"),
            $this->lang("October"),
            $this->lang("November"),
            $this->lang("December")
        );
        
        for($i = 1;$i <= 12; $i++){
            if(!(strcmp($i, $tempCCMonth))){
                $this->tpl->assign("MONTHSELECTED", " selected");
            }else{
                $this->tpl->assign("MONTHSELECTED", "");
            }
            
            $this->tpl->assign("MONTHNAME", $monthnames[$i-1]);
            $this->tpl->assign("MONTHVALUE", $i);
            
            if($i < 10){
                $this->tpl->assign("MONTHNUMBER", "0" . $i);
            }else{
                $this->tpl->assign("MONTHNUMBER", $i);
            }
            
            $this->tpl->parse("MONTHOPTION",".monthoption");
        }
        
        $tempCCYear = $this->ccyear;
        $curYear = date("Y");
        
        for($i = 0;$i <= 15; $i++){
            if(!(strcmp($curYear, $tempCCYear))){
                $this->tpl->assign("YEARSELECTED", " selected");
            }else{
                $this->tpl->assign("YEARSELECTED", '');
            }
            
            $this->tpl->assign("CCYEAR", $curYear);
            $this->tpl->parse("YEAROPTION",".yearoption");
            $curYear++;
        }
        
        $visabit=0;
        $mcbit=0;
        $amexbit=0;
        $discbit=0;
        $visastyle = '';
        $mastercardstyle = '';
        $americanexpressstyle = '';
        $discoverstyle = '';
        
        //check the cards we are accepting
        if(is_null($this->settings->get("plugin_".$selected."_Visa"))
          || $this->settings->get("plugin_".$selected."_Visa") == 0){
            $visastyle="none";
        }else{
            $visabit=1;
        }
        
        if(is_null($this->settings->get("plugin_".$selected."_MasterCard"))
          || $this->settings->get("plugin_".$selected."_MasterCard") == 0){
            $mastercardstyle="none";
        }else{
            $mcbit=1;
        }
        
        if(is_null($this->settings->get("plugin_".$selected."_AmericanExpress"))
          || $this->settings->get("plugin_".$selected."_AmericanExpress") == 0){
            $americanexpressstyle="none";
        }else{
            $amexbit=1;
        }
        
        if(is_null($this->settings->get("plugin_".$selected."_Discover"))
          || $this->settings->get("plugin_".$selected."_Discover") == 0){
            $discoverstyle="none";
        }else{
            $discbit=1;
        }
        
        // ****** Coupons **************
        $this->tpl->define_dynamic(array('coupons' => 'tables2_step2'));
        
        if($this->settings->get('Accept Coupons')){
            if($this->couponcode != ""){
                $this->tpl->assign('couponCode', $this->couponcode);
                $this->tpl->define_dynamic(array('validateCoupon' => 'tables2_step2'));
                $this->tpl->parse('trash', 'validateCoupon');
            }else{
                $this->tpl->assign('couponCode', '');
            }
            
            $this->tpl->parse('trash', 'coupons');
        }
        
        $this->tpl->assign("VISASTYLE", $visastyle);
        $this->tpl->assign("MASTERCARDSTYLE", $mastercardstyle);
        $this->tpl->assign("AMEXSTYLE", $americanexpressstyle);
        $this->tpl->assign("DISCSTYLE", $discoverstyle);
        $this->tpl->assign("BITVALIDCC", "$visabit$mcbit$amexbit$discbit");
        $this->tpl->assign("BILLINGBLOCKMEMBER", $billingblockmember_style);
        $this->tpl->assign("SIGNUPBLOCKDESCRIPTION",$this->lang("Billing Information"));
        $this->tpl->parse("SIGNUP_2_BILLINGINFO","signup_2_billinginfo");
        $this->tpl->assign("SIGNUPBLOCKRIGHTTEXT","");
        $this->tpl->parse("BILLINGINFORMATION", "billinginformation");
        //<!-- ***  END BILLING INFORMATION BLOCK *** -->
        
        //<!-- ***  BEGIN ACCOUNT INFORMATION BLOCK *** -->
        $displayAccountInfo = '';
        
        if((isset($_REQUEST['member'])&&$_REQUEST['member'] == 'on')
          || ($this->user->getEmail() != '' && !$this->user->isAdmin())){
            $strCheckedMemberInput = " CHECKED";
            $memberinfo_style = '';
            $accountinfo_style = 'none';
            
            if($this->user->getEmail() != '' && !$this->user->isAdmin()){
                $displayAccountInfo = 'none';
            }
        }else{
            $strCheckedMemberInput = '';
            $memberinfo_style = 'none';
            $accountinfo_style = '';
        }
        
        $this->tpl->assign('DISPLAY_ACCOUNT_INFO', $displayAccountInfo);
        $this->tpl->assign("MEMBERINFO_STYLE", $memberinfo_style);
        $this->tpl->assign("MEMBER_EMAIL", $this->member_email);
        $this->tpl->assign("MEMBER_PASSWORD", $this->member_password);
        $this->tpl->assign("ACCOUNTINFO_STYLE", $accountinfo_style);
        $this->tpl->assign("DISPLAYPROFILECUSTOMFIELDS", $this->displayCustomFields("Profile"));
        //get list of custom fields that are available in signup
        $this->tpl->assign("NEW_PASSWORD", $this->new_password);
        $this->tpl->assign("NEW_PASSWORD_CONFIRM", $this->new_password_confirm);
        
        if($this->settings->get('Request Access Code') == 1 && $this->user->getEmail() == ''){
            $this->tpl->assign("ENTERACCODE", NE_Lib::returnPopUpString($this->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.'), $this->settings));
            $this->tpl->parse("REQUEST_ACCESS_CODE", "request_access_code");
        }
        
        $this->tpl->assign("CHECKEDMEMBERINPUT", $strCheckedMemberInput);
        
        $this->tpl->parse("SIGNUP_2_ACCOUNTINFO" , "signup_2_accountinfo");
        $this->tpl->parse("ACCOUNTINFORMATION", "accountinformation");
        
        $tProratedPrice = 0;
        $proratedDays = 0;
        $proIncFollowing = 0;
        $tmpNextBill = 0;
        $proNextBill = 0;
        
        if($this->domain != '' && ($this->transfer == 0 || $this->transfer == 1)){
            //do not show domain price if it isn't being passed
            $this->tpl->assign("DOMAIN",$this->domain);
        }
        
        $this->tpl->assign('PRORATING', '0');
        
        if($this->paymentterm != 0){ //do not show price if no payment methods are set to show in signup
            $this->tpl->assign("PACKAGE",$this->lang("Package"));
            $this->tpl->assign("PLANNAME", $tPlanName);
            $this->tpl->assign("SHOWPROINCFOLLOWING", $this->lang("Billed")." ".$strBillingCycle);
            
            list($tPrice, $tProratedPrice, $proratedDays, $proIncFollowing, $tmpNextBill, $proNextBill)
              = $this->processProrating($this->settings->get('Prorate To Day'), $this->settings->get('Include Following Payment'), $this->paymentterm, $tPrice);
            
            // Prorating Display
            if($proratedDays > 0){
                $this->tpl->assign(array(
                    'PRORATING'                   => 1,
                    'PRORATEDDAYS'                => $proratedDays,
                    'SHOWPRORATEDDISPLAY_PACKAGE' => $this->lang("Prorated")." ".$proratedDays." ".$this->lang("days"),
                ));
                
                if($proIncFollowing == 1){
                    $this->tpl->setKey('PACKAGECYCLE', $this->lang("Billed")." ".$strBillingCycle);
                    $this->tpl->setKey('INCLUDEFOLLOWINGPAYMENT', 1);
                }
            }else{
                $this->tpl->assign(array(
                    'PACKAGECYCLE' => $this->lang("Billed")." ".$strBillingCycle
                ));
            }
        }
        
        if($tTaxable){
            $this->tpl->assign('displaySubTotalLabel', 'block');
            $this->tpl->assign('displaySubTotalValue', 'block');
        }else{
            $this->tpl->assign('displaySubTotalLabel', 'none');
            $this->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){
            $this->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;
                $this->tpl->parse("PRORATEDDAYSMORETHAN90", "prorateddaysmorethan90");
                $this->tpl->setKey('DISABLESUBSCRIPTIONS', '1');
            }
            
            $this->tpl->parse("PRORATEDDAYS", "prorateddays");
        }
        
        if(!$disableSubscriptionsSet){
            $this->tpl->setKey('DISABLESUBSCRIPTIONS', '0');
        }
        
        if($this->domain != '' && ($this->transfer == 0 || $this->transfer == 1)){
            $this->tpl->assign('HASDOMAINNAMEREGISTRATION','1');
        }
        
        if($this->paymentterm != 0){ //do not show price if no payment methods are set to show in signup
            // Prorating Display
            if($proratedDays > 0){
                if($proIncFollowing == 1){
                    $this->tpl->assign('PACKAGEUNPRORATEDAMOUNT', $tPrice);
                }
            }else{
                $this->tpl->assign('PACKAGEUNPRORATEDAMOUNT', $tPrice);
            }
        }
        
        $this->tpl->assign("TCURRENCY", $this->currency);
        $this->tpl->assign("TSELECTEDCURRENCY", $this->selectedCurrency);
        
        //place setup price
        $this->tpl->assign('PACKAGESETUP', $tSetup);
        
        // Will need these to actually make the invoice later
        if($proratedDays > 0){
            $this->tpl->assign('PACKAGEPRORATEDAMOUNT', $tProratedPrice);
            $this->tpl->assign("PRONEXTBILL", $proNextBill);
            $this->tpl->assign("TMPNEXTBILL", $tmpNextBill);
        }
        
        $this->tpl->assign("TTAXABLE", $tTaxable);
        $this->tpl->assign("SUBMITFUNCTION","SubmitStepTwo");
        $this->tpl->assign("BACKFUNCTION","BackStepTwo");
        $this->tpl->assign("SIGNUPBLOCKDESCRIPTION",$this->lang("Checkout"));
        
        if($this->settings->get("Enable Estimated Multi-Currency") == 1){
            if($this->user->getCurrency() === 0){
                $this->tpl->setKey('currencyDropdown', $currency->ShowCurrencyDropDownList($this->selectedCurrency, 'currencyPrice', true, 'onchange="getSelectedCurrencyInfo();"'));
                $this->tpl->parse('tmulticurrencyoptions1','multicurrencyoptions1');
            }elseif($this->user->getCurrency() != $this->settings->get('Default Currency') && !$this->user->isAdmin()){
                $this->tpl->setKey(array(
                    'REALPRICEVALUE'        => $this->currency,
                    'REALPRICESELECTED'     => 'selected',
                    'CUSTOMERPRICEVALUE'    => $this->user->getCurrency(),
                    'CUSTOMERPRICESELECTED' => '',
                ));
                
                $this->tpl->parse('tmulticurrencyoptions2','multicurrencyoptions2');
            }
            $this->tpl->assign("CURRENCYNAMEVAR", $currency->getName($this->currency));
        }
        
        $this->tpl->parse('SIGNUP_2_CHECKOUT', 'signup_2_checkout');
        $this->tpl->parse("TOTALINFO", "totalinfo");
        
        $var_querystring = base64_encode(serialize($arrCustomFields));
        $this->tpl->assign("VARQUERYSTRING", $var_querystring);
        
        // Symbol of the real currency
        $realcurrencysymbol = '';
        if(strtoupper($this->currency) == "EUR"){
            $realcurrencysymbol = "&#8364;";
        }elseif(strtoupper($this->currency) == "GBP"){
            $realcurrencysymbol = "&#163;";
        }elseif(strtoupper($this->currency) == "JPY"){
            $realcurrencysymbol = "&#165;";
        }elseif($this->currency != "") {
            $realcurrencysymbol = $currency->showCurrencySymbol($this, $this->currency,false);
        }
        
        // Symbol of the selected currency
        $selectedcurrencysymbol = '';
        if(strtoupper($this->selectedCurrency) == "EUR"){
            $selectedcurrencysymbol = "&#8364;";
        }elseif(strtoupper($this->selectedCurrency) == "GBP"){
            $selectedcurrencysymbol = "&#163;";
        }elseif(strtoupper($this->selectedCurrency) == "JPY"){
            $selectedcurrencysymbol = "&#165;";
        }elseif($this->selectedCurrency != "") {
            $selectedcurrencysymbol = $currency->showCurrencySymbol($this, $this->selectedCurrency,false);
        }
        
        $this->tpl->assign("CURRENCYSYMBOLVAR", $realcurrencysymbol);
        $this->tpl->assign("CURRENCYALIGNMENTVAR", $currency->getAlignment($this->currency));
        $this->tpl->assign("CURRENCYPRECISIONVAR", $currency->getPrecision($this->currency));
        $this->tpl->assign("CURRENCYRATEVAR", $currency->getRate($this->currency));
        
        $this->tpl->assign("SELECTEDCURRENCYSYMBOLVAR", $selectedcurrencysymbol);
        $this->tpl->assign("SELECTEDCURRENCYALIGNMENTVAR", $currency->getAlignment($this->selectedCurrency));
        $this->tpl->assign("SELECTEDCURRENCYPRECISIONVAR", $currency->getPrecision($this->selectedCurrency));
        $this->tpl->assign("SELECTEDCURRENCYRATEVAR", $currency->getRate($this->selectedCurrency));
        
        $this->tpl->assign("TTAXABLE", $tTaxable);
        $this->tpl->assign("SUBTOTALVAR", $tSetup+$tPrice+$tProratedPrice); //added prorate price
        $this->tpl->assign('ISCOUNTRYSET', $bolCountryPresent? '1' : '0');
        
        $this->tpl->parse("SIGNUP_2_ORDERFORM","signup_2_orderform");
        $this->tpl->FastPrint("SIGNUP_2_ORDERFORM");
        
        $this->tpl->FastPrint("FOOTER");
    }
    
    function displayCustomFields($fieldtype)
    {
        $field = '';
        global $arrCustomFields;
        
        $countries = new Countries($this->user);
        
        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{
            /* *** NEW CODE *** */
            $query = "SELECT id, "
                    ."name, "
                    ."fieldType, "
                    ."isRequired, "
                    ."20, "
                    ."dropDownOptions "
                    ."FROM customField "
                    ."WHERE groupId = ".CUSTOM_FIELDS_FOR_PACKAGE." "
                    ."AND InSignup = 1 "
                    ."AND inSettings = 1 "
                    ."ORDER BY fieldOrder ";
            /* *** NEW CODE *** */
            
            
            /* *** OLD CODE *** */
            /*
            $query = "SELECT id, "
                    ."name, "
                    ."type, "
                    ."isRequired, "
                    ."width, "
                    ."dropdownoptions "
                    ."FROM customdomainfields "
                    ."WHERE insignup = 1 "
                    ."AND inSettings = 1 "
                    ."ORDER BY myOrder ";
            */
            /* *** OLD CODE *** */
        }
        
        $result = $this->db->query($query);
        
        while(list($tID,$tName,$tType,$tRequired,$tWidth,$dropdownoptions) = $result->fetch()){
            if($fieldtype == "Package"){
                $innerQuery = "SELECT * FROM promotion_customdomainfields WHERE promotionid=? AND customid=?";
                $innerResult = $this->db->query($innerQuery, $this->clienttype, $tID);
                
                if($innerResult->fetch()){
                    continue;
                }
            }
            
            $this->tpl->assign("TID", $tID);
            $this->tpl->assign("TNAME", $this->varLang($tName));
            $this->tpl->assign("TTYPE", $tType);
            $this->tpl->assign("TREQUIRED", $tRequired);
            $this->tpl->assign("TWIDTH", $tWidth);
            $this->tpl->assign("DROPDOWNOPTIONS", $dropdownoptions);
            $savedValue="";
            $bolSavedData = false;
            
            if($fieldtype == "Profile"){
                $this->tpl->assign("P","");
                $this->tpl->parse("GETTAX","gettaxCountry");
                
                if((isset($_REQUEST['CT_'.$tID]))&&($_REQUEST['CT_'.$tID]!="")){
                    $savedValue=htmlspecialchars($_REQUEST['CT_'.$tID], ENT_QUOTES);
                    $bolSavedData = true;
                }
            }
            
            if($fieldtype == "Package"){
                $this->tpl->assign("P","P");
                
                if((isset($_REQUEST['PCT_'.$tID]))&&($_REQUEST['PCT_'.$tID]!="")){
                    $savedValue=htmlspecialchars($_REQUEST['PCT_'.$tID], ENT_QUOTES);
                    $bolSavedData = true;
                }
            }
            
            if($tRequired){
                $class="required";
            }else{
                $class="txtbox";
            }
            
            $this->tpl->assign("CLASS", $class);
            $this->tpl->assign("SAVEDVALUE", $savedValue);
            
            //check type
            if($tType == typeLANGUAGE){
                $d = dir("language");
                $languages = array();
                
                while(false !== ($tentry = $d->read())){
                    if($tentry != '.'
                      && $tentry != '..'
                      && $tentry != 'CVS'
                      && strpos($tentry, '.txt') !== false
                      && $tentry != 'words.txt'){
                        $tkey = ucfirst(strtolower(mb_substr($tentry, 0, -4)));
                        $languages[$tkey] = $this->varLang($tkey);
                    }
                }
                
                $d->close();
                asort($languages);
                $tValue = $this->settings->getLanguage();
                
                foreach($languages AS $key => $entry){
                    if($tValue == $key){
                        $selected = "selected";
                    }else{
                        $selected = "";
                    }
                    
                    $this->tpl->assign("ENTRYVALUE", $key);
                    $this->tpl->assign("ENTRY", $entry);
                    $this->tpl->assign("SELECTED", $selected);
                    $this->tpl->parse("OPTIONS", ".options");
                }
                
                $arrRemove[] = 'langField';
                $this->tpl->parse("TYPELANGUAGE", "typelanguage");
            }elseif($tType == typeSTATE){
                $this->tpl->parse("GETTAXSTATE", "gettaxState");
                $this->tpl->parse("TYPESTATE", "typestate");
            }elseif($tType == typeTEXTAREA){
                $this->tpl->parse("TYPETEXTAREA", "typetextarea");
            }elseif($tType == typeDROPDOWN){
                $script_name_array = explode(",", trim($dropdownoptions));
                
                foreach($script_name_array as $option){
                    if(preg_match('/(.*)(?<!\\\)\((.*)(?<!\\\)\)/', $option, $matches)){
                        $value = $matches[2];
                        $label = $matches[1];
                    }else{
                        $value = $label = $option;
                    }
                    
                    $label = str_replace(array('\\(', '\\)'), array('(', ')'), $label);
                    $selected = (($savedValue == $value)? 'selected="selected"' : '');
                    
                    $this->tpl->setKey(array(
                        'SCRIPTNAMEARRAY_VALUE' => $value,
                        'SCRIPTNAMEARRAY_LABEL' => $label,
                        'SELECTED'              => $selected,
                    ));
                    
                    $this->tpl->parse("OPTIONS1", ".options1");
                }
                
                $this->tpl->parse("TYPEDROPDOWN", "typedropdown");
            }elseif($tType == typeCOUNTRY){
                $bolCountryPresent=true;
                
                if($bolSavedData){
                    $tCountryCode = $savedValue;
                }else{
                    $tCountryCode = $this->settings->get("Default Country");
                }
                
                $this->tpl->assign("DISPLAYCOUNTRYCODES", $countries->getCodes($tCountryCode, $this, true,true));
                $this->tpl->parse("TYPECOUNTRY", "typecountry");
            }elseif($tType == typeYESNO || $tType == typeALLOWEMAIL){
                if($savedValue=="1"){
                    $selectedyes = "SELECTED";
                    $selectedno = "";
                }else{
                    $selectedyes = "";
                    $selectedno = "SELECTED";
                }
                
                if($tType == typeALLOWEMAIL){
                    $this->tpl->assign("ANNOUNCE_HELP", NE_Lib::returnPopupString($this->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."), $this->settings));
                    $this->tpl->parse("trash", "announcementoptout");
                }
                
                $this->tpl->assign("SELECTEDYES", $selectedyes);
                $this->tpl->assign("SELECTEDNO", $selectedno);
                $this->tpl->parse("TYPEYESNO", "typeyesno");
            } elseif ($tType == TYPEDATE){
                if($this->settings->get('Date Format') == 'm/d/Y'){
                    $this->tpl->assign("DATEFORMAT", '%m/%d/%Y');
                }else{
                    $this->tpl->assign("DATEFORMAT", '%d/%m/%Y');
                }
                
                if($bolSavedData){
                    $this->tpl->assign('SAVEDVALUE', $savedValue);
                }else{
                    $this->tpl->assign('SAVEDVALUE', '');
                }
                
                $this->tpl->parse('TYPEDATE', 'typedate');
            }elseif($tType == typeVATNUMBER){
                // Only show the VAT custom field if there is a tax rule using VAT.
                $query = "SELECT COUNT(*) FROM `taxrule` WHERE `vat`='1'";
                $vatResult = $this->db->query($query);
                $vatRow = $vatResult->fetch();
                
                if($vatRow[0] < 1){
                    continue;
                }
                
                $this->tpl->assign("BLOCKID", 'id="vatBlock"');
                
                $this->tpl->parse("TYPEVAT", "typeVAT");
            }else{
                $this->tpl->parse("TYPEOTHER", "typeother");
                
                if($tType == typePHONENUMBER){
                    $phoneVerifPlugins = new NE_PluginCollection('phoneverification', $this->user);
                    $this->tpl->assign('PHONEFIELD', $tID);
                    $this->tpl->parse('trash', 'phonefieldname');
                    while($phoneVerifPlugin = $phoneVerifPlugins->getNext(false)){
                        if($this->settings->get("plugin_{$phoneVerifPlugin}_Enabled")){
                            $this->tpl->parse('trash', 'phonefield');
                            break;
                        }
                    }
                }
            }
            
            /* START SPECIAL CASES */
            if($tType==typeORGANIZATION){
                $this->tpl->assign("ISORGANIZATION", NE_Lib::returnPopUpString($this->lang("Check here if you want to designate this account as a business rather than individual.<br><br><b>NOTE:</b> Checking this option will display the Organization name in your client selection list"), $this->settings));
                
                if(isset($_REQUEST['isOrganization'])&&$_REQUEST['isOrganization'] == 'on'){
                    $strCheckedIsOrganization = " CHECKED";
                }else{
                    $strCheckedIsOrganization = '';
                }
                
                $this->tpl->assign("CHECKEDISORGANIZATION", $strCheckedIsOrganization);
                $this->tpl->parse("ISORGANIZATION", "isorganization");
            }
            /*  END SPECIAL CASES */
            
            if($fieldtype == "Profile"){
                $arrCustomFields[]="CT_$tID";
                
                if($tName=="Email"){
                    $this->tpl->parse("TNAMEEMAIL", "tnameemail");
                }
                
                if($tRequired==1){
                    $this->tpl->parse("TREQUIRED", "trequired");
                }
                
                $field .= $this->tpl->parse("SIGNUP_2_CUSTOMFIELDS", "signup_2_customfields");
            }elseif($fieldtype == "Package"){
                $arrCustomFields[]="PCT_$tID";
                
                if($tRequired==1){
                    $this->tpl->parse("TREQUIRED", "trequired");
                }
                
                $field .= $this->tpl->parse("SIGNUP_2_CUSTOMFIELDS", "signup_2_customfields");
            }
            
            $this->tpl->clear_dynamic('gettax');
            $this->tpl->clear_dynamic('tnameemail');
            $this->tpl->clear_dynamic('typelanguage');
            $this->tpl->clear_dynamic('typestate');
            $this->tpl->clear_dynamic('typetextarea');
            $this->tpl->clear_dynamic('options1');
            $this->tpl->clear_dynamic('options');
            $this->tpl->clear_dynamic('typedropdown');
            $this->tpl->clear_dynamic('typecountry');
            $this->tpl->clear_dynamic('announcementoptout');
            $this->tpl->clear_dynamic('typeyesno');
            $this->tpl->clear_dynamic('typeother');
            $this->tpl->clear_dynamic('typeVAT');
            $this->tpl->clear_dynamic('isorganization');
            $this->tpl->clear_dynamic('phonefield');
            $this->tpl->clear_dynamic('typedate');
            $this->tpl->clear_dynamic('trequired');
            $this->tpl->clear_dynamic('signup_2_customfields');
        }
        
        return $field;
    }
}
?>
