<?php
/*

  

  Freeway eCommerce from ZacWare
  http://www.openfreeway.org

  Copyright 2007 ZacWare Pty. Ltd

  Released under the GNU General Public License
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );

	require('includes/application_top.php');
	
	define('EMAIL_PASS_1', 'Your password for this account is ');
	define('EMAIL_PASS_2', ', keep it in a safe place. (Please note: Your password is case sensitive.)');
	
	require(DIR_WS_LANGUAGES . $FSESSION->language . '/' . FILENAME_CREATE_ACCOUNT_PROCESS);
	$server_date = getServerDate(true);	

  /*function tep_validate_email($email) {
    $valid_address = true;
    
    $mail_pat = '^(.+)@(.+)$';
    $valid_chars = "[^] \(\)<>@,;:\.\\\"\[]";
    $atom = "$valid_chars+";
    $quoted_user='(\"[^\"]*\")';
    $word = "($atom|$quoted_user)";
    $user_pat = "^$word(\.$word)*$";
    $ip_domain_pat='^\[([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\]$';
    $domain_pat = "^$atom(\.$atom)*$";
    
    if (eregi($mail_pat, $email, $components)) {
    
      $user = $components[1];
      $domain = $components[2];

      // validate user  
      if (eregi($user_pat, $user)) {
        // validate domain
        if (eregi($ip_domain_pat, $domain, $ip_components)) {
          // this is an IP address
      	  for ($i=1;$i<=4;$i++) {
      	    if ($ip_components[$i] > 255) {
      	      $valid_address = false;
      	      break;
      	    }
          }
        }
        else {
          // Domain is symbolic name
          if (eregi($domain_pat, $domain)) {
  
            // domain name seems valid, but now make sure that it ends in a
            //  three-letter word (like com, net, org, gov, edu, int) or a two-letter word,
            //   representing country (ca, uk, nl), and that there's a hostname preceding 
            //   the domain or country. 
  
            $domain_components = explode(".", $domain);          
  
            // Make sure there's a host name preceding the domain.
            if (sizeof($domain_components) < 2)
              $valid_address = false;
            else {
              $top_level_domain = strtolower($domain_components[sizeof($domain_components)-1]);
              if (strlen($top_level_domain) < 2 || strlen($top_level_domain) > 6)
                $valid_address = false;
              elseif (strlen($top_level_domain) <= 6 && strlen($top_level_domain) >= 3) {
                switch ($top_level_domain) {
                  case 'com':
                  case 'net':
                  case 'org':
                  case 'gov':
                  case 'edu':
                  case 'int':
                  case 'biz':
                  case 'mil':
                  case 'info':
                  case 'name':
                  case 'aero':
                  case 'coop':
                  case 'museum':
                    break;
                  default:
                    $valid_address = false;
                    break;
                }
              }
            }
          }
          else {
      	    $valid_address = false;
      	  }
      	}
      }
      else {
        $valid_address = false;
      }
    }
    else
      $valid_address = false;

    if ($valid_address && ENTRY_EMAIL_ADDRESS_CHECK == 'true') {
      if (!checkdnsrr($domain, "MX") && !checkdnsrr($domain, "A")) {
        $valid_address = false;
      }
    }
    
    return $valid_address;
  } */
  
  if (!$FPOST['action']) {
   tep_redirect(tep_href_link(FILENAME_CREATE_ACCOUNT, '', 'NONSSL'));
 }

  $gender = $FREQUEST->postvalue('gender');
  $firstname = $FREQUEST->postvalue('firstname');
  $lastname = $FREQUEST->postvalue('lastname');
  $dob = $FREQUEST->postvalue('dob');
  $username = $FREQUEST->postvalue('username');
  $email_address = $FREQUEST->postvalue('email_address');
  $confirm_email_address = $FREQUEST->postvalue('confirm_email_address');
  $second_email_address = $FREQUEST->postvalue('second_email_address');
  if($second_email_address!='')
  		$second_confirm_email_address = $FREQUEST->postvalue('second_confirm_email_address');
    		
  $telephone = $FREQUEST->postvalue('telephone');
  $second_telephone = $FREQUEST->postvalue('second_telephone');
  $mobile = $FREQUEST->postvalue('mobile');
  $newsletter =$FREQUEST->postvalue('newsletter');
  //$reserve_newsletter = $FREQUEST->postvalue('reserve_newsletter');
  //$subscription_newsletter =$FREQUEST->postvalue('subscription_newsletter');
  $suspend_from = tep_convert_date_raw($FREQUEST->postvalue('txt_suspend_date','string','0000-00-00'));
  $resume_from=tep_convert_date_raw($FREQUEST->postvalue('txt_resume_date','string','0000-00-00'));
  $occupation=$FREQUEST->postvalue('occupation');
  $interest=$FREQUEST->postvalue('interest');
	//CGDiscountSpecials start
	$customers_discount_sign =$FREQUEST->postvalue('customers_discount_sign');
	$customers_discount = $FREQUEST->postvalue('customers_discount');
	$customers_groups_id = $FREQUEST->postvalue('customers_groups_id'); 
	if($customers_discount=='') $customers_discount='0';
	//CGDiscountSpecials end
		
  // check for newsletter is active
  $customers_type=$FREQUEST->postvalue('customers_type');
  $password = $FREQUEST->postvalue('password');
  $confirmation = $FREQUEST->postvalue('confirmation');
  $street_address = $FREQUEST->postvalue('street_address');
  $company = $FREQUEST->postvalue('company');
  $suburb = $FREQUEST->postvalue('suburb');
  $postcode = $FREQUEST->postvalue('postcode');
  $city = $FREQUEST->postvalue('city');
  $zone_id = $FREQUEST->postvalue('zone_id');
  $state = $FREQUEST->postvalue('state');
  if($state=='' || $FPOST['state1'])$state = $FREQUEST->postvalue('state1');
  $country = $FREQUEST->postvalue('country');
  $is_blocked=$FREQUEST->postvalue('is_blocked');
  if($is_blocked!='Y')
  			$is_blocked='N';
  /////////////////      RAMDOMIZING SCRIPT BY PATRIC VEVERKA       \\\\\\\\\\\\\\\\\\

/*$t1 = date("mdy"); 
srand ((float) microtime() * 10000000); 
$input = array ("A", "a", "B", "b", "C", "c", "D", "d", "E", "e", "F", "f", "G", "g", "H", "h", "I", "i", "J", "j", "K", "k", "L", "l", "M", "m", "N", "n", "O", "o", "P", "p", "Q", "q", "R", "r", "S", "s", "T", "t", "U", "u", "V", "v", "W", "w", "X", "x", "Y", "y", "Z", "z"); 
$rand_keys = array_rand ($input, 3); 
$l1 = $input[$rand_keys[0]];
$r1 = rand(0,9); 
$l2 = $input[$rand_keys[1]];
$l3 = $input[$rand_keys[2]]; 
$r2 = rand(0,9); 

$password = $l1.$r1.$l2.$l3.$r2; */

/////////////////    End of Randomizing Script   \\\\\\\\\\\\\\\\\\\

  
  
  $error = false; // reset error flag

  if (ACCOUNT_GENDER == 'true') {
    if (($gender == 'm') || ($gender == 'f')) {
      $entry_gender_error = false;
    } else {
      $error = true;
      $entry_gender_error = true;
    }
  }

  if (strlen($firstname) < ENTRY_FIRST_NAME_MIN_LENGTH) {
    $error = true;
    $entry_firstname_error = true;
  } else {
    $entry_firstname_error = false;
  }

  if (strlen($lastname) < ENTRY_LAST_NAME_MIN_LENGTH) {
    $error = true;
    $entry_lastname_error = true;
  } else {
    $entry_lastname_error = false;
  }

  if (ACCOUNT_DOB == 'true') {
    if (tep_check_date_raw($dob,EVENTS_DATE_FORMAT)) {
      $entry_date_of_birth_error = false;
    } else {
      $error = true;
      $entry_date_of_birth_error = true;
    }
  }

  if (ACCOUNT_USERNAME == 'true') {
	  if (strlen($username) < ENTRY_USERNAME_MIN_LENGTH) {
		$error = true;
		$entry_username_error = true;
	  } else {
		$entry_username_error = false;
	  }
  }
  
  if (strlen($email_address) < ENTRY_EMAIL_ADDRESS_MIN_LENGTH) {
    $error = true;
    $entry_email_address_error = true;
  } else {
    $entry_email_address_error = false;
  }

 if (!tep_validate_email($email_address)) {
    $error = true;
    $entry_email_address_check_error = true;
  }else if($email_address!=$confirm_email_address){ 
  	 $error = true;
    $entry_email_address_check_match_error = true;
  } else {
    $entry_email_address_check_error = false;
  }
  
   if($second_email_address!=''){
	  	if (!tep_validate_email($second_email_address) || $email_address==$second_email_address) {
	     	$error = true;
	    	$entry_second_email_address_check_error = true;
	  	}else if($second_email_address!=$second_confirm_email_address){ 
	      $error = true;
	      $entry_second_email_address_match_error = true;
	   } else {
	      $entry_second_email_address_match_error = false;
	      $entry_second_email_address_check_error = false;
	   }
  } 
  //rmh referral start
	$source="";
	$source_other="";
	if (HIDE_REFERRAL_BACK=='false'){
		$source =$FREQUEST->postvalue('source');
		$source_other = $FREQUEST->postvalue('source_other');
	}
//rmh referral end
	$error=false;

  if (strlen($street_address) < ENTRY_STREET_ADDRESS_MIN_LENGTH) {
    $error = true;
    $entry_street_address_error = true;
  } else {
    $entry_street_address_error = false;
  }

  if (strlen($postcode) < ENTRY_POSTCODE_MIN_LENGTH) {
    $error = true;
    $entry_post_code_error = true;
  } else {
    $entry_post_code_error = false;
  }

  if (!tep_validate_number($postcode))
  {
    $error = true;
    $integer_post_code_error = true;
  }
  else 
  {
    $integer_post_code_error = false;
  }


  function tep_validate_number($value)
  {

        if(is_numeric($value))
            $valid = true;
        else
            $valid = false;

        return $valid;
      
  }

  if (strlen($city) < ENTRY_CITY_MIN_LENGTH) {
    $error = true;
    $entry_city_error = true;
  } else {
    $entry_city_error = false;
  }

  if (!$country) {
    $error = true;
    $entry_country_error = true;
  } else {
    $entry_country_error = false;
  }

  if (ACCOUNT_STATE == 'true') {
    if ($entry_country_error) {
      $entry_state_error = true;
    } else {
      $zone_id = 0;
      $entry_state_error = false;
      $check_query = tep_db_query("select count(*) as total from " . TABLE_ZONES . " where zone_country_id = '" . tep_db_input($country) . "'");
      $check_value = tep_db_fetch_array($check_query);
      $entry_state_has_zones = ($check_value['total'] > 0);
      if ($entry_state_has_zones) {
        $zone_query = tep_db_query("select zone_id from " . TABLE_ZONES . " where zone_country_id = '" . tep_db_input($country) . "' and zone_name = '" . tep_db_input($state) . "'");
        if (tep_db_num_rows($zone_query) == 1) {
          $zone_values = tep_db_fetch_array($zone_query);
          $zone_id = $zone_values['zone_id'];
        } else {
          $zone_query = tep_db_query("select zone_id from " . TABLE_ZONES . " where zone_country_id = '" . tep_db_input($country) . "' and zone_code = '" . tep_db_input($state) . "'");
          if (tep_db_num_rows($zone_query) == 1) {
            $zone_values = tep_db_fetch_array($zone_query);
            $zone_id = $zone_values['zone_id'];
          } else {
            $error = true;
            $entry_state_error = true;
          }
        }
      } else {
        if (!$state) {
          $error = true;
          $entry_state_error = true;
        }
      }
    }
  }
// check occupation and interest value
if ((HIDE_CUSTOMER_OCCUPATION_BACK == 'false') && (is_numeric($occupation) == false)) {
        $error = true;
    }
    $entry_occupation_error=false;
    if ((HIDE_CUSTOMER_INTEREST_BACK == 'false') && (is_numeric($interest) == false)) {
        $error = true;
    }
	$entry_interest_error=false;

// check occupation and interest

if (ACCOUNT_TELEPHONE == 'true') {
  if (strlen($telephone) < ENTRY_TELEPHONE_MIN_LENGTH) {
    $error = true;
    $entry_telephone_error = true;
  } else {
    $entry_telephone_error = false;
  }
}

 
//rmh referral start
    if ((REFERRAL_REQUIRED == 'true') && (is_numeric($source) == false)) {
        $error = true;
        //$messageStack->add('create_order', ENTRY_SOURCE_ERROR);
    }

    if ((REFERRAL_REQUIRED == 'true') && (DISPLAY_REFERRAL_OTHER == 'true') &&($source == '9999') && (!tep_not_null($source_other)) ) {
        $error = true;

        //$messageStack->add('create_order', ENTRY_SOURCE_OTHER_ERROR);
    }
//rmh referral end
  if (strpos($mobile,"+")!==FALSE) {
    $error = true;
    $entry_mobile_error = true;
  } 
   

 else if (!tep_validate_number($mobile) && $mobile!='')
  {
    $error = true;
    $entry_mobile_error = true;
  }
  else
  {
    $_mobile_error = false;
  }

  $check_email = tep_db_query("select customers_email_address from " . TABLE_CUSTOMERS . " where customers_email_address = '" . tep_db_input($email_address) . "'"); // and customers_id <> '" . tep_db_input($customer_id) . "'");
  if (tep_db_num_rows($check_email)) {
    $error = true;
    $entry_email_address_exists = true;
  } else {
    $entry_email_address_exists = false;
  }
  if (ACCOUNT_USERNAME=="true"){
	  $check_name = tep_db_query("select customers_username from " . TABLE_CUSTOMERS . " where lower(customers_username) = '" . strtolower(tep_db_input($username)) . "'"); // and customers_id <> '" . tep_db_input($customer_id) . "'");
	  if (tep_db_num_rows($check_name)) {
		$error = true;
		$entry_username_exists = true;
	  } else {
		$entry_username_exists = false;
	  }
  }
/*  if(MODULE_ADMIN_PASSWORD_STRENGTH==4)
  {
  	if(!tep_check_password_strength($password))
	{
		$error=true;
		$entry_password_strength_error=true;
	}
	else
		$entry_password_strength_error=false;
  }*/
  if ($error == true) {
    $processed = true;
?>
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html <?php echo HTML_PARAMS; ?>>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
  <title><?php echo TITLE ?></title>
    
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<script language="javascript" src="includes/date-picker.js"></script>
<?php require('includes/form_check.js.php'); ?>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<!-- header //-->
<?php
  require(DIR_WS_INCLUDES . 'header.php');
?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2">
  <tr> 
<!-- body_text //-->
    <td width="100%" valign="top"><form name="account_edit" method="post" <?php echo 'action="' . tep_href_link(FILENAME_CREATE_ACCOUNT_PROCESS, '', 'SSL') . '"'; ?> onSubmit="return check_form();"><input type="hidden" name="action" value="process"><table border="0" width="100%" cellspacing="0" cellpadding="0">
      <tr>
        <td><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td class="pageHeading"><?php echo HEADING_TITLE; ?></td>
          </tr>
        </table></td>
      </tr>
<?php
  if (sizeof($navigation->snapshot) > 0) {
?>
      <tr>
        <td class="smallText"><br><?php echo sprintf(TEXT_ORIGIN_LOGIN, tep_href_link(FILENAME_LOGIN, tep_get_all_get_params(), 'SSL')); ?></td>
      </tr>
<?php
  }
?>
      <tr>
        <td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
      </tr>
      <tr>
        <td>
<?php
  $account['entry_country_id'] = STORE_COUNTRY;

  require(DIR_WS_MODULES . 'account_details.php');
?>
        </td>
      </tr>
        <td align="right" class="main" valign="middle"><br>
		<?php   echo tep_draw_checkbox_field("create_order",'Y',(isset($FPOST["create_order"])?true:false)) . '&nbsp;' . TEXT_CREATE_ORDER . '&nbsp;';
				echo tep_image_submit('button_confirm.gif', IMAGE_CONTINUE,'align=absmiddle'); ?>
		</td>
    </table></form></td>
<!-- body_text_eof //-->
    <td width="<?php echo BOX_WIDTH; ?>" valign="top"><table border="0" width="<?php echo BOX_WIDTH; ?>" cellspacing="0" cellpadding="2">
    </table></td>
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php include(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
</body>
</html>
<?php

  } else  {
  	 $encryption_style=(defined('ENCRYPTION_STYLE'))?ENCRYPTION_STYLE:'O';
     $sql_data_array = array('customers_firstname' => $firstname,
								'customers_lastname' => $lastname,
								'customers_email_address' => $email_address,
								'customers_fax' => $mobile,
								'customers_type' =>$customers_type,
								'customers_password' =>  tep_encrypt_password($password),
								//CGDiscountSpecials start
								'customers_discount' => $customers_discount_sign . $customers_discount,
								'customers_groups_id' => $customers_groups_id,
								'suspend_from' => $suspend_from,
								'resume_from' => $resume_from,
								'is_blocked'=>$is_blocked,
								//CGDiscountSpecials end
								//encription style
								'encryption_style'=>$encryption_style
								//encription style
							);
							
							
							

    if (ACCOUNT_USERNAME == 'true') $sql_data_array['customers_username'] = $username;
    if (ACCOUNT_SECOND_EMAIL == 'true') $sql_data_array['customers_second_email_address'] = $second_email_address;
    if (ACCOUNT_SECOND_PHONE == 'true') $sql_data_array['customers_second_telephone'] = $second_telephone;
    if (ACCOUNT_GENDER == 'true') $sql_data_array['customers_gender'] = $gender;
    if (ACCOUNT_DOB == 'true') $sql_data_array['customers_dob'] = tep_convert_date_raw($dob,EVENTS_DATE_FORMAT);
    if (ACCOUNT_NEWSLETTER == 'true') $sql_data_array['customers_newsletter'] = $newsletter;
    if (ACCOUNT_RESERVATION_NEWSLETTER == 'true') $sql_data_array['customers_reserve_newsletter'] = $reserve_newsletter;
    if (ACCOUNT_SUBSCRIPTION_NEWSLETTER == 'true') $sql_data_array['customers_subscription_newsletter'] = $subscription_newsletter;
	 if (ACCOUNT_TELEPHONE == 'true') $sql_data_array["customers_telephone"]=$telephone;
	 if (HIDE_CUSTOMER_OCCUPATION_BACK=='false') $sql_data_array["customers_occupation"]=$occupation;
 	 if (HIDE_CUSTOMER_INTEREST_BACK=='false') $sql_data_array["customers_interest"]=$interest;
	
    tep_db_perform(TABLE_CUSTOMERS, $sql_data_array);

    $customer_id = tep_db_insert_id();

    $sql_data_array = array('customers_id' => $customer_id,
                            //cchange line below to suit your version
							//'address_book_id' => 1,  //pre MS2
							//'address_book_id' => (int)$default_address_id, //for MS2
                            'entry_firstname' => $firstname,
                            'entry_lastname' => $lastname,
                            'entry_street_address' => $street_address,
                            'entry_postcode' => $postcode,
                            'entry_city' => $city,
                            'entry_country_id' => $country);

    if (ACCOUNT_GENDER == 'true') $sql_data_array['entry_gender'] = $gender;
    if (ACCOUNT_COMPANY == 'true') $sql_data_array['entry_company'] = $company;
    if (ACCOUNT_SUBURB == 'true') $sql_data_array['entry_suburb'] = $suburb;
    if (ACCOUNT_STATE == 'true') {
      if ($zone_id > 0) {
        $sql_data_array['entry_zone_id'] = $zone_id;
        $sql_data_array['entry_state'] = '';
      } else {
        $sql_data_array['entry_zone_id'] = '0';
        $sql_data_array['entry_state'] = $state;
      }
    }

    tep_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array);

    $address_id = tep_db_insert_id();

    tep_db_query("update " . TABLE_CUSTOMERS . " set customers_default_address_id = '" . (int)$address_id . "' where customers_id = '" . (int)$customer_id . "'");

//rmh referral start
      tep_db_query("insert into " . TABLE_CUSTOMERS_INFO . " (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created, customers_info_source_id) values ('" . (int)$customer_id . "', '0','" . tep_db_input($server_date) . "', '". (int)$source .  "')");
	  if ($source=="9999") {
        	tep_db_query("insert into " . TABLE_SOURCES_OTHER . " (customers_id, sources_other_name) values ('" . (int)$customer_id . "', '". tep_db_input($source_other) . "')");
      }
//rmh referral end

    //tep_db_query("insert into " . TABLE_CUSTOMERS_INFO . " (customers_info_id, customers_info_number_of_logons, customers_info_date_account_created) values ('" . tep_db_input($customer_id) . "', '0', now())");

    $customer_first_name = $firstname;
    $customer_default_address_id = 1;
    $customer_country_id = $country;
    $customer_zone_id = $zone_id;
    $FSESSION->set('customer_id',$customer_id);
    $FSESSION->set('customer_first_name',$customer_first_name);
    $FSESSION->set('customer_default_address_id',$customer_default_address_id);
    $FSESSION->set('customer_country_id',$customer_country_id);
    $FSESSION->set('customer_zone_id',$customer_zone_id);

// build the message content using built in template
      $send_details=array();
      
      //build merge details
      $merge_details=array();
      $merge_details[TEXT_FN]=$firstname;
      $merge_details[TEXT_LN]=$lastname;
      
      if (ACCOUNT_GENDER == 'true') {
         if ($FPOST['gender'] == 'm') {
           $merge_details[TEXT_GR] = EMAIL_GREET_MR;
         } else {
           $merge_details[TEXT_GR] = EMAIL_GREET_MS;
         }
      } else {
        $merge_details[TEXT_GR] = EMAIL_GREET_NONE;
      }
      $merge_details[TEXT_SM]=STORE_NAME;
      $merge_details[TEXT_SN]=STORE_OWNER;
      $merge_details[TEXT_SE]=STORE_OWNER_EMAIL_ADDRESS;
      if (ACCOUNT_USERNAME == 'true') {
	      $merge_details[TEXT_LE]=$username;
	  } else  {
		  $merge_details[TEXT_LE]=$email_address;
	  }

      if (ACCOUNT_USERNAME == 'true')
        $merge_details[TEXT_US]=$username;
      else
         $merge_details[TEXT_US]=$email_address;
	  
      $merge_details[TEXT_LP]=$password;

      $send_details[0]['to_name'] = $firstname . ' ' . $lastname;
      $send_details[0]['to_email'] = $email_address;
      $send_details[0]['from_name']=STORE_OWNER;
      $send_details[0]['from_email']=STORE_OWNER_EMAIL_ADDRESS;

      tep_send_default_email("CUS",$merge_details,$send_details);
		if (isset($FPOSTS["create_order"])){
				tep_redirect(tep_href_link(FILENAME_CREATE_ORDER_NEW, 'action=show_customer_details&cID=' . $customer_id));
		} else {
				tep_redirect(tep_href_link(FILENAME_CREATE_ACCOUNT_SUCCESS, 'cID=' . $customer_id, 'SSL'));
		}
  }

  require(DIR_WS_INCLUDES . 'application_bottom.php');
