### 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	1 Feb 2010 08:47:03 -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,23 +7,22 @@
  */
 
 /**
- * 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) {
-	
   global $base_url;
-    
+
   module_load_include('inc', 'gigya');
   $title = isset($account->title) ? $account->title : $account->name;
   drupal_set_title(check_plain($title));
 
   $form = array();
   gigya_login_block_js();
-  
+
   $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,238 +31,164 @@
       $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>',
   );
+
+  return drupal_render($form);
 }
 
-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');
-  }
+function gigya_shareui_ajax($currObj,$objType,$objID,$currUrl) {          
+  $shareUI_js = gigya_shareUI_js($currObj,$objType,$objID,$currUrl);
+  drupal_add_js($shareUI_js,'inline'); 
+  return '<div id="shareUI">'. t("Please wait for shareUI component of socialize") .'</div>';
 }
 
 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");
-  }
-  else {
-    $logout_behavior = array("logout_location" => $base_path);
-  }
+
+  $dest = $_REQUEST['destination'];
+  if(empty($dest)) $dest = $base_path;
+  $logout_behavior = array("logout_location" => $base_path);
+  
   drupal_add_js(array('gigya' => $logout_behavior), 'setting');
 
   $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;
-  
-  	  
-  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);
+  global $user, $base_path;
+
+  drupal_set_message('gigya_login_ajax u:' . $user->uid > 0);
+  module_load_include('inc', 'gigya'); 
+
+	if (!($user->uid)) { //not yet logged in to Drupal
+
+    if($_gigya_user = GigyaUser::UserFromUrl()){
+      $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) {
+          //we can suppress the notifylogin js because the user is clearly already logged into gigya
+          $_SESSION['gigya_suppress_notifylogin_js'] = true;
+          
+          //log the user in
+          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.
+ * AJAX function to handle various requests to gigya
+ * for now it's just used to set session variables for the javascript
+ */
+function gigya_ajax($op){
+  switch($op){
+    case 'notify-login':
+      $_SESSION['gigya_suppress_notifylogin_js'] = true;
+    break;
+    case 'link-accounts-complete':
+      $_SESSION['link_accounts'] = false;
+    break;
+    case 'logout':
+      
+    break;
+  }
+  exit();
+}
+
+
+/**
  */
 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')
         $site_friends[] = $friend_arr;
     }
   }
-
   return theme('gigya_friends', $site_friends);
 }
 
@@ -281,67 +206,24 @@
 
   $userinfo = '<div id="userinfo"></div>';
   return $userinfo;
-
 }
 
-
-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 +231,17 @@
     '#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'),
@@ -372,25 +249,13 @@
       'onClick' => "Popups.close();",
     ),
   );
-
-
-  $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,13 +269,11 @@
     }
   }
   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', ''),
                           );
-
   }
 
   switch ($form_state['values']['op']) {
@@ -419,10 +282,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:
 
@@ -431,14 +293,12 @@
 }
 
 function gigya_notify_friends($node) {
-
-  module_load_include('inc', 'gigya');   
-  popups_add_popups();
   global $user, $base_root;
-  $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);
+	module_load_include('inc', 'gigya');   
+  popups_add_popups();
+  $title = variable_get('gigya_share_link_title', GIGYA_DEFAULT_SHARE_LINK_TITLE);
+  drupal_set_title(check_plain($title));
+  $friends = gigya_getFriendsInfo($user->uid);
 
   if (variable_get('gigya_friends_uiconfig_raw', '')) {
     $friends_uiconfig = variable_get('gigya_friends_uiconfig_raw', '');
@@ -457,7 +317,7 @@
       "UIConfig" => $friends_uiconfig,
     ),
   );
-  
+
   drupal_add_js(array('gigya' => $gigya_friends_params), 'setting');
   $attach_behaviors_js = 'Drupal.attachBehaviors()';
   drupal_add_js($attach_behaviors_js, 'inline');
@@ -467,7 +327,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 +347,18 @@
   return $output;
 }
 
+function gigya_register(){
+  global $user;
 
-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_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;
+  // 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();
+  }
+  $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	1 Feb 2010 08:47:03 -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.
@@ -15,7 +15,7 @@
 /**
  * Implementation of hook_help().
  */
-function gigya_help() {
+function gigya_help($path,$arg) {
   switch ($path) {
     case 'admin/settings/gigya':
       return '<p>'. t('Server-wide setup of the gigya socialize module.') .'</p>';
@@ -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'),
@@ -82,17 +90,22 @@
     'page callback' => 'gigya_logout_ajax',
     'type' => MENU_CALLBACK,
     '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),
+  $items['gigya/shareui/%/%'] = array(
+    'page callback' => 'gigya_shareui_test',
+    'page arguments' => array(2,3),
     'type' => MENU_CALLBACK,
+    'access arguments' => array('access content'),
+    'file' => 'gigya.pages.inc',
+  );      
+  $items['socialize-ajax/%'] = array(
+    'page callback' => 'gigya_ajax',
+    'type' => MENU_CALLBACK,
+    'access arguments' => array('access content'),
     'file' => 'gigya.pages.inc',
+    'page arguments' => array(1),
   );
   $items['gigya/notifyfriends/%node'] = array(
     'page callback' => 'gigya_notify_friends',
@@ -116,7 +129,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 +141,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() {
@@ -145,27 +162,106 @@
       'any' => TRUE,
     ),
   );
-  $info['gigya_status_popup_action'] = array(
+  
+  $info['gigya_shareUI_action'] = array(
     'type' => 'system',
-    'description' => t('Update Social Networking Status with Gigya Socialize'),
+    'description' => t('Share UI of Gigya Socialize'),
     'configurable' => TRUE,
     'hooks' => array(
       'any' => TRUE,
     ),
-  );
+  );  
   return $info;
 }
 
+function gigya_shareUI_action($object, $context) {
+  global $base_path,$user;
+  
+  /*
+  watchdog('gigya', 'In gigya_shareUI_action ');
+  
+  
+  $xxx = gigya_printObject('',$context);
+  drupal_set_message('In gigya_shareUI_action:' . $xxx);   */
+  
+ 
+  module_load_include('inc', 'gigya');
+  
+  if(!($user->setStatus_popup_hide)){
+    $hook = $context['hook'];
+    $_SESSION['shareUI_action'] = $hook;
+    switch ($hook) {
+  	  case 'comment':	    			      	      	   
+  	      $context['node'] = node_load($context[$hook]->nid);	      	        		
+  		  $_SESSION['shareUI_nid'] = $context['node']->nid;
+  		  $_SESSION['shareUI_node'] = $context['node'];
+  		  $_SESSION['shareUI_default_message'] =$context['shareUI_default_message'];	
+  	    break;
+  	  case 'user':
+  		  $context['user'] = user_load($context['account']->uid);    	        		
+  		  $_SESSION['shareUI_uid'] = $context['user']->uid;
+  		  $_SESSION['shareUI_user'] = $context['user'];
+  		  
+  		  if ( $context['op'] ) {
+  		  	if ( $context['op'] == t('update') ) {
+  		  		$_SESSION['shareUI_default_message'] = 'Updated his/her profile';
+  		  	}
+  		  	else {
+  		  		$_SESSION['shareUI_default_message'] =$context['shareUI_default_message'];
+  		  	}
+  		  }
+  		  else {		  
+  		  	$_SESSION['shareUI_default_message'] =$context['shareUI_default_message'];
+  		  }
+  
+  	    break;
+  	  case 'nodeapi':
+  	  	$_SESSION['shareUI_nid'] = $context['node']->nid;
+  		  $_SESSION['shareUI_node'] = $context['node'];		  		  		
+  		  $_SESSION['shareUI_default_message'] = $context['shareUI_default_message'];
+  
+      	break;
+    }
+  }
+  
+}
+
+function gigya_shareUI_action_form($context) {
+  $form['shareUI_default_message'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Default User Message'),
+    '#description' => t('Configure the default user message for this action. E.g.: "posted an item"'),
+    '#default_value' => isset($context['shareUI_default_message']) ? $context['shareUI_default_message'] : 'posted a Drupal site item',
+    '#required' => TRUE,
+  );
+  /*$form['shareUI_content_types'] = array(
+    '#type' => 'select',
+    '#title' => t('Restrict shareUI items to the following content types'),
+    '#options' => node_get_types('names'),
+    '#multiple' => TRUE,
+    '#default_value' => isset($context['shareUI_content_types']) ? $context['shareUI_content_types'] : '',
+  );  */
+  return $form;
+}
+
+function gigya_shareUI_action_submit($form, $form_state) {  
+  return array(
+    'shareUI_template' => $form_state['values']['shareUI_template'],
+    'shareUI_default_message' => $form_state['values']['shareUI_default_message'],
+    //'shareUI_content_types' => $form_state['values']['shareUI_content_types'],
+  );
+}
+
 function gigya_newsfeed_action($object, $context) {
-  global $base_path;
+  global $base_path,$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 (!($user->uid)) {
+    return false;
   }
+  
   $xml_params = array();
   $xml_params['action'] = $context['default_message'];
   $xml_params['template'] = $context['template'];
@@ -199,44 +295,7 @@
     !empty($xml_params['template']) &&
     !empty($xml_params['action']) &&
     !empty($xml_params['path']))
-    gigya_publish_user_action($_SESSION['gigya_uid'], $xml_params);
-}
-
-function gigya_status_popup_action($object, $context) {
-  global $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);    
-    $_SESSION['setStatus_msg'] = $context['gigya_status_node_description'];
-    $_SESSION['setStatus_default'] = $context['gigya_status_node_default_message'];	          
-  }
-  
-  if ($hook == 'user') {
-    $_SESSION['setStatus_popup'] = TRUE;
-    $_SESSION['setStatus_uid'] = $context['account']->uid;
-    $_SESSION['setStatus_msg'] = $context['gigya_status_user_description'];
-    $_SESSION['setStatus_default'] = $context['gigya_status_user_default_message'];
-    return;
-  }
-
-  if (array_search($context['node']->type, $context['status_popup_content_types']) || empty($context['newsfeed_content_types'])) {
-    $_SESSION['setStatus_popup'] = TRUE;
-    $_SESSION['setStatus_nid'] = $context['node']->nid;
-    $_SESSION['setStatus_msg'] = $context['gigya_status_node_description'];
-    $_SESSION['setStatus_default'] = $context['gigya_status_node_default_message'];    
-  }
+    $user->gigya->PublishUserAction($xml_params);
 }
     
 function gigya_newsfeed_action_form($context) {
@@ -275,6 +334,7 @@
 /**
  * Form for configurable Drupal action for newsfeeds and status popups.
  */
+/*
 function gigya_status_popup_action_form($context) {
 	
 	module_load_include('module','popups');
@@ -330,47 +390,78 @@
     'gigya_status_node_description' => $form_state['values']['gigya_status_node_description'],
     'gigya_status_node_default_message' => $form_state['values']['gigya_status_node_default_message'],
   );
-}
+}*/
 
 function gigya_init() {
-  global $base_path,$base_url, $user;
+  global $base_path,$base_url,$user;
+  
   gigya_load_js();
   
-  if ($_SESSION['setStatus_popup']) {
-  	if ( !($user->uid)) {
-  		return;
-  	}  	
-
-  	popups_add_popups();
-  	
-    if (is_numeric($_SESSION['setStatus_nid'])) {  //nodeapi and comments
-		$currUrl = $base_url . '/gigya/setStatus/node/' . $_SESSION['setStatus_nid'] ;  
-      	$jquery_onLoad = "$(document).ready(function() { Drupal.gigya.loadSetStatusPopup('$currUrl'); });";     
-    }
-    else if (is_numeric($_SESSION['setStatus_uid'])) {  //users
-    	$currUrl = $base_url . '/gigya/setStatus/user/' . $_SESSION['setStatus_uid'] ;
-		$jquery_onLoad = "$(document).ready(function() { Drupal.gigya.loadSetStatusPopup('$currUrl'); });";        
-    }             
-    drupal_add_js($jquery_onLoad, 'inline');
-    unset($_SESSION['setStatus_popup']);
+  
+  if(empty($user->uid)){
+    //notify login is obsolete since we're logged out
+    $_SESSION['gigya_notify_login'] = false;    
+  }
+  else{
+  
+    //only use this if we want the javascript version of linkaccounts
+    /*if($_SESSION['link_accounts']){
+         date_default_timezone_set('GMT');
+        $timestamp = date('Y-m-d H:i:s');
+      
+      
+        $signature = _gigya_verify_signature($timestamp, $user->uid, variable_get('gigya_SecretKey', FALSE));
+        
+        $gigya_link_accounts_params = array(
+          'link_accounts_params' => array(
+          "siteUID" => $user->uid,
+          "timestamp" => $timestamp,
+          "signature" => $signature
+        ));
+      
+        drupal_add_js(array('gigya' => $gigya_link_accounts_params), 'setting');  
+      
+        $behaviors_js = 'Drupal.behaviors.gigya_linkAccounts = function(){ 
+          Drupal.settings.gigya.link_accounts_params.callback = Drupal.gigya.linkAccounts_callback;
+         gigya.services.socialize.linkAccounts(Drupal.settings.gigya.conf, Drupal.settings.gigya.link_accounts_params); }';
+        drupal_add_js($behaviors_js, 'inline');
+    }*/
+    
+  
+    GigyaUser::Load($user);
+    //add the notify login js if it's needed
+    if(!$_SESSION['gigya_suppress_notifylogin_js']){
+      gigya_setNotifyLoginParams($user->uid);                
+    }
   }
+  
+	if ( $_SESSION['shareUI_action'] ) {	
+		$nType = $_SESSION['shareUI_action'];
+		if (is_numeric($_SESSION['shareUI_nid'])) {  //nodeapi and comments							
+			$currUrl = $base_url . '/node/' . $_SESSION['shareUI_nid'] ;	      	
+	      	module_load_include('inc', 'gigya', 'gigya.pages');
+	      	unset($_SESSION['shareUI_action']);
+	      	$currNode = $_SESSION['shareUI_node'];
+	      	unset($_SESSION['shareUI_node']);
+	      	return gigya_shareui_ajax($currNode,$nType,$_SESSION['shareUI_nid'],$currUrl);	      	     
+	  }
+	  else if (is_numeric($_SESSION['shareUI_uid'])) {  //users	    		    		    	
+      $currUrl = $base_url . '/user/' . $_SESSION['shareUI_uid'] ;
+      module_load_include('inc', 'gigya', 'gigya.pages');
+      unset($_SESSION['shareUI_action']);
+        
+      $currUser = $_SESSION['shareUI_user'];
+      unset($_SESSION['shareUI_user']);	    	
+			return gigya_shareui_ajax($currUser,$nType,$_SESSION['shareUI_uid'],$currUrl);			       
+	  }             	    
+	  unset($_SESSION['shareUI_action']);	      	
+  }  	
+  
 }
 
 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');
-	  	}
-	  }
-  }  
-  
+    
   switch ($op) {
     case 'update':
     case 'insert':
@@ -384,12 +475,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($user->uid){
+          if ($result = $user->gigya->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 +500,54 @@
  * 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,$user;	
+
   module_load_include('inc', 'gigya');
   switch ($op) {
-    case 'login':    	
-      if (arg(1) == 'reset') {
-        break;
-      }
+    case 'form' :
+      if($category == 'account'){
+        $form = array();
+        $form['gigya'] = array(
+          '#type' => 'fieldset',
+          '#title' => t('Social network user settings'),
+          '#weight' => -1,
+          '#collapsible' => TRUE,
+          '#collapsed' => FALSE,
+          '#description' => t('Configure your socialize behaviors')
+        );
         
-      
-      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);
+        $form['gigya']['setStatus_popup_hide'] = array(
+          '#type' => 'checkbox',
+          '#title' => t('Never show popups for social network status updates'),
+          '#default_value' => $account->setStatus_popup_hide,
+          );
+        return $form;
       }
+    break;
+    case 'load':
+      GigyaUser::Load($account);
+    break;
+    case 'login':
       break;
     case 'logout':
-  		$userLoggedStr='gigya_' . $user->uid . '_logged';  
-	  	if ( $_SESSION[$userLoggedStr] ) {
-	  		unset($_SESSION[$userLoggedStr]);
-	  	}     
-      	unset($_SESSION['gigya_uid']);            	
-        drupal_goto('socialize-logout');
+      $user->gigya->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);
+        //$_SESSION['link_accounts'] = true;
+        $_gigya_user->MapExtendedProfileFields($edit);
+        
+        //we can suppress the notifylogin js because the user is clearly already logged into gigya
+        $_SESSION['gigya_suppress_notifylogin_js'] = true;
+      }
       break;
     case 'delete':
-      gigya_delete_profile($account->uid);
+      $account->gigya->Unlink();
       break;
     case 'categories':
       return array(
@@ -464,8 +559,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) {
@@ -511,11 +607,10 @@
   }
 }
 
-function gigya_printObject($parentKey='',$currentObject,$depth=0) {
-	if ( !$currentObject ) {
+function gigya_printObject($parentKey='', $currentObject,$depth=0) {
+	if (!$currentObject) {
 		return $parentKey . '->N/A';
 	}
-	
 	$xxx = '';	
 	$spaces = str_repeat('&nbsp;',(2*$depth)+1);
 	foreach ($currentObject as $key => $val) {			
@@ -533,242 +628,25 @@
 	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;
+function gigya_link_accounts_submit(&$form, &$form_state) {
+	global $user;
+	if (!empty($user->uid) && $_gigya_user = GigyaUser::UserFromUrl()){
+	
+    
+    $_gigya_user->LinkAccounts($user->uid);
+        
+    /**
+     *  Don't suppress notify login for now -- hopefully we'll get a response to this question:
+     *  http://forum.gigya.com/forum/Default.aspx?g=posts&t=775
+     */
+	  //$_SESSION['link_accounts'] = true;
+    //$_SESSION['gigya_suppress_notifylogin_js'] = true;
      
-  $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(&$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);
-  	
+  return;
 }
 
-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().
@@ -776,66 +654,15 @@
  * 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 $base_url,$user;	
   
   $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;
-    $account = user_load($form['#uid']);
-    if (user_get_authmaps($account->uid)) {
-      unset($form['account']['pass']);
-    }
-
-    $form['gigya'] = array(
-      '#type' => 'fieldset',
-      '#title' => t('Social network user settings'),
-      '#weight' => -1,
-      '#collapsible' => FALSE,
-      '#collapsed' => FALSE,
-      '#description' => t('Configure your socialize behaviors')
-    );
-    //if ($account->setStatus_popup_hide == 1) {
-      $form['gigya']['setStatus_popup_hide'] = array(
-        '#type' => 'checkbox',
-        '#title' => t('Never show popups for social network status updates'),
-        '#default_value' => $account->setStatus_popup_hide,
-      );
-      $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 +670,115 @@
         '#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';
     }
+    */
+    $account = user_load($form['#uid']);
+    $gigya_bio = $account->gigya->GetUserInfo();
+    if (!empty($gigya_bio)) {
+      if($gigya_bio['loginProvider'] != 'siteaccount') unset($form['account']['pass']);
+    }
   }
   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
+  	module_load_include('inc', 'gigya');
+    module_load_include('.inc', 'user', 'user.pages');
+
+    //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]);	
-	      	}
-      	}
-      } 
-      
-      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;      				
-      		}
-      	}
-      }
-      
-      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);
+      $form['links']['#weight'] = 2;    
     }
-    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{// if they HAVE logged into gigya then populate some of the data and hide the password field
+      $bio = $_gigya_user->GetUserInfo();
+      //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;
+      }
+      //map the fields from the social network
+      if(gigya_populate_fields($bio['loginProvider'])) {
+        // @TODO How should username and email be dealt with?
+        // Mabye We could have a choice to map something to username in the admin,
+        // And the var_get() it here
+        // With regards for email, it seems strange that we are even collecting email,
+        // Since the user has just authenticated with a affiliate network,
+        // Why do we force them to enter an email address at all?
+        //$form_account['name']['#default_value'] = (empty($bio['nickname']) ? '' : $bio['nickname']);
+        //$form_account['mail']['#default_value'] = (empty($bio['email']) ? '' : $bio['email']);
+        //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];
+                      }
+                    }                                                                    
+                  }
                 }
-				else {
-					$form['requiredCategories'][$cat_name][$arr_name]['#default_value'] = '';
-				}									                                  	                               
               }
             }
           }
         }
       }
+      elseif (module_exists('content') && module_exists('content_profile')) {
+        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, '');
+          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];
+          }
+        }
+      }
+      if (!variable_get('user_email_verification', TRUE)) {
+        $form_account['pass']['#type'] = 'hidden';
+        $form_account['pass']['#value'] = user_password();
+      }
+      if(module_exists('logintoboggan')) {
+        // @TODO Is there something we should do here?
+      }
     }
-        
-    $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 +789,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,46 +800,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;     
+    global $user, $_gigya_uid;  
+      
     module_load_include('inc', 'gigya');
 
     if (variable_get('gigya_login_surpress_login', FALSE)) {
@@ -1094,11 +820,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,35 +836,31 @@
     );
     $form['links']['#weight'] = 2;
     
-    
-   
-	if (isset($form['#action'])) {				
-		$currAction = $form['#action'];
-		if (strpos($currAction,'socialize-login') ) {
-			unset($form['links']);  
-			unset($form['name']);
-      		unset($form['pass']);
-      		unset($form['submit']);
-			unset($form['gigya_login']);
-		}  
-	}
+  	if (isset($form['#action'])) {
+  		$currAction = $form['#action'];
+  		if (strpos($currAction,'socialize-login') ) {
+  			unset($form['links']);  
+  			unset($form['name']);
+        		unset($form['pass']);
+        		unset($form['submit']);
+  			unset($form['gigya_login']);
+  		}  
+  	}
 	
-    return;
+    return $form;
   }
   
-  /** 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($user->uid)) return;
+    if (!$user->gigya->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();
@@ -1163,38 +885,14 @@
     $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))));
-  }
-}
-
 /**
  * If the user deletes the photo or load a new picture, 
  * we deactivate the automatic import of the avatar.
@@ -1211,40 +909,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() {
@@ -1255,6 +931,7 @@
   $params['timestamp'] = gmmktime();
   return $params;
 }
+
 /**
  * gigya javascript bootstrap
  *
@@ -1272,7 +949,6 @@
     drupal_set_message(t("the gigya module is enabled but not configured. !configure",array("!configure" => l("Please configure it now","admin/settings/gigya"))));  
     return;
   }
-    
   // we dont care about the friendly titles, and when the checkboxes in the system settings area
   // are saved, all the keys are saved but with a 0 for the unselected values. if we swap the keys
   // with values all the unselected ones except for the last get automatically unset
@@ -1290,6 +966,7 @@
   drupal_add_js($path .'/gigya.js');
   drupal_add_js($path .'/gigya.behaviors.js');
 }
+
 /**
  * gigya javascript settings for login block
  *
@@ -1302,14 +979,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,85 +998,53 @@
       "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');
   
+  $signature = _gigya_verify_signature($timestamp, $userID, variable_get('gigya_SecretKey', FALSE));
   $gigya_notify_login = array(
     'notify_login_params' => array(
     "siteUID" => $userID,
     "timestamp" => $timestamp,
     "signature" => $signature,
-    "context" => array("method" => "notifyLogin"),
+    "context" => array("method" => "notifyLogin")
   ));
   
   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');
 }
 
-/**
- * GIGYA Javascript Wrappers
- *
- * The following functions inject gigya JS for their respective function name
- */
-/**
- * Wrapper for the gigya javascript NotifyLogin function.
- *
- * @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;
-}
-function gigya_link($type, $node = NULL, $teaser = FALSE) {
+function gigya_link($type, $object, $teaser = FALSE) {
   module_load_include('inc', 'gigya');
   global $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(!($user->uid)) return $links;
+  
+  if ($user->gigya->HasCapability('Notifications') && $user->gigya->HasCapability('Friends')) {
+    $allowed_types = variable_get('gigya_share_types', array('story' => 'story', 'blog' => 'blog'));
+    if ($type == 'node' && !empty($allowed_types[$object->type])) {
+      $links['socialize_notify_friends'] = array(
+        'title' => variable_get('gigya_share_link_title', GIGYA_DEFAULT_SHARE_LINK_TITLE),
+        'href' => "gigya/notifyfriends/$object->nid",
+        'attributes' => array('title' => t('Tell your friends about !nodetitle.', array('!nodetitle' => $object->title)), 'class' => 'popups-form'),
+      );
     }
   }
   return $links;
 }
+
 /**
  * Implementation of hook_theme().
  */
@@ -1426,6 +1069,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 +1082,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 +1097,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;
@@ -1525,14 +1166,14 @@
 
 function gigya_preprocess_block(&$vars) {
 	if ( $vars['block']->subject == t('User login') ) {  
-		if ( variable_get('remove_user_login_title', FALSE) ) {
-				$vars['block']->subject = '';	
+    if ( variable_get('remove_user_login_title', FALSE) ) {
+		  $vars['block']->subject = '';	
 		}
-		else {			
-			if ( variable_get('gigya_login_surpress_login',FALSE) ) {
-				$vars['block']->subject = 'Login using social networks';
-			} 
-		}			
+    else {			
+      if ( variable_get('gigya_login_surpress_login',FALSE) ) {
+        $vars['block']->subject = 'Login using social networks';
+      } 
+    }			
 	} 
 	else {
 		if ( $vars['block']->subject == '' ) {  
@@ -1557,10 +1198,8 @@
   return $output;
 }
 
-
-
 /**
- * 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
@@ -1601,39 +1240,261 @@
   return $output;
 }
 
+function gigya_footer($main=0) {
+	module_load_include('inc', 'gigya', 'gigya.admin');
+	return '<!-- ' . GIGYA_MODULE_VERSION . ' -->';
+}
 
-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_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_footer($main=0) {
-	module_load_include('inc', 'gigya', 'gigya.admin');
-	return '<!-- ' . GIGYA_MODULE_VERSION . ' -->';
-}	
+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 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 Load(&$account){
+    $account->gigya = new GigyaUser($account->uid);
+  }
+   
+  public function Logout(){
+    /*
+     * redirect to a logout URL where javascript will be added to the page
+     * I don't like doing this on a separate page -- it's kinda fragile -- but it's the best
+     * I can figure out for now since the session gets destroyed by the user_logout function
+     */
+    $_REQUEST['destination'] = urlencode('socialize-logout?destination='. $_REQUEST['destination']);
+  }
+  
+  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 array();
+    }
+  }
+  
+  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;
+    }           
+  }
+}
 
+function gigya_shareUI_js($currObj,$objType,$objID,$currUrl) {		
+	global $base_url;
+	/*$xxx = gigya_printObject('',$currObj);
+	drupal_set_message('nodeeee= ' . $xxx);*/	 	
+	if ( t('comment')==$objType) {
+		// Setting the Title";
+		$current_title = $currObj->title;
+		if (empty($current_title)) {
+			$current_title = drupal_get_title();
+			if (empty($current_title)) {
+				$current_title = 'A Drupal site item';
+			}
+		}
+
+		// Setting the description";
+		if ( empty($currObj->teaser) ) {
+			$currBody = $currObj->body;
+		}
+		else {
+			$currBody = $currObj->teaser;
+		}
+		
+		$currAction = 'commented on item: ';
+	} 
+	else {
+		$current_title = drupal_get_title();
+		if (empty($current_title)) {
+			$current_title = 'A Drupal site item';
+		}	
+		$currBody = '';
+		
+		$currAction = 'viewed';
+	}
+	$current_title = str_replace('039;','\\\'',$current_title);
+	$current_title = str_replace("'",'\'',$current_title);
+	$currBody = strip_tags($currBody);	
+	$currBody = str_replace('039;','\\\'',$currBody);	
+	$currBody = str_replace("\r",' ',$currBody);	
+	$currBody = str_replace("\n",' ',$currBody);		
+	$currBody = str_replace("'",'\'',$currBody);
+
+	// Constructing a UserAction Object; Constructor receives an Action Template string
+	$shareUI_js .= "var act = new gigya.services.socialize.UserAction('{actor} {action}'); ";
+	
+	// Setting the {action} in the Action Template String  
+	$shareUI_js .= "act.setActionName('$currAction'); " ;  
+	
+	// Setting the User Message;
+	$currUserMsg = empty($_SESSION['shareUI_default_message'])?'Enter your message here':$_SESSION['shareUI_default_message'];
+	$shareUI_js .= "act.setUserMessage('$currUserMsg'); ";
 
+	$shareUI_js .= 'act.setTitle("' . $current_title . '");';
+	
+	// Setting the Link Back
+	$shareUI_js .= "act.setLinkBack('$currUrl'); ";
+	
+	// Setting the Description		 
+	$shareUI_js .= 'act.setDescription("' . $currBody . '");';	
+	
+	$currImg ='';
+	if ( $currObj->images ) { 			
+		$currImages = $currObj->images;		
+		if ($currImages['preview']) {
+			$currImg = $currImages['preview'];	
+		}	
+		else {
+			if ($currImages['thumbnail']) {
+				$currImg = $currImages['thumbnail'];	
+			}			
+		}
+		if ( $currImg != '' ) { 
+			// Adding a Media Item (image)
+			$shareUI_js .= "var img = {";
+			$shareUI_js .= "		        src: '$base_url/$currImg',";					
+			$shareUI_js .= "		        href: '$currUrl',";			
+			$shareUI_js .= "		        type: 'image'";			
+			$shareUI_js .= "		    }; ";
+			$shareUI_js .= " act.addMediaItem(img); ";	
+		}
+	}
+	/*	 	 	
+		// 	Adding a Media Item (video)
+		$shareUI_js .= "var video = {";
+		$shareUI_js .= "		        src: 'http://www.youtube.com/watch?v=GaNjCal26CM',";
+		$shareUI_js .= "		        previewImageURL: '$base_url/$currImg',";
+		$shareUI_js .= "		        type: 'flash'";
+		$shareUI_js .= "		    }; ";
+		$shareUI_js .= " act.addMediaItem(video); ";  
+
+		*/
+	// Adding an Action Link
+	$shareUI_js .= "act.addActionLink('Check out the site', '$base_url'); ";
+ 	$shareUI_js .= "var shareUI_params= {};";
+	$shareUI_js .= "shareUI_params.showEditLink='false'; ";    		  
+  $shareUI_js .= 'shareUI_params.userAction=act; ';
+  // $shareUI_js .= "shareUI_params.showCaption='true'";
+  // $shareUI_js .= "shareUI_params.captionText='This is my Caption';";
+           		
+	// Publishing the User Action
+	$shareUI_js .= "gigya.services.socialize.showShareUI(Drupal.settings.gigya.conf, shareUI_params); ";	
+	return 'Drupal.behaviors.gigya_init = function(context){'. $shareUI_js .'}';
+}
\ No newline at end of file
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	1 Feb 2010 08:47:03 -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 $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 = $user->gigya->GetCapabilities()) {
     if (array_search('Status', $capabilities)) {
       $form = array();
       $form['status'] = array(
@@ -203,22 +108,21 @@
   $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;
 }
 
-
 function gigya_get_network_displayName($networkName) {	
 	$networks = gigya_get_networks();
 	if ( array_key_exists($networkName,$networks)) {		
@@ -246,23 +150,8 @@
   );
 }
 
-/**
- * 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) {
-		
   if (empty($uid)) {
     return;
   }
@@ -276,50 +165,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 +181,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 +251,7 @@
  * 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);
@@ -417,19 +275,13 @@
     }
     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,20 +292,12 @@
  * 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".
             "?timestamp=". drupal_urlencode($gigya_params['timestamp']) .  
@@ -462,35 +306,23 @@
             "&sig=". drupal_urlencode($signature) .  
             "&uid=". urlencode($gigya_params['uid']); //for some reason drupal_urlencode doesn't take out slashes
   $headers = array('Content-type' => 'application/x-www-form-urlencoded');
-    
-   
+
   $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);
   $url = "http://". variable_get('gigya_api_url', 'socialize.api.gigya.com') ."/socialize.getFriendsInfo".
             "?apiKey=". drupal_urlencode($gigya_params['apiKey']) .
@@ -500,6 +332,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;
   }
@@ -525,7 +358,6 @@
   if (_gigya_request_failure($results)) {
     return FALSE;
   }
-
   return _gigya_convert_xml_to_array($results->data);
 }
 
@@ -542,11 +374,9 @@
             "&sig=". drupal_urlencode($signature) .
             "&uid=". urlencode($gigya_params['uid']) .
             "&userAction=". rawurlencode($gigya_params['userAction']);
-
   $headers = array('Content-type' => 'application/x-www-form-urlencoded');
   $results = drupal_http_request($url, $headers, 'GET');
 
-
   if (_gigya_request_failure($results)) {
     return FALSE;
   }
@@ -558,10 +388,9 @@
  * 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();
   $gigya_params['uid'] = $gigya_uid;
   $gigya_params['siteUID'] = $drupalUid;
@@ -579,11 +408,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);
 }
 
@@ -591,10 +415,9 @@
  * Break the linkage in Gigya Socialize between the current Drupal user and gigya user (Drupal uid != Gigya uid)
  */
 function gigya_unlinkAccounts($gigya_uid,$drupalUid) {	 
-  if (empty($gigya_uid))
+  if (empty($gigya_uid)) {
     return FALSE;
-
-    	      
+  }
   $gigya_params = gigya_load_params();
   $gigya_params['uid'] = $gigya_uid;
   $gigya_params['siteUID'] = $drupalUid;
@@ -632,9 +455,6 @@
 function _gigya_calc_signature($secretkey, $httpmethod, $apimethod, $parameters) {
   require_once("OAuth.inc");
   $req = OAuthRequest::from_request($httpmethod, 'http://socialize.api.gigya.com/socialize.'. $apimethod, $parameters);
-  //print_r("Base String.... ");
-  //print_r($req->get_signature_base_string());
-  //print_r("<br /><br />");
   return base64_encode(hash_hmac('sha1', $req->get_signature_base_string(), base64_decode($secretkey), TRUE));
 }
 
@@ -658,8 +478,7 @@
 		$xxx = gigya_printObject('results ', $results);
   		watchdog('gigya', '_gigya_request_failure ' . $xxx);
 	}  
-  
-  
+
   switch ($code) { //see if there is a issue with the request on the http level
     case 302:
       watchdog('gigya', $errorcode . ' Missing Schema. ' . $errormsg);
@@ -704,8 +523,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');
       }
        
@@ -741,68 +560,3 @@
   $xml = new SimpleXMLElement($data);
   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	1 Feb 2010 08:47:03 -0000
@@ -146,16 +146,25 @@
 	return str;
 }
 
-/**
- * Callback for the gigya.notifyLogin function
- * 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' ) {	  	  
-    window.location = Drupal.settings.gigya.login_redirect;
+Drupal.gigya.linkAccounts_callback = function(response) {
+
+ if ( response['status'] == 'OK' ) {
+	 $.get(Drupal.settings.basePath + 'socialize-ajax/link-accounts-complete');
+ } 
+ else {
+   alert(response['statusMessage']);
+ }
+};
+
+
+Drupal.gigya.notifyLogin_callback = function(response) {
+	 //alert('notify login');
+  if ( response['status'] == 'OK' ) {
+    //window.location = Drupal.settings.gigya.login_redirect;
+	  //alert('notify login succeeded');
   } 
   else {
-    alert("Unable to log you in. Please contact the system administrator\n");
+    alert(response['statusMessage']);
   }
 };
 
@@ -278,11 +287,21 @@
   //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);
+	}
+	else{
+		//alert(response['user']['UID']);
+	}
+}
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	1 Feb 2010 08:47:03 -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
@@ -111,6 +111,38 @@
 }
 
 /**
+ * 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;
+}
+
+/**
  *
  //don't really need this at all.... since we store the user picture in the user table
 function gigya_update_6001() {
Index: gigya_updatestatus.js
===================================================================
RCS file: /cvs/drupal/contributions/modules/gigya/Attic/gigya_updatestatus.js,v
retrieving revision 1.1.2.3
diff -u -r1.1.2.3 gigya_updatestatus.js
--- gigya_updatestatus.js	24 Dec 2009 12:15:24 -0000	1.1.2.3
+++ gigya_updatestatus.js	1 Feb 2010 08:47:03 -0000
@@ -1,6 +1,5 @@
-
 // update status javascript. We want to limit to 140 characters
-Drupal.behaviors.gigya_updateStatus = function() {	
+Drupal.behaviors.gigya_updateStatus = function() {
   $("#gigya-textfield").keyup(function() {
     var charsLeft = (140 - $(this).val().length);
     var descDiv = $(this).parent().parent().parent().children(".description");
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	1 Feb 2010 08:47:03 -0000
@@ -2,6 +2,16 @@
   $('.friends-ui:not(.gigya_notifyFriends-processed)', context).addClass('gigya_notifyFriends-processed').each(
     function () {
       gigya.services.socialize.getUserInfo(Drupal.settings.gigya.conf, {callback:Drupal.gigya.notifyFriends_callback});
-      gigya.services.socialize.addEventHandlers(Drupal.settings.gigya.conf, { onConnect:Drupal.gigya.notifyFriends_callback, onDisconnect:Drupal.gigya.notifyFriends_callback });
+      gigya.services.socialize.addEventHandlers(Drupal.settings.gigya.conf, {onConnect:Drupal.gigya.notifyFriends_callback, onDisconnect:Drupal.gigya.notifyFriends_callback });
    });
 };
+
+Drupal.behaviors.gigya_init = function(context){
+	if(Drupal.settings.gigya.notify_login_params != undefined){
+		//let the server know that notifylogin was attempted so that it doesn't run it again -- 
+		//the timeout exists because of the amount of time it seems to take for php to finish writing the session data from the previous page request
+		setTimeout("$.get(Drupal.settings.basePath + 'socialize-ajax/notify-login')",1000);
+		Drupal.settings.gigya.notify_login_params.callback = Drupal.gigya.notifyLogin_callback;
+		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	1 Feb 2010 08:47:03 -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.14 2009/09/30 14:39:52 japerry 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-beta11 minor version:1');
 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');
@@ -63,6 +64,9 @@
 define('GIGYA_DEFAULT_SHARE_SUBJECT', 'A site recommendation for you');
 define('GIGYA_DEFAULT_SHARE_MESSAGE', 'I wanted to recommend this site <br/>to you. I enjoy it and think you will like it.');
 define('GIGYA_DEFAULT_SHARE_LINK_TITLE', 'Share with friends');
+define('GIGYA_DEFAULT_SHARE_UI_LINK_TITLE', 'Share UI title');
+define('GIGYA_DEFAULT_SHARE_UI_SUBJECT', 'Share UI: A site recommendation for you');
+define('GIGYA_DEFAULT_SHARE_UI_MESSAGE', 'Share UI: I wanted to recommend this site <br/>to you. I enjoy it and think you will like it.');
 define('GIGYA_DEFAULT_LOGINUI_FBCONNECT', FALSE);
 /**
  *
@@ -82,7 +86,7 @@
     '#description' => t('Keys needed for connecting to the Gigya Socialize service.'),
     '#collapsible' => TRUE,
     '#collapsed' => TRUE,
-    '#weight' => -4,
+    '#weight' => -400,
   );
   $form['keys']['gigya_APIKey'] = array(
     '#type' => 'textfield',
@@ -90,7 +94,7 @@
     '#description' => t('Specify the gigya API key for this domain'),
     '#default_value' => variable_get('gigya_APIKey', ''),
     '#required' => TRUE,
-    '#weight' => -10,
+    '#weight' => -300,
   );
   $form['keys']['gigya_SecretKey'] = array(
     '#type' => 'textfield',
@@ -98,7 +102,7 @@
     '#description' => t('Specify the gigya Secret (Base64 encoded) key for this domain'),
     '#default_value' => variable_get('gigya_SecretKey', ''),
     '#required' => TRUE,
-    '#weight' => -9,
+    '#weight' => -200,
   );
   
   $form['gigya_selected_networks'] = array(
@@ -106,11 +110,12 @@
     '#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,
+    '#weight' => -100,
   );
 
+  /*
   $form['posting'] = array(
     '#type' => 'fieldset',
     '#title' => t('Socialize status update options'),
@@ -136,19 +141,52 @@
     '#description' => t('The given text will be posted to your social networks. You can use !url, !url-alias, !tinyurl, !title, and !user as replacement text.'),
     '#default_value' => variable_get('gigya_default_format', 'New post: !title !tinyurl'),
   );
+  
+  */
+  
+  $form['share_ui'] = array(
+    '#type' => 'fieldset',
+    '#title' => t('Share UI settings'),
+    '#description' => t('Set which node types will have the Share UI functionality enabled.'),
+    '#collapsible' => TRUE,
+    '#collapsed' => TRUE,
+    '#weight' => -10,
+  );
+
+  
+  $form['share_ui']['gigya_share_ui_link_title'] = array(
+    '#type' => 'textfield',
+    '#title' => t('Link text for "Share UI"'),
+    '#default_value' => variable_get('gigya_share_ui_link_title', GIGYA_DEFAULT_SHARE_UI_LINK_TITLE),
+  );  
+  
+  $form['share_ui']['gigya_share_ui_types'] = array(
+    '#type' => 'checkboxes',
+    '#title' => t('Node types for "Share UI"'),
+    '#options' => node_get_types('names'),
+    '#default_value' => variable_get('gigya_share_types', array('story' => 'story', 'blog' => 'blog')),
+  );
+  $form['share_ui']['gigya_share_ui_message'] = array(
+    '#type' => 'textarea',
+    '#title' => t('Suggested message for "Share UI"'),
+    '#default_value' => variable_get('gigya_share_ui_message', GIGYA_DEFAULT_SHARE_UI_MESSAGE),
+  );
+  /*  
   $form['sharing'] = array(
     '#type' => 'fieldset',
     '#title' => t('Share with a friend settings'),
     '#description' => t('Set which node types will have the Share with Friends functionality enabled.'),
     '#collapsible' => TRUE,
     '#collapsed' => TRUE,
-    '#weight' => -2,
+    '#weight' => -5,
   );
+  
   $form['sharing']['gigya_share_link_title'] = array(
     '#type' => 'textfield',
     '#title' => t('Link text for "share with friends"'),
     '#default_value' => variable_get('gigya_share_link_title', GIGYA_DEFAULT_SHARE_LINK_TITLE),
   );
+
   $form['sharing']['gigya_share_types'] = array(
     '#type' => 'checkboxes',
     '#title' => t('Node types for "Share with a friend"'),
@@ -160,6 +198,8 @@
     '#title' => t('Suggested message for "Share with a friend"'),
     '#default_value' => variable_get('gigya_share_message', GIGYA_DEFAULT_SHARE_MESSAGE),
   );
+  
+   */
   $form['login_uiconfig'] = array(
     '#type' => 'fieldset',
     '#title' => t('Parameters for Login UIConfig'),
@@ -336,8 +376,7 @@
     '#title' => t('Friends UI URL title'),
     '#default_value' => variable_get('gigya_friends_uiconfig_link_title', GIGYA_DEFAULT_FRIENDSUI_LINKTITLE),
     '#description' => t('Leave blank to echo the raw url, otherwise put some text like "view site".'),
-  );  
-  
+  );
   $form['friends_uiconfig']['gigya_friends_uiconfig_width'] = array(
     '#type' => 'textfield',
     '#title' => t('UI Box Width'),
@@ -551,54 +590,89 @@
       '#description' => t('Checking this option allows users to connect their user picture to their drupal profile picture'),
     );
   }
-  
+  // Start filling the mapping part
+  $fields = array();
   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(
     '#type' => 'fieldset',
     '#title' => t('Facebook fields Population'),   	
     '#collapsible' => TRUE,
     '#collapsed' => FALSE    
   );  
-  
-       
   $form['Facebook fields Population'][GIGYA_ENABLE_FACEBOOK_POPULATION] = array(
   	'#type' => 'checkbox', 	 
    	'#title' => t('Enable Facebook fields population'),
@@ -613,7 +687,6 @@
     '#collapsible' => TRUE,
     '#collapsed' => TRUE    
   );
-  
   $form[versionInfo]['gigya_socialize_module_version'] = array(
   	'#type' => 'item', 	  	
     '#value' => t('Current module version: ' . GIGYA_MODULE_VERSION),       
@@ -636,4 +709,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
Index: gigya.info
===================================================================
RCS file: /cvs/drupal/contributions/modules/gigya/Attic/gigya.info,v
retrieving revision 1.1.2.4
diff -u -r1.1.2.4 gigya.info
--- gigya.info	26 Nov 2009 15:09:22 -0000	1.1.2.4
+++ gigya.info	1 Feb 2010 08:47:03 -0000
@@ -1,9 +1,5 @@
 ; $Id
 name = Gigya Socialize
 description = "Allows sites to utilize the Gigya Socialize API for authentication and social network updates."
-dependencies[] = popups
 core = 6.x
 php = 5.2
-
-
-

