### Eclipse Workspace Patch 1.0
#P gigya-dev
Index: gigya.pages.inc
===================================================================
RCS file: /cvs/drupal/contributions/modules/gigya/Attic/gigya.pages.inc,v
retrieving revision 1.1.2.16
diff -u -r1.1.2.16 gigya.pages.inc
--- gigya.pages.inc	24 Dec 2009 12:15:24 -0000	1.1.2.16
+++ gigya.pages.inc	27 Jan 2010 06:12:29 -0000
@@ -1,5 +1,5 @@
 <?php
-// $Id: gigya.pages.inc,v 1.1.2.16 2009/12/24 12:15:24 gigya Exp $
+// $Id: gigya.pages.inc,v 1.1.2.15 2009/11/29 13:23:01 gigya Exp $
 
 /**
  * @file
@@ -7,8 +7,8 @@
  */
 
 /**
- * Wrapper for the gigya javascript NotifyLogin function.
- * Creates a button which should allow a user to syncronize their account with gigya at a click of the button,
+ * 
+ * 
  */
 function gigya_connect($account, $name = NULL) {
 	
@@ -23,7 +23,7 @@
   
   $bio = gigya_getUserInfo($account->uid);
        
-  if ($bio['isLoggedIn'] == 1 || $bio['isLoggedIn'] == TRUE) {
+  if ($bio['isLoggedIn'] == 1 || $bio['isLoggedIn'] == true) {
     
     if (variable_get('gigya_connect_uiconfig_raw', '')) {
       $connect_UIConfig = variable_get('gigya_connect_uiconfig_raw', '');
@@ -32,166 +32,46 @@
       $connect_UIConfig = "<config><body><captions background-color=\"". variable_get('gigya_connect_uiconfig_color_caption_background', GIGYA_DEFAULT_CONNECTUI_COLOR_CAPTION_BACKGROUND) ."\" color=\"". variable_get('gigya_connect_uiconfig_color_caption_text', GIGYA_DEFAULT_CONNECTUI_COLOR_CAPTION_TEXT) ."\"></captions><texts color=\"". variable_get('gigya_connect_uiconfig_color_text', GIGYA_DEFAULT_CONNECTUI_COLOR_TEXT) ."\"><links color=\"". variable_get('gigya_connect_uiconfig_color_link', GIGYA_DEFAULT_CONNECTUI_COLOR_LINK) ."\"></links></texts><controls><snbuttons buttonsize=\"". variable_get('gigya_connect_uiconfig_iconsize', GIGYA_DEFAULT_ICONSIZE) ."\" color=\"". variable_get('gigya_connect_uiconfig_color_button_text', GIGYA_DEFAULT_CONNECTUI_COLOR_BUTTON_TEXT) ."\"></snbuttons><scrollingarrow color=\"". variable_get('gigya_connect_uiconfig_color_navigation_arrow', GIGYA_DEFAULT_CONNECTUI_COLOR_NAVIGATION_ARROW) ."\"></scrollingarrow></controls><background background-color=\"". variable_get('gigya_connect_uiconfig_color_background', GIGYA_DEFAULT_CONNECTUI_COLOR_BACKGROUND) ."\" frame-color=\"". variable_get('gigya_connect_uiconfig_color_frame', GIGYA_DEFAULT_CONNECTUI_COLOR_FRAME) ."\"></background></body></config>";
     }
   }
-    $gigya_connect_params = array(
-      'connect_params' => array(
-        "headerText" => variable_get('gigya_connect_uiconfig_captionText', GIGYA_DEFAULT_CONNECTUI_CAPTIONTEXT),
-        "width" => variable_get('gigya_connect_uiconfig_width', GIGYA_DEFAULT_CONNECTUI_WIDTH),
-        "height" => variable_get('gigya_connect_uiconfig_height', GIGYA_DEFAULT_CONNECTUI_HEIGHT),
-        "containerID" => variable_get('gigya_connect_uiconfig_containerID', GIGYA_DEFAULT_CONNECTUI_CONTAINERID),
-        "showTermsLink" => variable_get('gigya_connect_uiconfig_terms', TRUE),
-        "hideGigyaLink" => variable_get('gigya_connect_uiconfig_branding', TRUE),
-        "useFacebookConnect" => variable_get('gigya_login_advanced_facebookconnect', GIGYA_DEFAULT_LOGINUI_FBCONNECT),
-        "UIConfig" => $connect_UIConfig,
-      ),
-    );
-    drupal_add_js(array('gigya' => $gigya_connect_params), 'setting');    
-    $form['gigya'] = array(
-      '#type' => 'fieldset',
-      '#theme' => 'gigya_connect_display',
-      '#description' => t('You may connect your profile to additional social networks here.'),
-    );
-
-    $form['gigya']['connect'] = array(
-      '#weight' => 10,
-      '#value' => '&nbsp;',
-      '#prefix' => '<div class="gigya editConnectionsUI"><strong>Social Network Connections</strong><div id="'. variable_get('gigya_connect_uiconfig_containerID', GIGYA_DEFAULT_CONNECTUI_CONTAINERID) .'">',
-      '#suffix' => '</div><script type="text/javascript">
-          var connect_params = Drupal.settings.gigya.connect_params;
-          connect_params.width = parseInt(connect_params.width);
-          connect_params.height = parseInt(connect_params.height);
-          gigya.services.socialize.showEditConnectionsUI(Drupal.settings.gigya.conf,connect_params);</script></div>',
-    );
-
-    $linked_networks = _gigya_get_linked_networks($account->uid);
-    if (!$linked_networks)
-      $linked_networks[variable_get('site_name', '')] = $account->uid;
-
-    // Retrieve actions that are already assigned to this hook-op combination.
-    if (count($linked_networks) > 1) {
-      $form['gigya']['assigned']['#type'] = 'value';
-      $form['gigya']['assigned']['#weight'] = -1;
-      $form['gigya']['assigned']['#value'] = array();
-      foreach ($linked_networks as $network => $gid) {
-        $form['gigya']['assigned']['#value'][$network] = array(
-          'description' => $network,
-          'link' => l(t('unlink network'), "user/". $account->uid ."/edit/gigya/unlink/". base64_encode($gid)),
-        );
-      }
-    }
-    else if (count($linked_networks) == 1) {
-      if ($bio['loginProvider']) {
-        $msg = $bio['loginProvider'];
-      }
-      else {
-       $msg = t('this site');
-      }
-      
-      foreach ($linked_networks as $network => $gid) {
-        $form['gigya']['assigned'] = array(
-          '#title' => t("Connected Networks"),
-          '#value' => t("You are currently using <strong>%network</strong> as your login provider", array('%network' => $msg)),
-        );
-      }
-    }
   
-    
-  return drupal_render($form);
-}
-
-/**
- * The overriden form submit form to get the gigya parameters stored in save_profile
- */
-function gigya_user_register_form_submit($form, &$form_state) {
-  global $user,$_gigya_uid;
-   
-  if (!$user || $user->uid == 0) {
-    user_external_login_register($form_state['values']['name'], 'gigya');
-    $account = user_load(array('name' => $form_state['values']['name']));
-    user_save($account, array('mail' => $form_state['values']['mail']));
-    $_SESSION['gigya_uid'] = $form_state['values']['gigya_uid'];    
-    if (module_exists('profile')) {
-      $categories = variable_get('gigya_profile_categories', '');
-      foreach ($categories as $cat_name) {
-        profile_save_profile($form_state['values'], $account, $cat_name, TRUE);
-      }
-    }
-    $user = $account;
-  }
-  if ($user && $user->uid > 0) {
-    $_SESSION['gigya_uid'] = $form_state['values']['gigya_uid'];
-    $edit = array(
-      'uid' => $user->uid,
-      'gigya_uid' => $form_state['values']['gigya_uid'],
-      'loginProvider' => $form_state['values']['loginProvider'],
-    );
-    gigya_save_profile($edit);
-  }
-}
-
-/**
- * Confirm removal of an assigned action.
- *
- * @param $hook
- * @param $op
- * @param $aid
- *   The action ID.
- * @ingroup forms
- * @see trigger_unassign_submit()
- */
-function gigya_unlink($form_state, $gidraw = NULL) {
-  global $user;
-  $gid = base64_decode($gidraw);
-  if (!($gid)) {
-    drupal_goto('user/'. $user->uid .'/edit');
-  }
-  $form['gid'] = array(
-    '#type' => 'value',
-    '#value' => $gid,
+  $gigya_connect_params = array(
+    'connect_params' => array(
+      "headerText" => variable_get('gigya_connect_uiconfig_captionText', GIGYA_DEFAULT_CONNECTUI_CAPTIONTEXT),
+      "width" => variable_get('gigya_connect_uiconfig_width', GIGYA_DEFAULT_CONNECTUI_WIDTH),
+      "height" => variable_get('gigya_connect_uiconfig_height', GIGYA_DEFAULT_CONNECTUI_HEIGHT),
+      "containerID" => variable_get('gigya_connect_uiconfig_containerID', GIGYA_DEFAULT_CONNECTUI_CONTAINERID),
+      "showTermsLink" => variable_get('gigya_connect_uiconfig_terms', TRUE),
+      "hideGigyaLink" => variable_get('gigya_connect_uiconfig_branding', TRUE),
+      "useFacebookConnect" => variable_get('gigya_login_advanced_facebookconnect', GIGYA_DEFAULT_LOGINUI_FBCONNECT),
+      "UIConfig" => $connect_UIConfig,
+    ),
   );
-  $form['uid'] = array(
-    '#type' => 'value',
-    '#value' => $user->uid,
+  drupal_add_js(array('gigya' => $gigya_connect_params), 'setting');    
+  $form['gigya'] = array(
+    '#type' => 'fieldset',
+    '#theme' => 'gigya_connect_display',
+    '#description' => t('You may connect your profile to additional social networks here.'),
   );
 
-  $network = _gigya_network_lookup($gid);
-
-  $destination = 'user/'. $user->uid .'/edit/gigya';
-
-  if ($gid == $_SESSION['gigya_uid']) {
-    $confmsg = t('This is your current login provider, if you unlink %title you will be logged out.', array('%title' => $network));
-  }
-  else {
-    $confmsg = t('You can assign it again later if you wish.');
-  }
-  return confirm_form($form,
-    t('Are you sure you want to unlink %title?', array('%title' => $network)),
-    $destination,
-    $confmsg,
-    t('Unlink'), t('Cancel')
+  $form['gigya']['connect'] = array(
+    '#weight' => 10,
+    '#value' => '&nbsp;',
+    '#prefix' => '<div class="gigya editConnectionsUI"><strong>Social Network Connections</strong><div id="'. variable_get('gigya_connect_uiconfig_containerID', GIGYA_DEFAULT_CONNECTUI_CONTAINERID) .'">',
+    '#suffix' => '</div><script type="text/javascript">
+        var connect_params = Drupal.settings.gigya.connect_params;
+        connect_params.width = parseInt(connect_params.width);
+        connect_params.height = parseInt(connect_params.height);
+        gigya.services.socialize.showEditConnectionsUI(Drupal.settings.gigya.conf,connect_params);</script></div>',
   );
-}
 
-function gigya_unlink_submit($form, &$form_state) {
- drupal_set_message('gigya_unlink_submit');
-  $form_values = $form_state['values'];
-  if ($form_values['confirm'] == 1) {
-    db_query("DELETE FROM {gigya} WHERE gigya_uid = '%s'", $form_values['gid']);
-    if ($form_values['gid'] == $_SESSION['gigya_uid']) {  
-    	drupal_set_message('ggigya_unlink_submitut b4 logout');  	
-      drupal_goto('socialize-logout');
-    }
-    $form_state['redirect'] = 'user/'. $form_values['uid'] .'/edit/gigya';
-  }
-  else {
-    drupal_goto('user/'. $form_values['uid'] .'/edit/gigya');
-  }
+  return drupal_render($form);
 }
 
+
 function gigya_logout_ajax() {
   global $user, $base_path;
   module_load_include('.inc', 'user', 'user.pages');
   module_load_include('inc', 'gigya');
-    
+
   if (isset($user) && $user->uid != 0) {
     $logout_behavior = array("logout_location" => $base_path ."logout");
   }
@@ -203,60 +83,89 @@
   $behavior_js = 'Drupal.behaviors.gigya_logout = function(){ gigya.services.socialize.logout(Drupal.settings.gigya.conf, {callback:Drupal.gigya.logoutResponse});};';
   drupal_add_js($behavior_js, 'inline');
   variable_set('remove_user_login_title', FALSE);
-  return '<div id="logoutMessage">'. t("Please wait while you are logged out of socialize") .'</div>';
+  return '<div id="logoutMessage">'. t("Logging out...") .'</div>';
 }
 /**
- * This function gets called from the gigya socialize login_uiconfig form. It stores the URI parameters posted from gigya
- * @return authenticated drupal user (which redirects to the authenticated session)
+
  */
 function gigya_login_ajax() {
-  global $_gigya_uid, $user, $base_path;
+
+  global $user, $base_path, $gigya_user;
   
-  	  
-  module_load_include('inc', 'gigya');    
-	if (isset($user) && $user->uid > 0) { //we already logged in, this means we're in the action.
-    	//Note, we check in the user function to see where the user is coming from. Only users who come from a login form should get here.
-	    //We need to call notifyLogin.
-    	$dest = gigya_notify_login($user->uid); //to get the login redirect parameter
-    	if (!isset($_SESSION['gigya_uid'])) { //for drupal users
-    		$userLoggedStr='gigya_' . $user->uid . '_logged';  
-  			if ( !($_SESSION[$userLoggedStr]) ) {
-  				$_SESSION[$userLoggedStr] = TRUE;  			    		
-      			$_SESSION['gigya_uid'] = $user->uid;
-      			//$dest = variable_get('gigya_login_uiconfig_urlredirect', 'user');      		
-      			$behavior_js = 'Drupal.behaviors.gigya_notifyLogin = function(){ Drupal.settings.gigya.notify_login_params.callback = Drupal.gigya.notifyLogin_callback; gigya.services.socialize.notifyLogin(Drupal.settings.gigya.conf, Drupal.settings.gigya.notify_login_params);};';
-      			drupal_add_js($behavior_js, 'inline');      			      							      			      		
-				return t('Please wait while we log you into socialize...');      			      	
-  			}
-   		}    	    	
-		drupal_goto();	
-  	}
-   	     
-  	$_gigya_uid = $_GET['UID'];
-  	if (!empty($_GET['signature']) && !empty($_GET['timestamp']) && !empty($_GET['UID'])) {  
-    	$gigya_login = array(
-      	'signature' => $_GET['signature'],
-      	'timestamp' => $_GET['timestamp'],
-      	'gigya_uid' => $_GET['UID'],
-    	);    	    
-    	return gigya_authenticate($gigya_login, TRUE);
+  drupal_set_message('gigya_login_ajax u:' . $user->uid > 0);
+  module_load_include('inc', 'gigya'); 
+  
+	if (!(isset($user) && $user->uid > 0)) { //not yet logged in to Drupal
+  
+    if($_gigya_user = GigyaUser::UserFromUrl()){
+      GigyaUser::SaveToSession($_gigya_user->uid);//we will use $gigya_user from here on out now that it's saved to the session
+	   //	include_once($base_path .'modules/user/user.pages.inc');
+         
+      $dest = $base_path . variable_get('gigya_login_uiconfig_urlredirect', 'user');
+    
+      $bio = $gigya_user->GetUserInfo();
+          
+      //check to see if the gigya_user is a drupal user
+      if ($account = user_load($gigya_user->uid)) {    
+        if (!variable_get('user_email_verification', true) || $account->login) {
+          user_external_login($account);
+        }
+        else {
+          drupal_set_message(t('You must validate your email address for this account before logging in via Gigya.'));
+        }
+        drupal_goto();
+      }
+      elseif(variable_get('user_register', 1)){ //try to register them if we're allowed to
+        $form_state['redirect'] = NULL;
+        $form_state['values']['name'] = (empty($bio['nickname']) ? '' : $bio['nickname']);
+        $form_state['values']['mail'] = (empty($bio['email']) ? '' : $bio['email']);
+        $form_state['values']['pass']  = user_password();
+        $form_state['values']['status'] = variable_get('user_register', 1) == 1;  
+        
+        $form = drupal_retrieve_form('user_register', $form_state);
+        drupal_prepare_form('user_register', $form, $form_state);
+        drupal_validate_form('user_register', $form, $form_state);
+      
+        if (form_get_errors()) {
+            // Append form validation errors below the above warning.
+            $messages = drupal_get_messages('error');
+              
+            // We were unable to register a valid new user
+            
+            drupal_goto('socialize-register',array('signature'=>$_GET['signature'],'UID'=>$_GET['UID'],'timestamp'=>$_GET['timestamp']));
+        }
+        else {
+          //save the new user
+          $account = user_save('', $form_state['values']);//possibly replace with drupal_process_form('user_register', $form, $form_state) ?
+          // Terminate if an error occured during user_save().
+          if (!$account) {
+            drupal_set_message(t("Error saving user account."), 'error');
+            drupal_goto();
+          }
+          //log in after registration -- maybe this should be an option to turn off/on?
+          user_external_login($account);
+        }
+        drupal_redirect_form($form, $form_state['redirect']);
+      }
+      else {
+        drupal_set_message(t('Only site administrators can create new user accounts.'), 'error');
+      }
   	}    
-  	
-    drupal_goto();   
+	}	
+  drupal_goto();
+	
 }
 
 /**
- * Wrapper for the gigya javascript getFriends function.
- * injects the gigya getFriends javascript function.
  */
 function gigya_get_friends($account, $name = NULL) {
   $title = isset($account->title) ? $account->title : $account->name;
   drupal_set_title(check_plain($title));
 
-  //add the onload functions
   module_load_include('inc', 'gigya');
   $site_friends = array();
-  if ($friends = gigya_getFriendsInfo(_gigya_get_gid_by_uid($account->uid) ? _gigya_get_gid_by_uid($account->uid) : $account->name)) {
+  $this_gigya_user = new GigyaUser($account->uid);
+  if ($friends = $this_gigya_user->GetFriends()) {
     foreach ($friends['friends']->friend as $friend) {
       $friend_arr = get_object_vars($friend);
       if ($friend_arr['isSiteUser'] === 'true')
@@ -284,64 +193,22 @@
 
 }
 
-
-function gigya_setStatus_replacements($form,&$msg,&$default) {	
-	global $user;
-	 
- if (isset($form['nid'])) { 	 
-    $node = node_load($form['nid']['#value']);    
-    $replacements = array('!title' => $node->title,
-                        '!url' => url('node/'. $node->nid, array('absolute' => TRUE, 'alias' => TRUE)),
-                        '!url-alias' => url('node/'. $node->nid, array('absolute' => TRUE)),
-    					'!user' => $user->name );
-    // Only generate the shortened URL if it's going to be used. No sense
-    // burning through TinyURLs without a good reason.
-    if ((strstr($msg, '!tinyurl') !== FALSE) || (strstr($default, '!tinyurl') !== FALSE)) {
-      $replacements['!tinyurl'] = gigya_shorten_url(url('node/'. $node->nid, array('absolute' => TRUE)));
-    }
-        
-    $uid = $user->uid;    
-  }
-  else if (isset($form['uid']['#value'])) {  	
-    $account = user_load($form['uid']['#value']);    
-    $replacements = array('!user' => $account->name); 
-    $uid = $account->uid;                         
-  }
-    	
-
-  $replacements['!profileurl'] = url('user/'. $uid, array('absolute' => TRUE));
-  $replacements['!sitename'] = variable_get('site_name', 'Drupal');
-                           
-  //$msg  = strtr($msg, $replacements);  
-  $default  = strtr($default, $replacements);
-
-	  
-}
-
-
 function gigya_setStatus_form($form_state, $hook, $id) {
   global $user;
-  
-    
+
   $form = array();
   $msg = $_SESSION['setStatus_msg'];
   $default = $_SESSION['setStatus_default'];
     
   if ($hook == 'user') {
     $account = user_load($id);
-    $form['uid'] = array('#type' => 'value', '#value' => $id);    
+    $form['uid'] = array('#type' => 'value', '#value' => $id);
   }
-  if ($hook == 'node') {  	
+  if ($hook == 'node') {
     $node = node_load($id);
     $form['nid'] = array('#type' => 'value', '#value' => $id);
   }
 
-
-  if ($hook == 'node' || $hook == 'user' ) { 
-  	gigya_setStatus_replacements($form,$msg,$default);
-  }
-
-  
   $form['status'] = array(
     '#type' => 'textarea',
     '#title' => t('Update Status'),
@@ -349,22 +216,18 @@
     '#default_value' => $default,
     '#cols' => 60,
     '#rows' => 3,
-    '#resizable' => FALSE,    
+    '#resizable' => FALSE,
+    
   );
-  
-        
-  
   $form['hide'] = array(
     '#type' => 'checkbox',
     '#title' => t('Never Show this Again'),
   );
 
-  
   $form['submit'] = array(
     '#type' => 'submit',
     '#value' => t('Send'),
   );
-  
   $form['close'] = array(
     '#type' => 'submit',
     '#value' => t('Close'),
@@ -374,23 +237,15 @@
   );
 
 
-  $form['gigya_uid'] = array('#type' => 'value', '#value' => _gigya_get_gid_by_uid($user->uid));
-    
-  if ( isset($_SESSION['status_sent']) ) {  	
-  	unset($form);
-  	unset($_SESSION['status_sent']);
-  }
-     
-   
+  $form['gigya_uid'] = array('#type' => 'value', '#value' => $user->uid);
   return $form;
 }
 
 function gigya_setStatus_form_submit($form, &$form_state) {
 
   global $user;
-  
-  
-  if (isset($form_state['values']['nid'])) {  
+
+  if (isset($form_state['values']['nid'])) {
     $node = node_load($form_state['values']['nid']);
 
     $replacements = array('!title' => $node->title,
@@ -404,11 +259,10 @@
     }
   }
   else if (isset($form_state['values']['uid'])) {
-    $account = node_load($form_state['values']['uid']);    
-    
+    $account = node_load($form_state['values']['uid']);
     $replacements = array('!profileurl' => url('user/'. $user->nid, array('absolute' => TRUE)),
                           '!user' => $user->name,
-                          '!sitename' => variable_get('site_name', 'Drupal'),
+                          '!sitename' => variable_get('site_name', ''),
                           );
 
   }
@@ -419,10 +273,9 @@
       gigya_setStatus($_SESSION['gigya_uid'], $status);
       user_save($user, array('setStatus_popup_hide' => $form_state['values']['hide'] ? TRUE : FALSE));
       drupal_set_message('Update sent to social networks successfully!');
-      $_SESSION['status_sent']=1;
       break;
     case 'Close':
-      user_save($user, array('setStatus_popup_hide' => $form_state['values']['hide'] ? TRUE : FALSE));      
+      user_save($user, array('setStatus_popup_hide' => $form_state['values']['hide'] ? TRUE : FALSE));
       break;
     default:
 
@@ -438,7 +291,7 @@
   $title = check_plain(variable_get('gigya_share_link_title', GIGYA_DEFAULT_SHARE_LINK_TITLE));
 
   drupal_set_title($title);
-  $friends = gigya_getFriendsInfo(_gigya_get_gid_by_uid($user->uid) ? _gigya_get_gid_by_uid($user->uid) : $user->name);
+  $friends = gigya_getFriendsInfo($user->uid);
 
   if (variable_get('gigya_friends_uiconfig_raw', '')) {
     $friends_uiconfig = variable_get('gigya_friends_uiconfig_raw', '');
@@ -467,7 +320,7 @@
   );
 
   drupal_add_js(array('gigya' => $notification_setting), 'setting');
-  $msg = variable_get('gigya_share_message', '');    
+  $msg = variable_get('gigya_share_message', '');
   $current_url = url('node/'.$node->nid,array('absolute' => TRUE));
   $urltitle = variable_get('gigya_friends_uiconfig_link_title',false) ? variable_get('gigya_friends_uiconfig_link_title',false) : url('node/'.$node->nid,array('absolute' => TRUE));
   $output = '
@@ -487,289 +340,18 @@
   return $output;
 }
 
-
-function gigya_link_accounts_or_register_form(&$form) {
-	global $_gigya_uid, $base_url;	
- 	
-	
-	$form_id = 'gigya_link_or_register_form';
-	
-	$form['form_id']['#value'] = $form_id;
-	$form['form_id']['#id'] = $form_id;
-	$form['#id'] = $form_id;
-		
-    	
-    $form['#submit'][1] = $form_id . '_submit';  
-    $form['#validate'] = array($form_id .'_validate');    
-
-	$form['origAction']= array(
-      '#type' => 'hidden', 
-      '#value' => $form['#action'],	
-    );
-                
-	$form['#parameters'][0] = $form_id;
-	$form['timezone']['#id'] = 'edit-' . $form_id . '-timezone';
-	unset($form['user_registration_help']);
-	    
-	if ( gigya_user_exists_in_drupal($_gigya_uid) ) {	 	
-	 	// The user is already registered and LINKED !!!
-	 	// After the following statment, the user is logged-in
-		return gigya_enter_user($_gigya_uid,$form['origAction']['#value']);	 		 			
-	}
-	 	 	 
-	 
-  	//Display this form and offer the user to link accounts or register.	
-	$bio = gigya_getUserInfo($_gigya_uid);
-   	if (!empty($bio['nickname'])) {
-    	$msg = t('Welcome %username,', array('%username' => $bio['nickname']));
-   	}
-   	else {
-   		$msg = t('Welcome');
-    }	
-    
-           
-    $form['welcome_title']= array(
-  	  '#type' => 'item',
-      '#value' => $msg,        
-      '#weight' => -100,
-    );  
-	$form[GIGYA_ALREADY_DRUPAL_USER] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Already a site user?'),
-        '#weight' => -50,
-        '#collapsible' => TRUE,
-        '#collapsed' => TRUE,
-        '#attributes' => array('id' => 'already-drupal-user'),
-	    '#submit' => array($form_id . '_submit'),
-   	);
-      
-      
-	$form[GIGYA_ALREADY_DRUPAL_USER]['content']= array(
-  	  '#type' => 'item',
-      '#value' => t('Link your social network account to your site login.'),        
-      '#weight' => -30,
-    );        
-       	
-	if ( isset($form['account']['name']) && ((!module_exists('profile')) || (isset($form['requiredCategories']) && is_array($form['requiredCategories']))) ) {  		
-  		$form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_name'] = $form['account']['name'];
-  	}
-  	else {
-  		$form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_name'] = $form['name'];
-   	}
-      
-     
-                  
-   	$form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_name']['#size'] = $form['pass']['#size'];                 
-    unset($form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_name']['#description']);
-   	$form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_name']['#weight'] = -20;
-	$form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_name']['#default_value'] = '';	  	  
-	  	       
-      
-    $form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_pass'] = $form['pass'];
-    $form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_pass']['#weight'] = -10;      
-    $form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_pass']['#default_value']= '';           
-      
-	$form[GIGYA_ALREADY_DRUPAL_USER]['link_accounts'] = array(
-      '#type' => 'submit',
-      '#value' => t('Link accounts'),
-      '#weight' => 1,	  
-	  '#submit' => array($form_id . '_submit'),	 	
-    );
-        
-    $form[ONLY_SOCIALIZE_USER] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Register a new user'),
-        '#weight' => 25,
-        '#collapsible' => TRUE,
-        '#collapsed' => FALSE,
-        '#attributes' => array('id' => 'only-socialize-user'),  
-        '#submit' => array($form_id . '_submit'),            
-      );      	 
-      
-	if (isset($form['origPost']['#drupal_user_name']) || isset($form['origPost']['#drupal_user_name']) ){
-		$form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_name']['#default_value'] =$form['origPost']['#drupal_user_name'];		
-		$form[GIGYA_ALREADY_DRUPAL_USER]['#collapsed'] = FALSE;
-		$form[ONLY_SOCIALIZE_USER]['#collapsed'] = TRUE;		
-	}
-	else { 
-		$form[GIGYA_ALREADY_DRUPAL_USER]['drupal_user_name']['#default_value'] = '';
-		if (isset($form['origPost']['#name']) || isset($form['origPost']['#mail']) ){
-			$form[ONLY_SOCIALIZE_USER]['#collapsed'] = FALSE;
-			$form[GIGYA_ALREADY_DRUPAL_USER]['#collapsed'] = TRUE;		
-		}	
-	}
-   	
-	$currentWeight = 40;
-
-	//drupal_set_message('acc name =' . $form['account']['name']);
-	//drupal_set_message('    name =' . $form['name']);
-	
- 	if ( isset($form['account']['name']) && ((!module_exists('profile')) || (isset($form['requiredCategories']) && is_array($form['requiredCategories']))) ) {
-	 		 	
-			$form[ONLY_SOCIALIZE_USER]['account'] = $form['account'];
- 			$form[ONLY_SOCIALIZE_USER]['account']['#weight'] = $currentWeight;
- 			$currentWeight +=20;
- 			$form[ONLY_SOCIALIZE_USER]['account']['name']['#size'] = $form['pass']['#size'];
- 			$form[ONLY_SOCIALIZE_USER]['account']['pass']['#type'] = 'hidden';
- 			$form[ONLY_SOCIALIZE_USER]['account']['pass']['#value'] = user_password(20);
- 		
- 			if ( isset($form['origPost']['#name'])) { 			
- 				$form[ONLY_SOCIALIZE_USER]['account']['name']['#default_value'] =$form['origPost']['#name'];
- 			} 
- 		
- 			if ( isset($form['origPost']['#mail'])) { 			
- 				$form[ONLY_SOCIALIZE_USER]['account']['mail']['#default_value'] =$form['origPost']['#mail'];
- 			} 
-		
-		
- 		
- 		
-		
- 		
- 		
-
- 		$enable_fb_population = variable_get('gigya_enable_facebook_population',FALSE); 
- 		
- 		if (isset($form['requiredCategories']) && is_array($form['requiredCategories'])) {
-	 		foreach($form['requiredCategories'] as $cat_name => $cat_val) { 			
-	 			$form[ONLY_SOCIALIZE_USER][$cat_name] = $form[$cat_name];
-	 			$form[ONLY_SOCIALIZE_USER][$cat_name]['#weight'] = $currentWeight; 			
-	 			$currentWeight +=20;
-	
-	 			if ( $enable_fb_population ) {
-	 				foreach($cat_val as $key=> $currVal) {
-	 					$form[ONLY_SOCIALIZE_USER][$cat_name][$key]['#default_value'] = $currVal['#default_value'];
-	 				}
-	 			}
-	 			
-	 			unset($form[$cat_name]);
-	 		} 
- 		}
- 	} 
- 	else { 		
-		$form[ONLY_SOCIALIZE_USER]['name'] = $form['name'];		
-		$form[ONLY_SOCIALIZE_USER]['name']['#weight'] = $currentWeight;
-		$currentWeight +=20;
-		$form[ONLY_SOCIALIZE_USER]['name']['#size'] = $form['pass']['#size'];
-
-		$form[ONLY_SOCIALIZE_USER]['mail'] = $form['mail'];		
-		$form[ONLY_SOCIALIZE_USER]['mail']['#size'] = $form['pass']['#size'];
-		$form[ONLY_SOCIALIZE_USER]['mail']['#weight'] = $currentWeight;	
-		$currentWeight +=20;	
-		$form[ONLY_SOCIALIZE_USER]['mail']['#required'] = TRUE;		
-		
-		$form[ONLY_SOCIALIZE_USER]['pass']['#type'] = 'hidden';
- 		$form[ONLY_SOCIALIZE_USER]['pass']['#value'] = user_password(20);
- 	
- 		if ( isset($form['origPost']['#name'])) {  			
- 			$form[ONLY_SOCIALIZE_USER]['name']['#default_value'] = $form['origPost']['#name'];
- 		}
- 		else { 			
-			$form[ONLY_SOCIALIZE_USER]['name']['#default_value'] = ''; 			
- 		} 
-	
- 		unset($form['name']);
- 		unset($form['mail']);
- 		unset($form['Personal Information']);
- 	}          
-
- 	$itemName = ONLY_SOCIALIZE_USER; 	
- 	$currentWeight = gigya_add_external_fields($form,$itemName,$currentWeight); 	
-
-	$form[ONLY_SOCIALIZE_USER]['create_account'] = array(
-      '#type' => 'submit',
-      '#value' => t('Create new account'),
-      '#weight' => $currentWeight,
-	  '#submit' => array($form_id . '_submit2'),
-    );   	
-    
-   
-	
-	unset($form['account']);     
-    unset($form['pass']);	
-	unset($form['submit']);    
-
-	$enableLinking = variable_get('gigya_enable_linking', TRUE);
-
-	if ( !$enableLinking ) {
-		unset($form[GIGYA_ALREADY_DRUPAL_USER]);
-		$form[ONLY_SOCIALIZE_USER]['#collapsible'] = FALSE;
-		$form[ONLY_SOCIALIZE_USER]['#collapsed'] = FALSE;			
-	}
-		
-	$form['currLoginProvider']= array(
-      '#type' => 'hidden', 
-      '#value' => $form['loginProvider']['#value'],	
-    );
-    
-                
-	return $form;
-}
-
-
-function gigya_add_required_fields($form_item,$parentKey,&$requiredFieldsStr,&$requiredFields) {
-  if (!is_array($form_item)) return;
-  
-        
-  if (isset($form_item['#type']) && $form_item['#type'] == 'checkbox') {
-  	if ($form_item['#required'] == TRUE) {
-  		if ( isset($form_item['#title'])) {
-  			$requiredText =$form_item['#title'];
-  		}
-  		else {
-  			if ( isset($form_item['#value'])) {
-  				$requiredText =$form_item['#value'];
-  			}
-  			else {
-  				$requiredText =	$parentKey;	
-  			}
-  		}
-  		   		  	
-  		$requiredFieldsStr .= $requiredText . ' ( ' . $parentKey . ' ),';  			  		
-  		$requiredFields .= $parentKey . ',';  			  		
-  	}  
-  }
- 
-  foreach ($form_item as $key => $val) {			
-	if ( is_array($val) ) {  
-		gigya_add_required_fields($val,$key,$requiredFieldsStr,$requiredFields);
-    }
+function gigya_register(){
+  global $user;
+  // If we are already logged on, go to the user page instead.
+  if ($user->uid) {
+    drupal_goto('user/'. $user->uid);
+  }
+  if (!($_gigya_user = GigyaUser::UserFromUrl())) {
+  //  drupal_goto();
   }
-
-}     
-
-
-
-function gigya_add_external_fields(&$form,$addToItem,&$currentWeight) {	
-		   
-    $requiredFields = '';
-    $requiredFieldsStr = '';             
-	foreach ($form as $key => $val) {			
-		if ( is_array($val) ) {
-			if ($form[$key]['#type']=='fieldset') {
-				if ( !in_array($key,array(ONLY_SOCIALIZE_USER,GIGYA_ALREADY_DRUPAL_USER,'account')) ) {					 								
-					$form[$addToItem][$key]=$form[$key];									
-					$form[$addToItem][$key]['#weight']= $currentWeight;						
-					gigya_add_required_fields($form[$addToItem][$key],$key,$requiredFieldsStr,$requiredFields);												
-					$currentWeight +=20; 	
-					unset($form[$key]);																																														
-				}  						
-			}
-		}
- 	} 	
- 	
- 	if ( $requiredFields !='') { 
- 		$form[$addToItem]['external_required']= array(
-      		'#type' => 'hidden', 
-      		'#value' => $requiredFields	
-    	);
-    	
-		$form[$addToItem]['external_requiredStr']= array(
-	      	'#type' => 'hidden', 
-	      	'#value' => $requiredFieldsStr	
-    	);    	
-    	
- 	} 
-         	 
- 	return $currentWeight;
+  
+  $bio = $_gigya_user->GetUserInfo();
+  $registration_form = drupal_get_form('user_register');
+  $link_accounts_form = drupal_get_form('gigya_link_accounts');
+  return theme('gigya_register', $bio, $registration_form, $link_accounts_form);
 }
\ No newline at end of file
Index: gigya.module
===================================================================
RCS file: /cvs/drupal/contributions/modules/gigya/Attic/gigya.module,v
retrieving revision 1.1.2.21
diff -u -r1.1.2.21 gigya.module
--- gigya.module	24 Dec 2009 12:15:24 -0000	1.1.2.21
+++ gigya.module	27 Jan 2010 06:12:29 -0000
@@ -1,5 +1,5 @@
 <?php
-// $Id: gigya.module,v 1.1.2.21 2009/12/24 12:15:24 gigya Exp $
+// $Id: gigya.module,v 1.1.2.20 2009/11/29 13:23:14 gigya Exp $
 /**
  * @file
  * This module provides a link to Gigya profiles from a users' drupal account.
@@ -34,6 +34,14 @@
     'description' => t('Gigya Configuration.'),
     'file' => 'gigya.admin.inc',
   );
+  $items['socialize-register'] = array(
+    'type' => MENU_CALLBACK,
+    'title' => t('Gigya'),
+  	'access arguments' => array('access content'),
+    'page callback' => 'gigya_register',
+    'description' => t('Gigya Registration.'),
+    'file' => 'gigya.pages.inc'
+  );
   $items['user/%user/friends'] = array(
     'title' => 'My Friends',
     'page callback' => 'gigya_get_friends',
@@ -61,7 +69,7 @@
     'access arguments' => array(),
     'file' => 'gigya.pages.inc',
   );
-  $items['user/%user_category/edit/gigya'] = array(
+  $items['user/%user/edit/gigya'] = array(
     'title' => 'Social Networks',
     'page callback' => 'gigya_connect',
     'page arguments' => array(1, 'user'),
@@ -84,16 +92,6 @@
     'access arguments' => array('access content'),
     'file' => 'gigya.pages.inc',
   );
-  $items['user/%user/edit/gigya/unlink'] = array(
-    'title' => 'Unlink',
-    'description' => 'Unlink a network from a user.',
-    'page callback' => 'drupal_get_form',
-    'page arguments' => array('gigya_unlink'),
-    'access callback' => 'user_edit_access',
-    'access arguments' => array(1),
-    'type' => MENU_CALLBACK,
-    'file' => 'gigya.pages.inc',
-  );
   $items['gigya/notifyfriends/%node'] = array(
     'page callback' => 'gigya_notify_friends',
     'page arguments' => array(2, 'node'),
@@ -116,7 +114,11 @@
  * Impletementation of hook_cron
  */
 function gigya_cron() {
-  if (variable_get('user_pictures', 0)) {
+/*by commenting this out we can no longer regularly update avatars
+ * todo: figure out a new way of handling avatars
+ */
+
+  /*if (variable_get('user_pictures', 0)) {
     $expire = time() - (24 * 3600);  
     $result = db_query('SELECT uid FROM {gigya} WHERE avatar_timestamp < %d', $expire);
     
@@ -124,7 +126,7 @@
       gigya_save_userpic($tab['uid']);
       db_query('UPDATE {gigya} SET avatar_timestamp = %d WHERE uid=%d', time(),$tab['uid']);
     }
-  }
+  }*/
 }
 
 function gigya_menu_access_user_debug() {
@@ -157,15 +159,15 @@
 }
 
 function gigya_newsfeed_action($object, $context) {
-  global $base_path;
+  global $base_path,$gigya_user;
   //notification actions here, we need to figure out a way to dynamically update a status
   //probably by showing a field, or making system configurable actions with canned action text
   module_load_include('inc', 'gigya');
-  if ($capabilities = _gigya_getUserCapabilities($_SESSION['gigya_uid'])) {
-      if (!array_search('Actions', $capabilities)) {
-        return FALSE;
-      }
+  
+  if (empty($gigya_user)) {
+    return false;
   }
+  
   $xml_params = array();
   $xml_params['action'] = $context['default_message'];
   $xml_params['template'] = $context['template'];
@@ -199,28 +201,25 @@
     !empty($xml_params['template']) &&
     !empty($xml_params['action']) &&
     !empty($xml_params['path']))
-    gigya_publish_user_action($_SESSION['gigya_uid'], $xml_params);
+    $gigya_user->PublishUserAction($xml_params);
 }
 
 function gigya_status_popup_action($object, $context) {
-  global $user;
-  
-  module_load_include('inc', 'gigya');  
+  global $user,$gigya_user;
+  module_load_include('inc', 'gigya');
 
   if ($user->setStatus_popup_hide)
     return FALSE;
     
-  if ($capabilities = _gigya_getUserCapabilities($_SESSION['gigya_uid'])) {  	  
- 	if (!array_search('Status', $capabilities)) {
-        return FALSE;
-    }
-  }
-      
-  $hook = $context['hook'];  
-  if ($hook == 'comment') {  	
-    $context['node'] = node_load($context[$hook]->nid);    
+  if(empty($gigya_user)) return false;
+  
+  if (!$gigya_user->HasCapability('Status')) return false;
+
+  $hook = $context['hook'];
+  if ($hook == 'comment') {
+    $context['node'] = node_load($context[$hook]->nid);
     $_SESSION['setStatus_msg'] = $context['gigya_status_node_description'];
-    $_SESSION['setStatus_default'] = $context['gigya_status_node_default_message'];	          
+    $_SESSION['setStatus_default'] = $context['gigya_status_node_default_message'];    
   }
   
   if ($hook == 'user') {
@@ -333,9 +332,23 @@
 }
 
 function gigya_init() {
-  global $base_path,$base_url, $user;
+  global $base_path,$base_url, $user,$gigya_user;
+  
+  
   gigya_load_js();
   
+  //make the current gigya user available
+  if($_gigya_user = GigyaUser::GetCurrentGigyaUser()){
+    $gigya_user = $_gigya_user;
+    
+    //make the current drupal gigya session info available to javascript so that it can run notifylogin, if necessary 
+    gigya_setNotifyLoginParams($gigya_user->uid);
+    
+    $bio = $gigya_user->GetUserInfo();
+    
+  }
+
+  
   if ($_SESSION['setStatus_popup']) {
   	if ( !($user->uid)) {
   		return;
@@ -357,20 +370,8 @@
 }
 
 function gigya_nodeapi(&$node, $op = 'view', $teaser, $page) {	
-  global $user;
-
-  if (FALSE !=variable_get('gigya_APIKey', FALSE)) { 
-	  if ( $user && $user->uid > 0 ) {
-	  	$userLoggedStr='gigya_' . $user->uid . '_logged';  
-	  	if ( !($_SESSION[$userLoggedStr]) ) {
-	  		$_SESSION[$userLoggedStr] = TRUE;  		   	  		
-	  		gigya_setNotifyLoginParams($user->uid,FALSE);	  		
-	  		$behavior_js = "Drupal.behaviors.gigya_notifyLogin = function(){ Drupal.settings.gigya.notify_login_params.callback = Drupal.gigya.notifyLogin_callback; gigya.services.socialize.notifyLogin(Drupal.settings.gigya.conf, Drupal.settings.gigya.notify_login_params);};";
-	      	drupal_add_js($behavior_js, 'inline');
-	  	}
-	  }
-  }  
-  
+  global $user,$gigya_user;
+    
   switch ($op) {
     case 'update':
     case 'insert':
@@ -384,12 +385,17 @@
         if (strstr($node->gigya['status'], '!tinyurl') !== FALSE) {
           $replacements['!tinyurl'] = gigya_shorten_url(url('node/'. $node->nid, array('absolute' => TRUE)));
         }
-        $status = strtr($node->gigya['status'], $replacements);        
-        if ($result = gigya_setStatus($_SESSION['gigya_uid'], $status)) {
-          drupal_set_message(t('Successfully posted to social networks'));
+        $status = strtr($node->gigya['status'], $replacements);
+        if(!empty($gigya_user)){
+          if ($result = $gigya_user->SetStatus($status)) {
+            drupal_set_message(t('Successfully posted to social networks'));
+          }
+          else {
+            drupal_set_message(t('An error occurred when posting to your social network:'));
+          }
         }
-        else {
-          drupal_set_message(t('An error occurred when posting to your social network:'));
+        else{
+          drupal_set_message(t('You are not logged in to any social networks.'));
         }
       }
       break;
@@ -404,55 +410,29 @@
  * The main API for accessing, storing, and viewing the gigya bios.
  */
 function gigya_user($op, &$edit, &$account, $category = NULL) {
-	global $base_url;
-			      
+	global $base_url, $gigya_user, $user;	
     
   module_load_include('inc', 'gigya');
   switch ($op) {
     case 'login':    	
-      if (arg(1) == 'reset') {
-        break;
-      }
-        
-      
-      if (user_get_authmaps($account->uid) == 0 || !user_get_authmaps($account->uid)) { //make sure we aren't coming from socialize
-        $dest = drupal_get_destination();
-        if (strpos($dest, 'user%2Fregister')) {
-          $_REQUEST['destination'] = 'socialize-login?destination=user';
-        }
-        else {        	
-        	if (strpos($dest, 'socialize-login')) {          		
-          		return;
-        	}
-        	else {
-        		$_REQUEST['destination'] = 'socialize-login?' . $dest;
-        	
-        	}
-        }
-      }   
-      else {
-      	if ( $account && $account->uid>0 ) {    		  							
-			$_SESSION['gigya_uid'] = $account->uid;      		
-      	}  
-
-      	$dest = variable_get('gigya_login_uiconfig_urlredirect', 'user');
-      	drupal_goto($dest);
-      }
+      GigyaUser::Login($user->uid);
       break;
     case 'logout':
-  		$userLoggedStr='gigya_' . $user->uid . '_logged';  
-	  	if ( $_SESSION[$userLoggedStr] ) {
-	  		unset($_SESSION[$userLoggedStr]);
-	  	}     
-      	unset($_SESSION['gigya_uid']);            	
-        drupal_goto('socialize-logout');
+      $gigya_user->Logout();
+      break;
     case 'update':
-      gigya_save_profile($edit, array('uid' => $account->uid, 'gigya_uid' => $edit['gigya_uid']));
+      break;
     case 'insert':
-      gigya_save_profile($edit);
+      //only link accounts if the user running this code has gigya login evidence in the URL
+      if ($_gigya_user = GigyaUser::UserFromUrl()) {
+        $bio = $_gigya_user->GetUserInfo();
+        $_gigya_user->LinkAccounts($account->uid);
+        $_gigya_user->MapExtendedProfileFields($edit);
+      }
       break;
     case 'delete':
-      gigya_delete_profile($account->uid);
+      $_gigya_user = new GigyaUser($account->uid);
+      $_gigya_user->Unlink();
       break;
     case 'categories':
       return array(
@@ -464,8 +444,9 @@
         ),
       );
     case 'view':
-      $content = '';        		         
-      $bio = gigya_getUserInfo($account->uid);
+      $content = '';
+      $_gigya_user = new GigyaUser($account->uid);
+      $bio = $_gigya_user->GetUserInfo();
                    
       if (!empty($bio['identities'])) {
         foreach ($bio['identities']->identity as $network_obj) {
@@ -488,12 +469,10 @@
  				'#type' => 'user_profile_category',
             	'#title' => t('Social Networks')   			      	
       		);
-
       		$account->content['gigya']['no_networks']['no_network'] = array (
       			'#type' => 'user_profile_item',        
       			'#value' => t('You are currently not connected to any social network. ') . l('Click here to connect to a social network', 'user/'. $account->uid .'/edit/gigya')
       		);      		
-      		
       	}
       }
       break;      
@@ -533,288 +512,35 @@
 	return $xxx;				
 }
 
-function gigya_drupal_user_authenticate_finalize(&$edit) {
-  global $user;  
-   
-  $user->login = time();
-  db_query("UPDATE {users} SET login = %d WHERE uid = %d", $user->login, $user->uid);
-  sess_regenerate();  
-}
 
-
-function gigya_drupal_user_authenticate($form_values) {
-  global $user;
-     
-  $account = user_load(array('name' => $form_values['name'], 'pass' => trim($form_values['pass']), 'status' => 1));
-  if ($account && drupal_is_denied('mail', $account->mail)) {
-    drupal_set_message( t('The name %name is registered using a reserved e-mail address and therefore could not be logged in.', array('%name' => $account->name)),'error');
-  }
-
-  // Name and pass keys are required.
-  // The user is about to be logged in, so make sure no error was previously
-  // encountered in the validation process.
-  if (!empty($form_values['name']) && !empty($form_values['pass']) && $account) {
-    $user = $account;
-    gigya_drupal_user_authenticate_finalize($form_values);
-    return $user;
+function gigya_link_accounts_submit(&$form, &$form_state) {
+	global $user;
+	if (!empty($user->uid) && $_gigya_user = GigyaUser::UserFromUrl()){
+    $_gigya_user->LinkAccounts($user->uid);
   }
+  return;
 }
 
 
-function gigya_link_accounts(&$form, &$form_state) {
-	global $_gigya_uid,$base_path,$base_url,$base_root;
-	
-	include_once 'modules/user/user.pages.inc';
-	//# base_path /drupal/
-	//# base_url http://assaf.com/drupal
-	//# base_root http://assaf.com	
-		
-	$failThePost = FALSE;	
-	$currPost =  $form_state['post'];
-	$moreQueryParams = '&drupal_user_name=' . $currPost['drupal_user_name'];
-	// 'check user and password '
-	$invalidUserName = user_validate_name($currPost['drupal_user_name']);
-	if ( $invalidUserName ) { 		
-		drupal_set_message($invalidUserName, 'error');
-		$failThePost =TRUE;		
-	}
-			   
-	if ( empty($currPost['drupal_user_pass']) ) { 
-		drupal_set_message('You must enter a password.', 'error');
-		$failThePost =TRUE;		
-	}
-	
-	if ( $failThePost ) {		
-		drupal_goto($base_root . $currPost['origAction'] . $moreQueryParams);
-	}
-	
-	//$moreQueryParams .= '&drupal_user_pass=' . $currPost['drupal_user_pass'];
-	
-	$form_values = array(
-		'name' => $currPost['drupal_user_name'], 
-		'pass' => $currPost['drupal_user_pass']
-    );
-	    
-    $currUser =  gigya_drupal_user_authenticate($form_values);
-              
-	if ( $currUser ) {				    	
-		// params are ok, so link 
-		$linkRes = gigya_linkAccountsRest($_gigya_uid,$currUser->uid);		
-		if  ( $linkRes ) {		
-			// from now on, work with the drupal user
-			$_gigya_uid = $currUser->uid;
-			$_SESSION['gigya_uid'] = $_gigya_uid;	
-			user_set_authmaps($currUser,array('auth_gigya'=> $currUser->uid));			
-			gigya_add_user_to_gigya_table($_gigya_uid,$currUser->uid,$form['currLoginProvider']);
-			$dest = variable_get('gigya_login_uiconfig_urlredirect', 'user');
-			drupal_goto($dest);					
-		}	
-		else {			
-			user_delete(array(),$currUser->uid);
-			$user = NULL;
-			drupal_set_message(t('Link accounts failed') ,'error');
-			drupal_goto($base_root . $currPost['origAction'] . $moreQueryParams);		
-		}							
-	}
-	else {				  
-    	form_set_error('name', t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => url('user/password'))));    	
-  	}
-		
-	drupal_goto($base_root . $currPost['origAction'] . $moreQueryParams);
-}
-
-function gigya_create_user_and_link_accounts(&$form, &$form_state) {	
-	global $base_path,$base_url,$base_root,$_gigya_uid	;
-	
-	include_once 'modules/user/user.pages.inc';
-		
-	$failThePost = FALSE;	
-
-	$currPost =  $form_state['post'];
-		
-	if (isset($currPost['external_required'])) {
-		$external_required_raw = $currPost['external_required'];
-		$external_requiredStr_raw = $currPost['external_requiredStr'];			
-		$external_required = explode(',',$external_required_raw);
-		$external_requiredStr = explode(',',$external_requiredStr_raw);
-		$count_external = count($external_required);		
-		if ( $count_external > 1 ) {
-			// there is a comma in the end of the string, so one array item is removed
-			$count_external--;
-			for ($i = 0; $i < $count_external; $i++) {
-				$currExternalRequired =$external_required[$i];
-				if ( !(isset($currPost[$currExternalRequired])) || ($currPost[$currExternalRequired]!=1 && $currPost[$currExternalRequired]!=TRUE)) {
-					$currExternalRequiredStr =$external_requiredStr[$i];
-					drupal_set_message($currExternalRequiredStr . ' field is required','error' );
-					$failThePost = TRUE;
-				}				
-			}
-		}
-		
-	}
-	
-	
-	$moreQueryParams = '&name=' . $currPost['name'];
-	// 'check user and password '
-	$invalidUserName = user_validate_name($currPost['name']);
-	if ( $invalidUserName ) { 
-		drupal_set_message($invalidUserName, 'error');
-		$failThePost= TRUE;
-	}
-	
-	$alreadyTakenName = gigya_username_exists_in_drupal($currPost['name']);
-	if ( $alreadyTakenName ) { 		
-		$failThePost= TRUE;
-	}
-	
-	$moreQueryParams .= '&mail=' . $currPost['mail'];
-	$invalidMail = user_validate_mail($currPost['mail']);
-	if ( $invalidMail ) { 
-		drupal_set_message($invalidMail, 'error');
-		$failThePost= TRUE;
-	} 
-	else {	
-		$alreadyTakenEmail = gigya_mail_exists_in_drupal($currPost['mail']);
-		if ( $alreadyTakenEmail ) { 		
-			$failThePost= TRUE;
-		}
-	}	
-	
-		 
-	if ( empty($currPost['pass']) ) { 
-		drupal_set_message('You must enter a password.', 'error');
-		$failThePost= TRUE;
-	}
-	
-	if ( empty($currPost['pass']['pass1']) ) { 
-		drupal_set_message('Password field is required.', 'error');
-		$failThePost= TRUE;
-	}
-
-	if ( empty($currPost['pass']['pass2']) ) { 
-		drupal_set_message('Confirm password field is required.', 'error');
-		$failThePost= TRUE;
-	}	
-	
-	$form_values = array(
-		'name' => $currPost['name'],
-		'mail' => $currPost['mail'], 
-		'pass' => $currPost['pass']['pass1'],		
-		'pass1' => $currPost['pass']['pass1'],		
-		'pass2' => $currPost['pass']['pass2'],	
-    );
-
-  
-	$pass1 = trim($form_values['pass1']);  	
-    $pass2 = trim($form_values['pass2']);
-    if (strcmp($pass1, $pass2)) {
-    	drupal_set_message(t('The specified passwords do not match.'), 'error');
-		$failThePost= TRUE;     	
-  	}
-  	
-  	if ($failThePost) {
-  		drupal_goto($base_root . $currPost['origAction'] . $moreQueryParams);
-  	}
-  	
-  	unset($form_values['pass1']);
-  	unset($form_values['pass2']);
-  	  	
-  	$form_values['status'] = 1;
-  	$form_values['init'] = $form_values['mail'];
-  	
-  	  	
-  	// create a new user  	
-  	$newUser = user_save('', $form_values);
-  	if ( $newUser ) {  		
-  		global $user;
-  		$user = $newUser;		  		  		  		 
-  		$linkRes = gigya_linkAccountsRest($_gigya_uid,$user->uid);		 		 	
-		if  ( $linkRes ) {
-			// from now on, work with the drupal user
-			$_gigya_uid = $user->uid;
-			$_SESSION['gigya_uid'] = $_gigya_uid;	
-			user_set_authmaps($user,array('auth_gigya'=> $user->uid));		
-			gigya_add_user_to_gigya_table($_gigya_uid,$user->uid,$form['currLoginProvider']);
-			gigya_save_user_profileValues($form,$currPost);
-			$dest = variable_get('gigya_login_uiconfig_urlredirect', 'user');
-			drupal_goto($dest);				
-  		}
-		else {			
-			user_delete(array(),$user->uid);
-			$user = NULL;
-			drupal_set_message(t('Link accounts failed') ,'error');
-			drupal_goto($base_root . $currPost['origAction'] . $moreQueryParams);				
-		}							
-  	}		  	
-  	
-	drupal_set_message(t('Cannot create a new user.'), 'error');
-  	drupal_goto($base_root . $currPost['origAction'] . $moreQueryParams);
-  	
-}
-
-function gigya_save_user_profileValues($form,$currPost) {
-	global $user;
-	
-	if (module_exists('profile')) {							
-		if ($profile_categories = profile_categories()) {			
-        	foreach ($profile_categories as $category) {
-          		$cat_name = $category['name'];          		
-          		$profiles = profile_form_profile(NULL, NULL, $category['name'], TRUE);          		
-          		if ($profiles && $profiles[$category['name']]) {          			
-          			if ( !empty($form[$cat_name]) && is_array($form[$cat_name])) {            	
-						profile_save_profile($currPost, $user, $cat_name,FALSE);              			
-          			}
-            	}
-          	}
-        }						     			      	
-    }
-}
-
 /**
  * Implementation of hook_form_alter().
  *
  * Alters user_register, user_login, and user_login_block forms
  */
 function gigya_form_alter(&$form, $form_state, $form_id) {
-  global $_gigya_uid, $base_url,$base_path;	
-  /** before we do any form alter, we should know what type of user we're dealing with, and if gigya is logged in yet.
-    * below these lines, we need to get the userInfo.
-    */
-    
+  global $gigya_user, $base_url;	
   
   $currPost =  $form_state['post']; 
- 	 
- 
-  if (  $currPost['form_id'] ==  'gigya_link_or_register_form') {  	 	  		  		  	  		  	
-  	$form['currLoginProvider'] = $form_state['post']['currLoginProvider'];
-    unset($form['#validate']);           
-    if ( $currPost['op'] == t('Link accounts')) {    		
-    	return gigya_link_accounts($form, $form_state);
-    }   
-    else {
-		// if $currPost['op'] == t('Create new account') 		
-    	return gigya_create_user_and_link_accounts($form, $form_state);	
-    }        
-                           		
-  }  
   
-  
-  if(arg(0) == 'socialize-logout') {  	
-    unset($form); 
-    return;
-  } 
-    
-  
-  // Replace the drupal authenticate function is it's used as validation.
-  if (isset($form['#validate']) && is_array($form['#validate']) && ($key = array_search('user_login_authenticate_validate', $form['#validate']))) {  	
-    $form['#validate'][$key] = 'gigya_login_validate';
-  }
-   
-  if ($form_id == 'user_profile_form') {	   
-    $gigya_profile = 0;
+  if ($form_id == 'user_profile_form') { 
+
     $account = user_load($form['#uid']);
-    if (user_get_authmaps($account->uid)) {
-      unset($form['account']['pass']);
+    $_gigya_user = new GigyaUser($account->uid);
+    $gigya_bio = $_gigya_user->GetUserInfo();
+    
+    //detect whether we should be showing the password field (loginprovider is not empty then we don't need a password)    
+    if (!empty($gigya_bio)) {
+      if(!empty($gigya_bio['loginProvider'])) unset($form['account']['pass']);
     }
 
     $form['gigya'] = array(
@@ -833,9 +559,11 @@
       );
       $gigya_profile++;
     //}
-    if ($gigya_profile == 0) {
-      unset($form['gigya']);
-    }
+  
+    /*
+     *todo: need to reevaluate how to deal with user pictures -- commenting this out for now 
+     */ 
+      /*
     if (variable_get('user_pictures', 0) && variable_get('gigya_user_picture',FALSE) && !$register && user_get_authmaps($account->uid) && gigya_avatar_check(arg(1))) {
       $form['picture']['gigya_user_picture'] = array (
         '#type' => 'checkbox',
@@ -843,182 +571,118 @@
         '#default_value' => $account->gigya_user_picture,
         '#description' => t('Checking this option will connect your social network picture to your site avatar'),
       );
-      $form['gigya_uid'] = array (
-       '#type' => 'value',
-       '#value' => $account->uid,
-      );
+      
       $form['#submit'][] = 'gigya_user_picture_submit';
     }
+    */
   }
   if ($form_id == 'user_register') {
-  	
     module_load_include('inc', 'gigya');
     module_load_include('.inc', 'user', 'user.pages');
     global $user;
-    $screentoggle_behavior_js = 'Drupal.behaviors.gigya_toggleScreens = Drupal.gigya.toggleScreens';
-    drupal_add_js($screentoggle_behavior_js, 'inline');
-    if (!isset($_gigya_uid)) { //we use this because the user isn't logged in yet, and thus has no session variable.
-      //if gigya is the only way to login, disable username and password block. NOTE admin can still login through /user
+   
+    //if they haven't logged into gigya simply add the gigya login block
+    if(!($_gigya_user = GigyaUser::UserFromUrl())){    
       gigya_login_block_js();
       $login_js = 'Drupal.behaviors.gigya_login = function(context){ Drupal.gigya.login(); }';
       drupal_add_js($login_js, 'inline');
-      $form['gigya'] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Social network login'),
-        '#weight' => -10,
-        '#collapsible' => FALSE,
-        '#collapsed' => FALSE,
-        '#description' => t('Use one of the following services? Login now before completing your user profile.')
-      );
       $item = array(
         'data' => '<div id="'. variable_get('gigya_login_uiconfig_containerID', GIGYA_DEFAULT_LOGINUI_CONTAINERID) .'"></div>',
       );
-      $form['gigya']['gigya_login'] = array(
+      $form['gigya_login'] = array(
         '#value' => theme('gigya_login_block', $item),
         '#weight' => -10,
       );
-      $form['links']['#weight'] = 2;
-            
-      $wrap_create_account  =array();      	      
-      foreach ($form as $currentKey=>$currentVal) {
-      	if ($currentKey != 'gigya') {      		      
-      		$wrap_create_account[$currentKey] = $form[$currentKey];      		
-      	}
-      	else {
-			$form[$currentKey]['#weight'] = -500;   
-      		$form[$currentKey]['#collapsible'] = TRUE;
-      		$form[$currentKey]['#collapsed']  = FALSE;			   		
-      	}
-      } 
-      
-     
-      $form['wrap_create_account'] = $wrap_create_account;
-      $form['wrap_create_account']['#type'] = 'fieldset';
-      $form['wrap_create_account']['#title'] = t('Register a new user');
- 	  $form['wrap_create_account']['#weight'] = -400;  
-      $form['wrap_create_account']['#collapsible'] = TRUE;
-      $form['wrap_create_account']['#collapsed']  = FALSE;
-
-      
-	  unset($form['account']);		           
-	  unset($form['submit']);		           
-      
-	  if (module_exists('profile')) {
-		  $profile_categories = profile_categories();      
-	      foreach ($profile_categories as $category) {
-	      	$cat_name = $category['name'];      	
-	        $profiles = profile_form_profile(NULL, NULL, $cat_name, TRUE);
-	        if ($profiles && $profiles[$category['name']]) {        	
-	        	unset($form[$cat_name]);		
-	        }
-	      }
-	  }   	  
-
-      foreach ($form as $currentKey=>$currentVal) {
-      	if ($currentKey != 'gigya' && $currentKey !='wrap_create_account') {  
-	      	if (is_array($form[$currentKey]) && $form[$currentKey]['#type']=='fieldset' ) {  	      			
-	      		unset($form[$currentKey]);	
-	      	}
-      	}
-      } 
+      $form['links']['#weight'] = 2;	  
+	  }
+    else{// if they HAVE logged into gigya then populate some of the data and hide the password field
+      $bio = $_gigya_user->GetUserInfo();
       
-      if ($user->uid == 1) {
-      	if ( arg(0) =='admin' ) { 
-      		unset($form['gigya']);
-      		if ( isset($form['wrap_create_account']) && isset($form['wrap_create_account']['#collapsible']) ) { 
-      			$form['wrap_create_account']['#collapsed'] = 0;
-      			$form['wrap_create_account']['#collapsible'] = 0;      				
-      		}
-      	}
+      //sometimes the account info is inside of an 'account' array, sometimes it's not.  Truthfully, I don't always know why it's one or the other -- seems to have to do with what fields are on the page
+    	if(is_array($form['account'])){
+      	$form_account = &$form['account'];
+      }
+      else{
+      	$form_account = &$form;
       }
       
-      return $form;
-    }
-    
-    $enable_fb_population = variable_get('gigya_enable_facebook_population',FALSE);    
-    
-    $bio = gigya_getUserInfo($_gigya_uid);
-    if (!$enable_fb_population && $bio && drupal_strtolower($bio['loginProvider']) == 'facebook') {
-      unset($bio);
-    }
-    if (!empty($bio['nickname'])) {
-      $msg = t('Hello %username, please complete your registration below.', array('%username' => $bio['nickname']));
-    }
-    else {
-      $msg = t('Please complete your registration below:');
-    }
-    //if the loginProvider has an email, populate that form item.
-    if (isset($bio['email'])) {
-      $form['account']['mail']['#default_value'] = $bio['email'];
-    }
-    //link gigya login provider profile information to the drupal proivder, if the profile module is enabled
-    $noCategories = TRUE;
-    
-    if ( module_exists('profile')  ) {      
-      if ($profile_categories = profile_categories()) {      	
-        foreach ($profile_categories as $category) {
-          $cat_name = $category['name'];
-          $profiles = profile_form_profile(NULL, NULL, $category['name'], TRUE);
-          if ($profiles && $profiles[$category['name']]) {
-            foreach($form[$cat_name] as $arr_name => $arr_val) {
-              if (is_array($arr_val)) {
-              	if ( $noCategories ) {
-					$form['requiredCategories'] = array();
-					$noCategories = FALSE;	
-				}							                
-				if (variable_get('gigya_profile_'. $arr_name, '') != '0') {
-					$bio_assoc = variable_get('gigya_profile_'. $arr_name, '');
-					if ($enable_fb_population || ($bio && drupal_strtolower($bio['loginProvider']) != 'facebook')) {  
-                  		$form['requiredCategories'][$cat_name][$arr_name]['#default_value'] = $bio[$bio_assoc];
-                  	}
-                  	else {
-                  		$form['requiredCategories'][$cat_name][$arr_name]['#default_value'] = '';
-                  	}                  	
-                }
-				else {
-					$form['requiredCategories'][$cat_name][$arr_name]['#default_value'] = '';
-				}									                                  	                               
-              }
+      //map the fields from the social network
+      if(gigya_populate_fields($bio['loginProvider'])) {
+  	    //first the email and nickname
+  	    //$form_account['name']['#default_value'] = (empty($bio['nickname']) ? '' : $bio['nickname']);
+  	    //$form_account['mail']['#default_value'] = (empty($bio['email']) ? '' : $bio['email']);
+  	    //now the extended profile fields
+  	    if ( module_exists('profile')  ) {      
+  	      if ($profile_categories = profile_categories()) {
+  	        foreach ($profile_categories as $category) {
+  	          $cat_name = $category['name'];
+  	          $profiles = profile_form_profile(NULL, NULL, $category['name'], TRUE);
+  	          if ($profiles && $profiles[$cat_name]) {
+  	            foreach($form[$cat_name] as $arr_name => $arr_val) {
+  			          if (is_array($arr_val)) {
+                    foreach (_gigya_get_profile_fields() as $field_key => $field_name) {
+                      if ($arr_name == variable_get('gigya_bio_'. $field_name, '')) {
+                        $form[$cat_name][$arr_name]['#default_value'] = $bio[$field_name];
+                      }
+  			            }	                                  	                               
+  			          }
+  	            }
+  	          }
+  	        }
+  	      }
+ 	      }
+ 	    }
+      // TODO remove this dd
+      // dd('------Loop------');
+      foreach (_gigya_get_profile_fields() as $field_key => $field_name) {
+        if (!isset($bio[$field_name]))
+          continue; // skip empty values from XML call
+        $var_name = 'gigya_bio_'. $field_name;
+        $mapped_field = variable_get($var_name, '');
+        /* TODO remove these drupal debug 
+        dd('----Field item----'); 
+        dd('----var_name:'); dd($var_name); 
+        dd('----mapped_field:'); dd ('"' . $mapped_field . '"');
+        dd('----value:'); dd ($bio[$field_name]);
+        dd('END Field item----'); 
+        */
+        if (strpos($mapped_field, 'field_') === 0) {
+          if ($var_name == 'gigya_bio_birthMonth' || $var_name == 'gigya_bio_birthDay' || $var_name == 'gigya_bio_birthYear') {
+            // date parts go to a birthdate CCK field
+            $form[$mapped_field][0]['#default_value'] = array('month' => $bio['birthMonth'], 'day' => $bio['birthMonth'], 'year' => $bio['birthYear']);
+          }
+          else {
+            if (strpos($var_name, 'gigya_bio_gender') === 0) {
+              // Gender CCK field, must have keys 'm' and 'f'. Labels can be whatever needed.
+              $form[$mapped_field]['#default_value'][0]['value'] = $bio[$field_name];
+            }
+            else {
+               // Regular text CCK field
+               $form[$mapped_field][0]['#default_value']['value'] = $bio[$field_name];
             }
           }
         }
+        elseif (strpos($mapped_field, 'username') === 0) {
+          // when nickname is mapped to username
+          $form['account']['name']['#default_value'] = $bio[$field_name];
+          // TODO remove this dd
+          // dd('username!'); dd($form['account']['name']);
+        }
+      }
+      // TODO remove this dd
+      // dd('------END Loop------');
+      // TODO remove this dd
+      dd('---Form!'); dd($form);
+      if (!variable_get('user_email_verification', TRUE)) {
+        $form_account['pass']['#type'] = 'hidden';
+        $form_account['pass']['#value'] = user_password();
+      }
+      if(module_exists('logintoboggan')) {
+       //
       }
     }
-        
-    $form['pass']= array('#type' => 'password',
-      '#title' => t('Password'),
-      '#size' => 20,
-      '#value' => '',
-      '#default_value' => '',    
-      '#required' => TRUE,
-    );
-    
-    $form['origPost'] = array();
-    if ( isset($_GET['name'])) {
-  		$form['origPost']['#name']= $_GET['name'];
-    }
-    if ( isset($_GET['mail'])) {
-  		$form['origPost']['#mail']= $_GET['mail'];
-    }
-    
-    if ( isset($_GET['drupal_user_name'])) {
-  		$form['origPost']['#drupal_user_name']= $_GET['drupal_user_name'];
-    }
-    
-    
- 
-    $form['mail']['#required'] = FALSE;
-    $form['loginProvider'] = array('#type' => 'value', '#value' => $bio['loginProvider']);
-    $form['gigya_uid'] = array('#type' => 'value', '#value' => $_gigya_uid);
-    unset($form['#submit']);
-    $form['#submit'][] = 'gigya_user_register_form_submit';   
-    
-    variable_set('remove_user_login_title',TRUE);
-    
-   
-    return gigya_link_accounts_or_register_form($form);       
+    return $form;
   }
-  
   if ($form_id == 'user_login') {    	
     module_load_include('inc', 'gigya');
     if (!isset($_gigya_uid)) {
@@ -1029,7 +693,7 @@
         drupal_add_js(array('gigya' => $drupal_logged_out), 'setting');
       }
       gigya_login_block_js();
-      $login_js = "Drupal.behaviors.gigya_login = function(context){  Drupal.gigya.login(); }";
+      $login_js = 'Drupal.behaviors.gigya_login = function(context){ Drupal.gigya.login(); }';
       drupal_add_js($login_js, 'inline');
       $item = array(
         'data' => '<div id="'. variable_get('gigya_login_uiconfig_containerID', GIGYA_DEFAULT_LOGINUI_CONTAINERID) .'"></div>',
@@ -1040,48 +704,12 @@
       );
       $form['links']['#weight'] = 2;
     }
-    else if (!variable_get('gigya_login_surpress_login', FALSE)) {
-      $bio = gigya_getUserInfo($_gigya_uid);
-      if (!empty($bio['nickname'])) {
-        $msg = t('Welcome back, %username. Login below to connect your social network to your site login', array('%username' => $bio['nickname']));
-      }
-      else {
-        $msg = t('Login below to connect your social network to your site login');
-      }
-      $form['existing_user'] = array(
-        '#type' => 'fieldset',
-        '#title' => t('Already a site user? Click here to login and connect your social network'),
-        '#weight' => 5,
-        '#collapsible' => TRUE,
-        '#collapsed' => TRUE,
-        '#description' => $msg,
-        '#attributes' => array('id' => 'user-login-description'),
-      );
-      drupal_add_js($login_greeting, 'inline');
-      $form['existing_user']['name'] = $form['name'];
-      $form['existing_user']['pass'] = $form['pass'];
-      $form['existing_user']['submit'] = $form['submit'];
-      unset($form['submit']);
-      unset($form['name']);
-      unset($form['pass']);
-      $form['loginProvider'] = array('#type' => 'value', '#value' => $bio['loginProvider']);
-      $form['gigya_uid'] = array('#type' => 'value', '#value' => $_gigya_uid);
-      $form['existing_user']['submit']['#value'] = t('Login and link accounts');
-      $form['#submit'][] = 'gigya_user_register_form_submit';
-    }
-    else {
-      unset($form['submit']);
-      unset($form['name']);
-      unset($form['pass']);
-      $form = array();
-    }
   }
-  
-  if ($form_id == 'user_login_block') {
-  	  	 	 
-    global $user, $_gigya_uid;     
-    module_load_include('inc', 'gigya');
 
+  if ($form_id == 'user_login_block') {  	  	 	 
+    global $user, $_gigya_uid;  
+
+    module_load_include('inc', 'gigya');
     if (variable_get('gigya_login_surpress_login', FALSE)) {
       unset($form['name']);
       unset($form['pass']);
@@ -1094,11 +722,11 @@
           'drupal_logged_out' => TRUE,
         );
         drupal_add_js(array('gigya' => $drupal_logged_out), 'setting');
-      }   
+      }
     }
     //if gigya is the only way to login, disable username and password block. NOTE admin can still login through /user
     gigya_login_block_js();
-    $login_js = "Drupal.behaviors.gigya_login = function(context){ Drupal.gigya.login(); }";
+    $login_js = 'Drupal.behaviors.gigya_login = function(context){ Drupal.gigya.login(); }';
     drupal_add_js($login_js, 'inline');
     $item = array(
       'data' => '<div style="margin-top: 10px; margin-left:auto; margin-right:auto;" id="'. variable_get('gigya_login_uiconfig_containerID', GIGYA_DEFAULT_LOGINUI_CONTAINERID) .'"></div>',
@@ -1110,9 +738,7 @@
     );
     $form['links']['#weight'] = 2;
     
-    
-   
-	if (isset($form['#action'])) {				
+	if (isset($form['#action'])) {
 		$currAction = $form['#action'];
 		if (strpos($currAction,'socialize-login') ) {
 			unset($form['links']);  
@@ -1126,19 +752,17 @@
     return;
   }
   
-  /** alter the updates status upon node edit/created **/    
+  /** alter the updates status upon node edit/created **/
   if (isset($form['#node']) && $form['#node']->type .'_node_form' == $form_id) {
     module_load_include('inc', 'gigya');
-    if ($capabilities = _gigya_getUserCapabilities($_SESSION['gigya_uid'])) {
-      if (!array_search('Status', $capabilities)) {
-        return;
-      }
-    }
+    if(empty($gigya_user)) return;
+    if (!$gigya_user->HasCapability('Status')) return;
+    
     // If we haven't enabled Gigya Socialize posting on this node type, nothing to do
     // here.
-    $type = $form['#node']->type;    
+    $type = $form['#node']->type;
     $allowed_types = variable_get('gigya_status_types', array('story' => 'story', 'blog' => 'blog'));
-    if (empty($allowed_types[$type])) {      
+    if (empty($allowed_types[$type])) {
       return;
     }
     $gigya_status_form = gigya_status_form();
@@ -1154,7 +778,7 @@
     );
     $form['gigya']['post'] = array(
       '#type' => 'checkbox',
-      '#title' => t('Announce this post to your social networks'),
+      '#title' => t('ANoahnnounce this post to your social networks'),
       '#default_value' => (empty($form['nid']['#value'])),
       '#id' => 'gigya-toggle',
     );
@@ -1163,36 +787,13 @@
     $form['gigya']['status']['#description'] = variable_get('gigya_status_description', 'The given text will be posted to your social networks. You can use !url, !url-alias, !tinyurl, !title and !user as replacement text.');
   }
 
-  if ($form_id == 'user_pass') {
-    $form['#validate'][] = 'gigya_socialize_user_validate';
-  }
   
-  // Warning msg on user edit.
-  if ($form_id == 'user_profile_form' && variable_get('user_pictures', 0)) {
-    $user = user_load(arg(1));
-    if ($user->gigya_user_picture) {
-      $form['picture']['gigya_user_picture'] = array(
-        '#value' => t('You are currently using your socialize picture, if you delete or load a new picture, your picture from socialize will no longer be updated.'),
-        '#weight' => 0,
-      );
-      $form['#submit'][] = 'gigya_user_edit_submit';          
-    }
-  }
   if ($form_id == 'gigya_admin_form') {  	   	  	  	   
-   	$currOp = $form_state['post']['op'];
-   	if ($currOp == t('Save configuration') ) {   		
-   		$_SESSION['validation_msg_not_required']=TRUE;   			
-   	}  		    	 
+   	$currOp = $form_state['post']['op'];  	  	   		
+    variable_get("need_validation_msg", FALSE);	  
     unset($form['buttons']['reset']);
   }
-}
 
-function gigya_socialize_user_validate($form, &$form_state) {
-	
-  $account = $form_state['values']['account'];
-  if (user_get_authmaps($account->uid)) {
-    form_set_error('user',t('This user logged in via a social network. Please login with your !loginprovider account',array('!loginprovider' => gigya_get_loginprovider($account->uid))));
-  }
 }
 
 /**
@@ -1211,40 +812,18 @@
 function gigya_user_picture_submit($form, &$form_state) {
   $account = user_load(arg(1));
   if($form_state['values']['gigya_user_picture'] && variable_get('user_pictures', 0)) {  
-    if ($picture = gigya_save_userpic($form_state['values']['gigya_uid'])) {
+    if ($picture = gigya_save_userpic($account->uid)) {
       $data['picture']   = $picture;
-      $data['gigya_user_picture'] = 1;
-      db_query('UPDATE {gigya} SET avatar_timestamp=%d WHERE uid=%d', time(),$form_state['values']['gigya_uid']);
-      
+      $data['gigya_user_picture'] = 1;      
       user_save($account, $data);   
     }
   }
 }
 
-/**
- * user validation function.
- *
- * If successful, sets the global $user object.
- */
-function gigya_login_validate($form, &$form_state) {  
-  module_load_include('inc', 'gigya');
-  
-  
-  if ($form_state['values']['form_id'] == 'user_login' || $form_state['values']['form_id'] == 'user_login_block') {  	 
-  	user_authenticate($form_state['values']);    
-  }
-  else {  	
-    gigya_authenticate($form_state['values']);    
-  }
-}
-
 function gigya_mail_alter(&$message) {
-
-  if ($message['id'] == 'user_register_no_approval_required') {
-    if (user_get_authmaps($message['params']['account']->uid != 0)) {
-      unset($message);
-    }
-  }
+/*
+ * todo: suppress emails in certain situations - should probably be configurable
+ */
 }
 
 function gigya_load_params() {
@@ -1302,14 +881,12 @@
     "context" => "context",
   ));
   drupal_add_js(array('gigya' => $gigya_params), 'setting');
-          
-  if (variable_get('gigya_login_advanced_raw', '')) {
-    $login_UIConfig = variable_get('gigya_login_advanced_raw', '');    
+  if (variable_get('gigya_login_uiconfig_raw', '')) {
+    $login_UIConfig = variable_get('gigya_login_uiconfig_raw', '');
   }
   else {
-    $login_UIConfig = "<config><body><captions background-color=\"". variable_get('gigya_login_uiconfig_color_caption_background', GIGYA_DEFAULT_LOGINUI_COLOR_CAPTION_BACKGROUND) ."\" color=\"". variable_get('gigya_login_uiconfig_color_caption_text', GIGYA_DEFAULT_LOGINUI_COLOR_CAPTION_TEXT) ."\"></captions><texts color=\"". variable_get('gigya_login_uiconfig_color_text', GIGYA_DEFAULT_LOGINUI_COLOR_TEXT) ."\"><links color=\"". variable_get('gigya_login_uiconfig_color_link', GIGYA_DEFAULT_LOGINUI_COLOR_LINK) ."\"></links></texts><controls><snbuttons buttonsize=\"". variable_get('gigya_login_uiconfig_iconsize', GIGYA_DEFAULT_ICONSIZE) ."\" color=\"". variable_get('gigya_login_uiconfig_color_button_text', GIGYA_DEFAULT_LOGINUI_COLOR_BUTTON_TEXT) ."\"></snbuttons><scrollingarrow color=\"". variable_get('gigya_login_uiconfig_color_navigation_arrow', GIGYA_DEFAULT_LOGINUI_COLOR_NAVIGATION_ARROW) ."\"></scrollingarrow></controls><background background-color=\"". variable_get('gigya_login_uiconfig_color_background', GIGYA_DEFAULT_LOGINUI_COLOR_BACKGROUND) ."\" frame-color=\"". variable_get('gigya_login_uiconfig_color_frame', GIGYA_DEFAULT_LOGINUI_COLOR_FRAME) ."\"></background></body></config>";    
+    $login_UIConfig = "<config><body><captions background-color=\"". variable_get('gigya_login_uiconfig_color_caption_background', GIGYA_DEFAULT_LOGINUI_COLOR_CAPTION_BACKGROUND) ."\" color=\"". variable_get('gigya_login_uiconfig_color_caption_text', GIGYA_DEFAULT_LOGINUI_COLOR_CAPTION_TEXT) ."\"></captions><texts color=\"". variable_get('gigya_login_uiconfig_color_text', GIGYA_DEFAULT_LOGINUI_COLOR_TEXT) ."\"><links color=\"". variable_get('gigya_login_uiconfig_color_link', GIGYA_DEFAULT_LOGINUI_COLOR_LINK) ."\"></links></texts><controls><snbuttons buttonsize=\"". variable_get('gigya_login_uiconfig_iconsize', GIGYA_DEFAULT_ICONSIZE) ."\" color=\"". variable_get('gigya_login_uiconfig_color_button_text', GIGYA_DEFAULT_LOGINUI_COLOR_BUTTON_TEXT) ."\"></snbuttons><scrollingarrow color=\"". variable_get('gigya_login_uiconfig_color_navigation_arrow', GIGYA_DEFAULT_LOGINUI_COLOR_NAVIGATION_ARROW) ."\"></scrollingarrow></controls><background background-color=\"". variable_get('gigya_login_uiconfig_color_background', GIGYA_DEFAULT_LOGINUI_COLOR_BACKGROUND) ."\" frame-color=\"". variable_get('gigya_login_uiconfig_color_frame', GIGYA_DEFAULT_LOGINUI_COLOR_FRAME) ."\"></background></body></config>";
   }
-  
   $gigya_login_params = array(
     'login_params' => array(
       "headerText" => variable_get('gigya_login_uiconfig_title', ''),
@@ -1323,33 +900,19 @@
       "UIConfig" => $login_UIConfig,
     ),
   );
-    
-  if(variable_get('gigya_login_advanced_custombuttons', '')) {  	
+  if(variable_get('gigya_login_advanced_custombuttons', ''))
     $gigya_login_params['login_params']["SNButtonsResourceURL"] = variable_get('gigya_login_advanced_custombuttons', '');
-  }
   
   drupal_add_js(array('gigya' => $gigya_login_params), 'setting');
 }
 
-function gigya_setNotifyLoginParams($userID,$useRedirect=TRUE) {
+function gigya_setNotifyLoginParams($userID) {
   global $base_path;
   module_load_include('inc', 'gigya');
   //setup the timestamp for validation through gigya_verify_signature
   date_default_timezone_set('GMT');
   $timestamp = date('Y-m-d H:i:s');
-       
-  
-  if ( $useRedirect == TRUE ) { 
-  	$destination = variable_get('gigya_login_uiconfig_urlredirect', 'user');	 
-  }
-     
   $signature = _gigya_verify_signature($timestamp, $userID, variable_get('gigya_SecretKey', FALSE));
-  $gigya_login_redirect = array(
-    'login_redirect' => array($destination),
-  );
-     
-  drupal_add_js(array('gigya' => $gigya_login_redirect), 'setting');
-  
   $gigya_notify_login = array(
     'notify_login_params' => array(
     "siteUID" => $userID,
@@ -1360,14 +923,7 @@
   
   drupal_add_js(array('gigya' => $gigya_notify_login), 'setting');  
   
-  if ( FALSE == _gigya_get_gid_by_uid($userID) ) {
-  	gigya_add_user_to_gigya_table($userID,$userID);
-  }
-  
-  if ( $useRedirect == TRUE ) { 
-  	return $destination;
-  }
-    
+  watchdog('gigya', 'gigya_notify_login');
 }
 
 /**
@@ -1381,27 +937,30 @@
  * @param string $userID this is the gigya username to be passed into notifyLogin
  */
 function gigya_notify_login($userID) {
-  $destination = gigya_setNotifyLoginParams($userID,TRUE);  
-  return $destination;
+  //gigya_setNotifyLoginParams($userID);
+  $behavior_js = 'Drupal.behaviors.gigya_notifyLogin = function(){ gigya.services.socialize.notifyLogin(Drupal.settings.gigya.conf, Drupal.settings.gigya.notify_login_params);};';
+  drupal_add_js($behavior_js, 'inline');  
 }
 function gigya_link($type, $node = NULL, $teaser = FALSE) {
   module_load_include('inc', 'gigya');
-  global $user;
+  global $user,$gigya_user;
   $links = array();
-  if ($capabilities = _gigya_getUserCapabilities($_SESSION['gigya_uid'])) {
-    if (array_search('Notifications', $capabilities) && array_search('Friends', $capabilities)) {
-      $allowed_types = variable_get('gigya_share_types', array('story' => 'story', 'blog' => 'blog'));
-      if ($type == 'node' && !empty($allowed_types[$node->type])) {
-        $links['socialize_notify_friends'] = array(
-          'title' => variable_get('gigya_share_link_title', GIGYA_DEFAULT_SHARE_LINK_TITLE),
-          'href' => "gigya/notifyfriends/$node->nid",
-          'attributes' => array('title' => t('Tell your friends about !nodetitle.', array('!nodetitle' => $node->title)), 'class' => 'popups-form'),
-        );
-      }
+  if(empty($gigya_user)) return $links;
+  
+  if ($gigya_user->HasCapability('Notifications') && $gigya_user->HasCapability('Friends')) {
+    $allowed_types = variable_get('gigya_share_types', array('story' => 'story', 'blog' => 'blog'));
+    if ($type == 'node' && !empty($allowed_types[$node->type])) {
+      $links['socialize_notify_friends'] = array(
+        'title' => variable_get('gigya_share_link_title', GIGYA_DEFAULT_SHARE_LINK_TITLE),
+        'href' => "gigya/notifyfriends/$node->nid",
+        'attributes' => array('title' => t('Tell your friends about !nodetitle.', array('!nodetitle' => $node->title)), 'class' => 'popups-form'),
+      );
     }
   }
   return $links;
 }
+
+
 /**
  * Implementation of hook_theme().
  */
@@ -1426,6 +985,12 @@
     'gigya_notify_friends' => array(
       'arguments' => array('title', 'subj', 'msg'),
     ),
+    'gigya_link_accounts' => array(
+      'arguments' => array('form' => NULL),
+    ),
+    'gigya_register' => array(
+      'arguments' => array('bio','registration_form','link_accounts_form')
+    )
   );
 }
 function theme_gigya_friends($friends) {
@@ -1433,22 +998,14 @@
   $content = '<div id="gigya_friends">';
   $content .= '<table id="gigya_friends_table" style="border:0" cellpadding="0" cellspacing="0">';
   $content .= '<tr class="gigya table">';
-  $site_friends = array();
-  $friend_count = 0;
-  foreach ($friends as $friend) {  	
-    $friend_bio = $friend['identities']->identity;
-    //drupal_set_message('friend: '  . $friend_bio->UID) ;
-    if (_gigya_get_uid_by_gid($friend_bio->UID)) {      
-      $site_friends[] = $friend_bio;
-      $friend_count++;      
-    }
-  }
+  $friend_count = count($friends);
+  
   $rows = $friend_count / 5;
   $tail = $friend_count % 5;
-  
   $rowcount = 1;
   $colcount = 0;
-  foreach ($site_friends as $site_friend) {
+  foreach ($friends as $friend) {
+    $site_friend = $friend['identities']->identity;
     $colcount++;
     if (isset($site_friend->thumbnailURL))
       $friend_photo = $site_friend->thumbnailURL;
@@ -1456,7 +1013,7 @@
       $friend_photo = $site_friend->photoURL;
     else                       
       $friend_photo = $base_url .'/'. drupal_get_path('module', 'gigya') .'/silhouette.gif';
-    $friend_link =  l($site_friend->nickname, 'user/'. _gigya_get_uid_by_gid($site_friend->UID));
+    $friend_link =  l($site_friend->nickname, 'user/'. $site_friend->UID);
     $content .= '<td width="20%" class="friend_bio"><img width="50" height="50" src="'. $friend_photo .'" /><br /><span class="friend_nickname">'. $friend_link .'</span></td>';
     if (($colcount * $rowcount) == $friend_count) {
       $remainer = 5 - $colcount;
@@ -1560,7 +1117,7 @@
 
 
 /**
- * Theme funciton for gigya_notify_friends
+ * Theme function for gigya_notify_friends
  */
 function theme_gigya_notify_friends($title, $subj = '', $msg = '') {
   //disable providers who don't have friends abilities
@@ -1602,38 +1159,171 @@
 }
 
 
-function gigya_enter_user($drupalUserID,$origAction) {	
-	global $base_url;	
-		
-	$currUser = user_load($drupalUserID);
-	if ( $currUser ) { 
-		$values = array(
-			'name' => $currUser->name , 
-			'pass' => $currUser->pass,	
-			'mail' => $currUser->mail,
-		);
-										
-		// Valid login.
-  		global $user;
-  		$user = $currUser;
-  		user_authenticate_finalize($values);
-  		$dest = variable_get('gigya_login_uiconfig_urlredirect', 'user');
-  		drupal_goto($dest);				       	
-	}		
-	else {
-		drupal_set_message('Failed loading user id ' . $drupalUserID , 'error');
-	}
-		 
-	drupal_goto($base_root);
-
-}
 
 function gigya_footer($main=0) {
 	module_load_include('inc', 'gigya', 'gigya.admin');
 	return '<!-- ' . GIGYA_MODULE_VERSION . ' -->';
-}	
+}
 
 
+function gigya_link_accounts(){
+  $form = array(
+  	'#theme' => 'gigya_link_accounts'
+  );
+    
+  $form['link_accounts']['name'] = array('#type' => 'textfield',
+    '#title' => t('Username'),
+    '#size' => 60,
+    '#maxlength' => USERNAME_MAX_LENGTH,
+    '#required' => TRUE,
+  );
+
+  $form['link_accounts']['name']['#description'] = t('Enter your @s username.', array('@s' => variable_get('site_name', 'Drupal')));
+  $form['link_accounts']['pass'] = array('#type' => 'password',
+    '#title' => t('Password'),
+    '#description' => t('Enter the password that accompanies your username.'),
+    '#required' => TRUE,
+  );
+  $form['#validate'] = user_login_default_validators();
+  $form['submit'] = array('#type' => 'submit', '#value' => t('Log in'), '#weight' => 2);
+
+  return $form;
+}
 
+function gigya_populate_fields($loginProvider){
+	return (strtolower($loginProvider) != 'facebook' || variable_get('gigya_enable_facebook_population',FALSE));
+}
 
+function theme_gigya_link_accounts($form){
+	$output = '<h3>Or log in to link your existing account to this social network</h3>';
+	$output .= drupal_render($form);
+	return $output;
+}
+
+function theme_gigya_register($bio, $registration_form, $link_accounts_form){
+	//the bio variable is a gigya User object as documented here: http://wiki.gigya.com/030_Gigya_Socialize_API_2.0/030_API_reference/Objects/User_object
+	$output = '<h2>Complete your registration</h2>
+	<p>You have been authenticated via '. $bio['loginProvider'] .'.  Please complete your registration below.</p>';
+	$output .= $registration_form . $link_accounts_form;
+	return $output;
+}
+
+class GigyaUser{
+  public $uid;
+  private $userinfo;
+  
+  public function __construct($gigya_uid){
+    $this->uid = $gigya_uid;  
+  }
+  
+  public static function GetCurrentGigyaUser(){
+    if(!empty($_SESSION['gigya_uid'])) return new GigyaUser($_SESSION['gigya_uid']);
+    return false;
+  }
+  
+  public function GetUserInfo($refresh = false){
+    if(!empty($this->userinfo) && !$refresh) return $this->userinfo;
+    return gigya_getUserInfo($this->uid);  
+  }
+  
+  public function PublishUserAction($content){
+    if(!$this->HasCapability('Actions')) return false;
+    return gigya_publish_user_action($this->uid,$content);
+  }
+  
+  public static function SaveToSession($gigya_id){
+    global $gigya_user;
+    $_SESSION['gigya_uid'] = $gigya_id;
+    return $gigya_user = new GigyaUser($gigya_id);
+  }
+  
+  public static function Login($gigya_id){
+    global $gigya_user;
+    GigyaUser::SaveToSession($gigya_id);
+  }
+    
+  public function Logout(){
+    global $gigya_user;
+    unset($gigya_user);
+    //drupal_goto('socialize-logout');
+  }
+  
+  public function GetFriends(){
+    return gigya_getFriendsInfo($this->uid);
+  }
+  
+  public function GetCapabilities() {
+    if ($bio = $this->GetUserInfo()) {
+      $capabilities = split(', ', $bio['capabilities']);
+      array_walk($capabilities, '_gigya_trim_value');
+      return $capabilities;
+    }
+    else {
+      return FALSE;
+    }
+  }
+  
+  public function HasCapability($capability){
+    $capabilities = $this->GetCapabilities();
+    return array_search('Actions', $capabilities);
+  }
+  
+  public function MapExtendedProfileFields($edit){
+    //map whatever extended profile fields we can that weren't on the registration form
+    $bio = $this->GetUserInfo();
+    if(gigya_populate_fields($bio['loginProvider']) && variable_get(GIGYA_POPULATE_NON_REG_PROFILE_FIELDS,FALSE)){
+      if ( module_exists('profile')  ) {
+        $temp_edit = array();
+        if ($profile_categories = profile_categories()) {
+                
+          foreach ($profile_categories as $category) {
+            $result = _profile_get_fields($category['name']);
+            while ($field = db_fetch_object($result)) {
+              //only attempt to set this variable if we've mapped it and it isn't already set elsewhere
+              if (variable_get('gigya_profile_'. $field->name, '') != '0' && !isset($edit[$field->name])) {
+                $bio_assoc = variable_get('gigya_profile_'. $field->name, '');
+                $temp_edit[$field->name] = $bio[$bio_assoc];
+              }
+            }
+            //this could potentially cause conflicts with other modules not expecting that this will be called; disable mapping of extended profile fields if this causes a problem -- could probably replace with profile_save_profile but haven't fully investigated
+            user_save($account,$temp_edit,$category['name']);
+          }
+        }       
+      }
+    }
+  }
+  
+  public function LinkAccounts($uid){
+    return gigya_linkAccountsRest($this->uid,$uid);
+  }
+  
+  public function SetStatus($status){
+    return gigya_setStatus($this->uid,$status);
+  }
+  
+  public function Unlink(){
+    gigya_unlinkAccounts($this->uid,$this->uid);
+    return true;
+  }
+  
+  public static function UserFromUrl(){
+    if (!empty($_GET['signature']) && !empty($_GET['timestamp']) && !empty($_GET['UID'])) {
+      //first, verify signature
+      $localkey = _gigya_verify_signature($_GET['timestamp'], $_GET['UID'], variable_get('gigya_SecretKey', FALSE));
+      if ($localkey != $_GET['signature']) {
+        drupal_set_message(t('Unable to authenticate. Gigya signature does not match.'), 'error');
+          if ($user->uid == 1) {
+            drupal_set_message(t('Signature is %gigya, Site sig is %site.', array('%gigya' => $form_values['signature'], '%site' => $localkey)), 'error');
+          }
+         return false;
+      }
+      else{
+        return new GigyaUser($_GET['UID']);
+      }  
+    }
+    else{
+      return false;
+    }           
+  }
+}
 
Index: gigya.inc
===================================================================
RCS file: /cvs/drupal/contributions/modules/gigya/Attic/gigya.inc,v
retrieving revision 1.1.2.21
diff -u -r1.1.2.21 gigya.inc
--- gigya.inc	24 Dec 2009 12:15:24 -0000	1.1.2.21
+++ gigya.inc	27 Jan 2010 06:12:28 -0000
@@ -1,5 +1,5 @@
 <?php
-// $Id: gigya.inc,v 1.1.2.21 2009/12/24 12:15:24 gigya Exp $
+// $Id: gigya.inc,v 1.1.2.20 2009/12/03 20:55:15 gigya Exp $
 
 /**
  * @file
@@ -11,111 +11,15 @@
  * @package gigya
  */
 
-/**
- * Main user authentication function.
- *
- * If successful, sets the global $user object.
- */
-function gigya_authenticate($form_values, $gigya_loggedin = FALSE) {
-  
-  global $base_path, $user, $_gigya_uid;
-    
-  include_once 'modules/user/user.pages.inc';
-  $dest = variable_get('gigya_login_uiconfig_urlredirect', 'user');
-  //we've logged in with a user through the normal login block. We need to check to see if they're a gigya user as well
-  if (!$gigya_loggedin) {
-    if (user_authenticate($form_values)) {     	
-		drupal_goto($dest);		
-      	//return "I'm logged in";
-    }
-  }
-  $localkey = _gigya_verify_signature($form_values['timestamp'], $form_values['gigya_uid'], variable_get('gigya_SecretKey', FALSE));
-     		 
-  //first, verify signature
-  if ($localkey != $form_values['signature']) {
-    //print $localkey ."    and     ". $form_values['signature'];
-    drupal_set_message(t('Unable to authenticate. Gigya signature does not match.'), 'error');
-      if ($user->uid == 1) {
-        drupal_set_message(t('Signature is %gigya, Site sig is %site.', array('%gigya' => $form_values['signature'], '%site' => $localkey)), 'error');
-      }
-      
-     return 'Unable to authenticate. Gigya signature does not match.';
-  }
-
-  //check to see if the gigya_user is linked to a drupal user
-  if ($drupal_uid = _gigya_get_uid_by_gid($form_values['gigya_uid'])) { 
-
-    $user = user_load($drupal_uid);    
-    $userLoggedStr='gigya_' . $drupal_uid . '_logged';     	
-  	$_SESSION[$userLoggedStr] = TRUE;           
-    $_gigya_uid = $form_values['gigya_uid'];
-    user_authenticate_finalize($form_values);
-    $_SESSION['gigya_uid'] = $form_values['gigya_uid'];      
-    drupal_goto($dest);
-  }
-  else { //otherwise, lets give them a registration page
-    $output .= drupal_get_form('user_register');
-    return $output;
-  }
-}
-
-/**
- * Storage function to link the gigya GID+Provider to a drupal username
- *
- * @param array &$edit contains the uid, gigya_uid, and a provider to be stored
- */
-function gigya_save_profile($edit) {
-  if (!$edit['uid'] || $edit['gigya_uid'] == '') {
-    return;
-  }
-  //print_r("Socialize ID:" . $_SESSION['gigya_uid']);
-  if (!isset($edit['loginProvider'])) {
-    $bio = gigya_getUserInfo($_SESSION['gigya_uid']);
-    //print_r($bio);
-    $edit['loginProvider'] = $bio['loginProvider']; 
-  }
-  if($edit['loginProvider'] && $edit['uid'] && $edit['gigya_uid']) {
-    db_query("UPDATE {gigya} SET uid = %d, gigya_uid = '%s', loginProvider = '%s' WHERE uid = %d", $edit['uid'], $edit['gigya_uid'], $edit['loginProvider'], $edit['uid']);
-    if (!db_affected_rows()) {
-      db_query("INSERT INTO {gigya} (uid, gigya_uid, loginProvider) VALUES (%d, '%s', '%s')", $edit['uid'], $edit['gigya_uid'], $edit['loginProvider']);
-    }
-    return TRUE;
-  } else {
-    drupal_set_message("Error saving your socialize profile info. Please contact the system administrator",'error');
-    return FALSE;
-  }
-}
-
 function gigya_delete_profile($uid) {
-  if($gid = _gigya_get_gid_by_uid($uid)){
-	db_query("DELETE FROM {gigya} WHERE uid = %d", $uid);
-  	gigya_unlinkAccounts($gid,$uid);
-	}
-	else{
- 		gigya_unlinkAccounts($uid,$uid);
-	}
-   return TRUE;
+  gigya_unlinkAccounts($uid,$uid);
+  return TRUE;
 }
 
-
-
-
 function gigya_get_loginprovider($uid) {
-	  	
-  if($login_provider = db_result(db_query("SELECT loginProvider FROM {gigya} WHERE uid = %d",$uid)))
-    return $login_provider;
   return false;
 }
 
-function gigya_avatar_status($uid) {
-  $res = db_result("SELECT use_avatar, avatar_timestamp FROM {gigya} WHERE uid=%d",$uid);
-  while($data = db_fetch_array($res)) {
-    if(!$data['use_avatar']) {
-      return FALSE;
-    } 
-    return $data;
-  }
-}
 
 function gigya_avatar_check($uid) {
   $bio = gigya_getUserInfo($uid);
@@ -178,15 +82,16 @@
   return $services;
 }
 
-function gigya_status_form($account = NULL) {	
+function gigya_status_form($account = NULL) {
+  global $gigya_user;
   drupal_add_js(drupal_get_path('module', 'gigya') .'/gigya_updatestatus.js', 'module');
-   
+ 
   if (empty($account)) {
     global $user;
     $account = $user;
   }
 
-  if ($capabilities = _gigya_getUserCapabilities($_SESSION['gigya_uid'])) {  	
+  if ($capabilities = $gigya_user->GetCapabilities()) {
     if (array_search('Status', $capabilities)) {
       $form = array();
       $form['status'] = array(
@@ -203,16 +108,16 @@
   $services = array(
     'facebook' => 'Facebook',
     'myspace' => 'MySpace',
-    'twitter' => 'Twitter',  
+    'twitter' => 'Twitter',
     'google' => 'Google',
     'yahoo' => 'Yahoo',
     'aol' => 'AOL',  
-    'blogger' => 'Blogger',
+    'blogger' => 'blogger',
     'wordpress' => 'WordPress',
-    'typepad' => 'Typepad',
-    'liveJournal' => 'LiveJournal', 
-    'hyves' =>  'Hyves' ,
-    'veriSign' =>'VeriSign'
+    'typepad' => 'typepad',
+    'liveJournal' => 'liveJournal', 
+    'hyves' =>  'hyves' ,
+    'veriSign' =>'veriSign'
   
   );
   return $services;
@@ -246,20 +151,6 @@
   );
 }
 
-/**
- * Internal gigya function to get the Gigya User id when the drupal uid is known
- * @param integer $uid The drupal user id
- * @return integer gigya user id if it exists in the link table
- */
-function _gigya_get_gid_by_uid($uid) {
-	
-  if ($gid = db_result(db_query("SELECT gigya_uid FROM {gigya} WHERE uid = %d", $uid))) {
-    return $gid;
-  }
-  else {
-    return FALSE;
-  }
-}
 
 function _gigya_getUserCapabilities($uid) {
 		
@@ -276,50 +167,7 @@
   }
 }
 
-/**
- * Internal gigya function to get the Gigya User id when the drupal uid is known
- * @param integer $uid The drupal user id
- * @return integer gigya user id if it exists in the link table
- */
-function _gigya_get_linked_networks($uid) {
-			
-  $network = array();
-  //TODO: REST API call here
-  $res = db_query("SELECT gigya_uid,loginProvider FROM {gigya} WHERE uid = %d", $uid);
-  while ($gid = db_fetch_array($res)) {
-    $network[$gid['loginProvider']] = $gid['gigya_uid'];
-  }
-  return $network;
-}
-
-/**
- * Internal gigya function to get the drupal user id when the gigya uid is known
- * @param integer $uid The gigya user id
- * @return integer drupal user id if it exists in the link table
- */
-function _gigya_get_uid_by_gid($gid) {
-	
-  if ($uid = db_result(db_query("SELECT uid FROM {gigya} WHERE gigya_uid = '%s'", $gid))) {
-    return $uid;
-  }
-  else {
-    return FALSE;
-  }
-}
 
-/**
- * Internal gigya function to get the drupal user id when the gigya uid is known
- * @param integer $uid The gigya user id
- * @return integer drupal user id if it exists in the link table
- */
-function _gigya_network_lookup($gid) {  
-  if ($provider = db_result(db_query("SELECT loginProvider FROM {gigya} WHERE gigya_uid = '%s'", $gid))) {
-    return $provider;
-  }
-  else {
-    return FALSE;
-  }
-}
 
 function _gigya_trim_value(&$value) {
     $value = trim($value);
@@ -335,6 +183,18 @@
  * @param string $uid The gigya GID being passed to/from gigya
  * @param string $privatekey The private key set in the admin settings. Fetch the key from the gigya socialize site
  */
+
+function gigya_verify_signature($timestamp,$uid,$signature){
+	$secret = variable_get('gigya_SecretKey', FALSE);
+	$localkey = _gigya_verify_signature($timestamp, $uid, $secret);
+	if($localkey == $signature){
+		return $uid;
+	}
+	else{
+		return false;
+	}
+}
+
 function _gigya_verify_signature($timestamp, $uid, $privatekey) {
 
   $ch1data = $timestamp .'_'. $uid;
@@ -393,7 +253,9 @@
  * If it shows the user logged out, thats good, if it returns an error then our keys are most likely bad
  */ 
 function gigya_validate($update = FALSE) {
-  	  	
+  	
+  $origValidateState = variable_get("gigya_validate", FALSE);	
+	
   $gigya_params = gigya_load_params();
   $gigya_params['uid'] = 'admin';
   $signature = _gigya_calc_signature(variable_get('gigya_SecretKey', FALSE), 'GET', 'getUserInfo', $gigya_params);
@@ -418,18 +280,16 @@
     return FALSE;
   }
   
-    
-  if ($_SESSION['validation_msg_not_required']) {
-  	unset($_SESSION['validation_msg_not_required']);
-  	return TRUE;	
-  }
   
-  if(!$update) {    	  		  	
-  	drupal_set_message("Gigya validated properly. This site is authorized to use Gigya services");
-    variable_set("gigya_validate", TRUE);     	
+  
+  if ( !$origValidateState || variable_get("need_validation_msg", FALSE)) {  	   
+  	drupal_set_message($eee . " Gigya validated properly. This site is authorized to use Gigya services");
+  	variable_set("need_validation_msg", TRUE);  	  
   }
-        
-  return TRUE; 
+  
+  variable_set($eee . "gigya_validate", TRUE);
+    
+  return TRUE;
 }
   
 /**
@@ -440,19 +300,14 @@
  * Fetch information about users following a given socialize account.
  */
 function gigya_getUserInfo($gigya_uid) {			    
-  global $user;
-	
+
   if (empty($gigya_uid)) {
     return FALSE;
   }
-    
+  
   $gigya_params = gigya_load_params();
-  if ( $user && ($user->uid)>0 ) {   	
-  	$gigya_params['uid'] = $gigya_uid;
-  }
-  else {   	 	  
-	return FALSE;
-  }
+  $gigya_params['uid'] = $gigya_uid;  	
+
   
   $signature = _gigya_calc_signature(variable_get('gigya_SecretKey', FALSE), 'GET', 'getUserInfo', $gigya_params);
   $url = "http://". variable_get('gigya_api_url', 'socialize.api.gigya.com') ."/socialize.getUserInfo".
@@ -467,28 +322,21 @@
   $results = drupal_http_request($url, $headers, 'GET');
   
 
-  //print_r($results);
-  if (_gigya_request_failure($results)) {  		  	  	     	  	  	    
+  if (_gigya_request_failure($results)) {
+  	watchdog('gigya', 'gigya_getUserInfo failure'); 
     return FALSE;
   }
   return _gigya_convert_xml_to_array($results->data);
 }
 
 function gigya_getFriendsInfo($gigya_uid) {
-  global $user;
 	
   if (!$gigya_uid) {
     return FALSE;
   }
 
   $gigya_params = gigya_load_params();
-    
-  if ( $user && ($user->uid)>0 ) {  	
-  	$gigya_params['uid'] = $gigya_uid;
-  }
-  else {  	
-	return FALSE; 	
-  }  
+	$gigya_params['uid'] = $gigya_uid;  	
   
   
   $signature = _gigya_calc_signature(variable_get('gigya_SecretKey', FALSE), 'GET', 'getFriendsInfo', $gigya_params);
@@ -500,6 +348,7 @@
             "&uid=". urlencode($gigya_params['uid']);
   $headers = array('Content-type' => 'application/x-www-form-urlencoded');
   $results = drupal_http_request($url, $headers, 'GET');
+  
   if (_gigya_request_failure($results)) {
     return FALSE;
   }
@@ -558,8 +407,7 @@
  * Create a linkage in Gigya Socialize between the current Drupal user and gigya user (Drupal uid<->Gigya uid)
  */
 function gigya_linkAccountsRest($gigya_uid,$drupalUid) {
-			
-  if (empty($gigya_uid))
+  if (empty($gigya_uid) || empty($drupalUid))
     return FALSE;
 
   $gigya_params = gigya_load_params();
@@ -579,11 +427,6 @@
   if (_gigya_request_failure($results)) {  	
     return FALSE;
   }
-
-   /* The following is added so that notifyLogin will NOT be activated */ 
-  $userLoggedStr='gigya_' . $drupalUid . '_logged';    
-  $_SESSION[$userLoggedStr] = TRUE;
-  
   return _gigya_convert_xml_to_array($results->data);
 }
 
@@ -704,8 +547,8 @@
         return TRUE;
     case 500:
       // 500 Internal Server Error: we did something wrong.  Please post to the group about it and the Gigya team will investigate.
-      watchdog('gigya', $errorcode . ' Internal Server Error. ' . $errormsg);   	  
-  	  if ( !(stripos($errormsg,'Pending'))) {
+      watchdog('gigya', $errorcode . ' Internal Server Error. ' . $errormsg);  	  
+  	  if ( !(strpos($errormsg,'Data Pending'))) {
       	drupal_set_message('Gigya Socialize Error: code(' . $errorcode . ') Internal Server Error. ' . $errormsg,'error');
       }
        
@@ -742,67 +585,6 @@
   return get_object_vars($xml);
 }
 
-/**
- * Checks if the user exists in users table
- * @param $currUserID
- * @return TRUE if the user exists
- */
-function gigya_user_exists_in_drupal($currGigyaUID) {		
-	if ( is_numeric($currGigyaUID)) {				
-		$currentDrupalUID = db_result(db_query("SELECT uid FROM {users} WHERE uid = '%s'", $currGigyaUID));						
-  		if ( $currentDrupalUID  ) {  			  		 	  		 
-  		 	drupal_set_message('user ' . $currentDrupalUID . ' is in Drupal');
-  		 	return TRUE; 	
-  		}
-	}  	
-		
-  	return FALSE;
-}
-
-/**
- * Checks if the user exists in gigya table
- * @param $currUserID
- * @return TRUE if the user exists in in gigya table
- */
-function gigya_user_exists_in_gigya_table($currGigyaUID) {			
-	$currentDrupalUID = db_result(db_query("SELECT uid FROM {gigya} WHERE gigya_uid = '%s'", $currGigyaUID));		
-  	if ( $currentDrupalUID ) {
-  		drupal_set_message('user :' . $currGigyaUID .' is in gigya table, drupal uid=' . $currentDrupalUID);
-  		return TRUE; 	
-  	}
-	drupal_set_message($currGigyaUID . ' does not exist in gigya table');	  	
-  	return FALSE;
-}
-
-/**
- * Adds the user to gigya table
- * @param $currGigyaUID
- * @param $currentDrupalUID
- * 
- */
-function gigya_add_user_to_gigya_table($currGigyaUID,$currentDrupalUID,$loginProvider=' ') {	
-	db_query("UPDATE {gigya} SET uid = %d, gigya_uid = '%s', loginProvider='%s' WHERE gigya_uid = '%s'",$currentDrupalUID,'' . $currentDrupalUID, $loginProvider,$currGigyaUID);
-    if (!db_affected_rows()) {
-      db_query("INSERT INTO {gigya} (uid, gigya_uid, loginProvider) VALUES (%d, '%s', '%s')", $currentDrupalUID, $currentDrupalUID, $loginProvider);
-    }
-}	
-
-
-function gigya_username_exists_in_drupal($userName) {
-	if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE LOWER(name) = LOWER('%s')", $userName)) > 0) {
-		drupal_set_message(t('The name %name is already taken.', array('%name' =>$userName)), 'error');
-		return TRUE;
-    }
-	return FALSE; 
-}
-
-function gigya_mail_exists_in_drupal($mail) {	
-	if (db_result(db_query("SELECT COUNT(*) FROM {users} WHERE LOWER(mail) = LOWER('%s')", $mail)) > 0) {
-		drupal_set_message(t('The e-mail address %email is already registered.', array('%email' =>$mail)), 'error');
-		return TRUE;
-    }
-	return FALSE; 
-}
 
 
 
Index: gigya.js
===================================================================
RCS file: /cvs/drupal/contributions/modules/gigya/Attic/gigya.js,v
retrieving revision 1.1.2.8
diff -u -r1.1.2.8 gigya.js
--- gigya.js	24 Dec 2009 12:15:24 -0000	1.1.2.8
+++ gigya.js	27 Jan 2010 06:12:28 -0000
@@ -151,7 +151,7 @@
  * In production, this function may not be needed. Sends an alert if the user logged in.
  */
 Drupal.gigya.notifyLogin_callback = function(response) {	
-  if ( response['status'] == 'OK' ) {	  	  
+  if ( response['status'] == 'OK' ) {
     window.location = Drupal.settings.gigya.login_redirect;
   } 
   else {
@@ -278,11 +278,18 @@
   //popupElement.setAttribute('destination','index.php');
   popupElement.setAttribute('class','popups-form popups-processed');
   popupElement.textContent="setStatus";
-  parent.path='http://assaf.com/drupal';  
+  parent.path=url;  
   Popups.openPath(popupElement,Popups.options,parent);  
-  ///Popups.message('Titles','here we go!');
+  //Popups.message('Titles','here we go!');
 };
 
 Drupal.gigya.SetStatusPopup_onClose = function(response) {	
+	//alert('dfgdfgdf');
   Popups.close();
 };
+
+Drupal.gigya.init_response = function(response){
+	if(response['user']['UID'] != Drupal.settings.gigya.notify_login_params.siteUID){
+		gigya.services.socialize.notifyLogin(Drupal.settings.gigya.conf, Drupal.settings.gigya.notify_login_params);
+	}
+}
Index: gigya.install
===================================================================
RCS file: /cvs/drupal/contributions/modules/gigya/Attic/gigya.install,v
retrieving revision 1.1.2.17
diff -u -r1.1.2.17 gigya.install
--- gigya.install	24 Dec 2009 12:15:24 -0000	1.1.2.17
+++ gigya.install	27 Jan 2010 06:12:28 -0000
@@ -1,5 +1,5 @@
 <?php
-// $Id: gigya.install,v 1.1.2.17 2009/12/24 12:15:24 gigya Exp $
+// $Id: gigya.install,v 1.1.2.16 2009/11/26 15:38:51 gigya Exp $
 
 /**
  * @file
@@ -105,9 +105,41 @@
 }
 
 function gigya_update_6005() {
-  /* we cannot do a rest API change, so we need to tell the user to visit the gigya page to update it. */
-  drupal_set_message(t("You must visit the !configuration in order to validate and enable gigya",array("!configuration" => l('gigya configuration page', 'admin/settings/gigya'))));
-  return array(array('success' => TRUE, 'query' => 'Updated Gigya service validation settings.'));
+ /* we cannot do a rest API change, so we need to tell the user to visit the gigya page to update it. */
+ drupal_set_message(t("You must visit the !configuration in order to validate and enable gigya",array("!configuration" => l('gigya configuration page', 'admin/settings/gigya'))));
+ return array(array('success' => TRUE, 'query' => 'Updated Gigya service validation settings.'));
+}
+
+/**
+ * Updates weight and migrates existing variables
+ */
+function gigya_update_6006() {
+  $items = array();
+  
+  // set weight to content profile registration + 1
+  switch ($GLOBALS['db_type']) {
+    case 'mysqli':
+    case 'mysql':
+    case 'pqsql':
+      $items[] = update_sql("UPDATE {system} SET weight = 2 WHERE name = 'gigya'");
+      break;
+  }
+  
+  // migrate existing mapping variables to the new variables
+  if (module_exists('profile')) {
+    $result = _profile_get_fields($category, TRUE);
+    $weight = 1;
+    $fields = array();
+    while ($field = db_fetch_object($result)) {
+      $bio_assoc = variable_get('gigya_profile_'. $field->name, '');
+      if (!empty($bio_assoc)) {
+        variable_set('gigya_bio_'. $bio_assoc, $arr_name);
+      }
+    }
+  }
+
+  $items[] = array('success' => TRUE, 'query' => 'Migrated mapping variables of core profile fields.');
+  return $items;
 }
 
 /**
Index: gigya.behaviors.js
===================================================================
RCS file: /cvs/drupal/contributions/modules/gigya/Attic/gigya.behaviors.js,v
retrieving revision 1.1.2.2
diff -u -r1.1.2.2 gigya.behaviors.js
--- gigya.behaviors.js	31 Jul 2009 02:25:10 -0000	1.1.2.2
+++ gigya.behaviors.js	27 Jan 2010 06:12:28 -0000
@@ -5,3 +5,7 @@
       gigya.services.socialize.addEventHandlers(Drupal.settings.gigya.conf, { onConnect:Drupal.gigya.notifyFriends_callback, onDisconnect:Drupal.gigya.notifyFriends_callback });
    });
 };
+
+Drupal.behaviors.gigya_init = function(context){
+	gigya.services.socialize.getUserInfo(Drupal.settings.gigya.conf,{callback: Drupal.gigya.init_response}); 
+}
Index: gigya.admin.inc
===================================================================
RCS file: /cvs/drupal/contributions/modules/gigya/Attic/gigya.admin.inc,v
retrieving revision 1.1.2.20
diff -u -r1.1.2.20 gigya.admin.inc
--- gigya.admin.inc	24 Dec 2009 12:15:24 -0000	1.1.2.20
+++ gigya.admin.inc	27 Jan 2010 06:12:28 -0000
@@ -1,5 +1,5 @@
 <?php
-// $Id: gigya.admin.inc,v 1.1.2.20 2009/12/24 12:15:24 gigya Exp $
+// $Id: gigya.admin.inc,v 1.1.2.19 2009/11/29 13:23:14 gigya Exp $
 
 /**
  * @file
@@ -14,10 +14,11 @@
 /**
  * Constants defined for gigya system settings
  */
-define('GIGYA_MODULE_VERSION', 'gigya-6.x-1.0-beta10 minor version:3');
+define('GIGYA_MODULE_VERSION', 'gigya-6.x-1.0-beta10 minor version:2');
 define('GIGYA_ALREADY_DRUPAL_USER', 'already_drupal_user');
 define('ONLY_SOCIALIZE_USER','only_socialize_user');
 define('GIGYA_ENABLE_FACEBOOK_POPULATION','gigya_enable_facebook_population');
+define('GIGYA_POPULATE_NON_REG_PROFILE_FIELDS','gigya_populate_non_reg_profile_fields');
 define('GIGYA_DEFAULT_ICONSIZE', 30);
 define('GIGYA_DEFAULT_LOGINUI_WIDTH', '120');
 define('GIGYA_DEFAULT_LOGINUI_HEIGHT', '110');
@@ -68,12 +69,12 @@
  *
  */
 function gigya_admin_form() {
-  global $user,$base_path ;
-  include_once 'modules/user/user.pages.inc';
+  global $user;
+  include_once($base_path .'modules/user/user.pages.inc');
   module_load_include('inc', 'gigya');
   $capabilities = gigya_get_capabilities();
   $form = array();
-   
+
   gigya_validate();
 
   $form['keys'] = array(
@@ -106,7 +107,7 @@
     '#title' => t('Networks available to socialize'),
     '#default_value' => variable_get('gigya_selected_networks', array()),
     '#options' => gigya_get_networks(),
-    '#required' => TRUE,    
+    '#required' => TRUE,
     '#description' => t('Select the networks this site should be allowed to connect to via socialize'),
     '#weight' => -3,
   );
@@ -551,44 +552,83 @@
       '#description' => t('Checking this option allows users to connect their user picture to their drupal profile picture'),
     );
   }
-  
+  // Start filling the mapping part
+  $fields = array('--Not mapped--', 'username');
   if (module_exists('profile')) {
-    $form['profile'] = array(
-      '#type' => 'fieldset',
-      '#title' => t('Gigya <=> Drupal Profile Mappings'),
-      '#collapsible' => TRUE,
-      '#collapsed' => FALSE,
-    );
+	 $form['profile'][GIGYA_POPULATE_NON_REG_PROFILE_FIELDS] = array(
+		'#type' => 'checkbox', 	 
+	   	'#title' => t('Map non-registration profile fields.'),
+	    '#description' => t('(You will have to save the configuration to see the change). Normally you can only map fields that are visible on your registration form.  Enabling this will allow you to map any of your profile fields.  Please note that this can cause unexpected behavior with some configurations.  Disable it if you are having problems.'), 
+	  	'#default_value' => variable_get(GIGYA_POPULATE_NON_REG_PROFILE_FIELDS,FALSE),      
+	    '#weight' => -20,
+	  );
+	  // Gather profile fields (profile module)
     if ($profile_categories = profile_categories()) {
       $profile_fields = array();
       $category_names = array();
       foreach ($profile_categories as $category) {
         $category_names[$category['name']] = $category['name'];
-        $profiles = profile_form_profile(NULL, NULL, $category['name'], TRUE);
+        $profiles = profile_form_profile(NULL, NULL, $category['name'], !variable_get(GIGYA_POPULATE_NON_REG_PROFILE_FIELDS,TRUE));
         if ($profiles && $profiles[$category['name']]) {
           foreach ($profiles[$category['name']] as $field_name => $profile) {
             if (is_array($profile)) {
-              $form['profile']['gigya_profile_'. $field_name] = array(
-                '#type' => 'select',
-                '#title' => $profile['#title'],
-                '#options' => array_merge(array(0 => ''), _gigya_get_profile_fields()),
-                '#default_value' => variable_get('gigya_profile_'. $field_name, ''),
-              );
+              $fields[] = $field_name;
             }
           }
         }
       }
     }
-    else {
-      //drupal_set_message(t("Although the profile module is enabled, You currently have no profile categories created"));
+   else {
+    drupal_set_message(t("Although the profile module is enabled, You currently have no profile categories created"));
+   }
+  }
+  // Gather content profile fields
+  elseif (module_exists('content') && module_exists('content_profile')) {
+    $profile_types = content_profile_get_types('names');
+  
+   if (!empty($profile_types)) {
+   	  foreach ($profile_types as $type => $name) {
+        $typeinfo = content_types($type);
+        $fields = array_merge($fields, array_keys($typeinfo['fields']));
+   	  }
     }
   }
   else {
-    $form['from'] = array(
+    $form['bio_mapping'] = array(
       '#type' => 'item',
-      '#title' => t('Profile Module Disabled'),
-      '#value' => t('If you wish to map profile settings to gigya settings, please enable the profile module'),
+      '#title' => t('Profile Modules Disabled'),
+      '#value' => t('If you wish to map profile settings to gigya settings, please enable the Profile module and/or the Content Profile module'),    );
+  }
+  if (!empty($fields)) {
+    // Build the mapping list
+    $form['bio_mapping'] = array(
+      '#type' => 'fieldset',
+      '#title' => t('Gigya <=> Drupal Profile Mappings'),
+      '#collapsible' => TRUE,
+      '#collapsed' => FALSE,
     );
+    foreach (_gigya_get_profile_fields() as $field_key => $field_name) {
+      if ($field_name != 'email') {
+        $form['bio_mapping']['gigya_bio_'. $field_name] = array(
+          '#type' => 'select',
+          '#title' => $field_name,
+          '#options' => array_combine($fields, $fields),
+          '#default_value' => variable_get('gigya_bio_'. $field_name, ''),
+        );
+      }
+      if ($field_name == 'gender') {
+        $form['bio_mapping']['gigya_bio_gender'] = array_merge($form['bio_mapping']['gigya_bio_gender'], 
+        array('#description' => t('Gender CCK field must have keys "m" and "f". Labels can be whatever needed')));
+      }
+      if ($field_name == 'nickname') {
+        $form['bio_mapping']['gigya_bio_nickname'] = array_merge($form['bio_mapping']['gigya_bio_nickname'], 
+        array('#description' => t('You may want to map this to "username"')));
+      }
+      if (strpos($field_name, 'birth') !== false) {
+        $form['bio_mapping']['gigya_bio_'. $field_name] = array_merge($form['bio_mapping']['gigya_bio_'. $field_name], 
+        array('#description' => t('You may map month, day, year to the same date CCK field')));
+      }
+    }
   }
   
   $form['Facebook fields Population'] = array(
@@ -636,4 +676,5 @@
     $form_state['values']['gigya_connect_uiconfig_color_background'] = 'Transparent';
          
   variable_set(GIGYA_ENABLE_FACEBOOK_POPULATION,$form_state['values'][GIGYA_ENABLE_FACEBOOK_POPULATION]);           
+  variable_set(GIGYA_POPULATE_NON_REG_PROFILE_FIELDS,$form_state['values'][GIGYA_POPULATE_NON_REG_PROFILE_FIELDS]);
 }
\ No newline at end of file

