
/*
  support the Gigya API for Handshakes
  James Tolley, james dot tolley at gmail
*/

var DEBUG = false;
var regdlg;
function send_request(url) {
  var oXmlhttp = zXmlHttp.createRequest();
  oXmlhttp.open("GET", url, false);
  oXmlhttp.send(null);

  if (DEBUG) {
    alert("sending Ajax request:\n\n" + url);
  }

  var response = oXmlhttp.responseText;

  if (DEBUG) {
    alert("Ajax response:\n\n" + response);
  }

  return response;
}

function onLoad() {
  if(typeof conf != "undefined")
  {
   
  // if we're logged out (we don't have a mem_id cookie), then make sure gigya knows it.
  if (!/mem_id=/.test(document.cookie)) {
    if (DEBUG) {
      alert("you are not logged in");
    }
    gigya.services.socialize.isLoggedIn(conf, {
      callback: function(response) {
        window.ili_response = response;
        if (DEBUG) {
          alert("gigya thinks you are logged in: " + response.loggedIn);
        }

        if (response.loggedIn) {
          if (DEBUG) {
            alert("logging you out");
          }

          gigya.services.socialize.logout(conf, {
            callback: function(logout_event) {
              window.logout_event = logout_event;
              if (DEBUG) {
                alert("you are now logged out");
              }
            }
          });
        }
      }
    });

    

  }

  // register gigya's onLogin event
  gigya.services.socialize.addEventHandlers(conf, { context: { str: 'congrats on your' }, onLogin: onGigyaLogin });
  }
}

// onLogin Event handler
function onGigyaLogin(event_object) {
  // store globally for debugging
window.login_event = event_object;

  if (DEBUG) {
    alert("in the gigya login callback");
  }

  if (!event_object.UID) {
    alert("The gigya login seems not to have worked.\n\nPlease login through normal channels.");
    return;
  }

  var uid = encodeURIComponent(event_object.UID);
  var ts  = encodeURIComponent(event_object.timestamp);
  var sig = encodeURIComponent(event_object.signature);
  var request_is_valid = send_request('ajax/gigya_verify_signature.php?timestamp=' + ts + '&UID=' + uid + '&signature=' + sig);
  if (request_is_valid == '1' || request_is_valid == '2') {
    if (DEBUG) {
      alert("you have logged in with gigya");
    }

    // user is returning
    if (request_is_valid == '1' && event_object.user.isSiteUID) {
      if (DEBUG) {
        alert("your userID is from this site");
      }

      // log the user in
      $.ajax({
        type: 'post',
        url: 'ajax/gigya_login.php',
        data: {
          UID: event_object.UID,
          signature: event_object.signature,
          timestamp: event_object.timestamp
        },
        dataType: 'text',
        error: function() { alert("There was an error logging you in.\n\nPlease try again later."); },
        success: function(user_is_logged_in) {
          if (DEBUG) {
            alert("in the login callback: '" + user_is_logged_in + "'");
          }
window.uili = user_is_logged_in;
          if (user_is_logged_in) {
            if (DEBUG) {
              alert("user_is_logged_in is true");
            }
            else {
              location.href = 'index.php?page=my_handshakes';
            }
          }
          else {
            window.login_error = user_is_logged_in;
            alert("There was an error logging you in.");
          }
        }
      });
    }
    // user is new
    else {
      if (DEBUG) {
        alert("your userID is not from this site");
      }

      // 1) create the user
      var user          = event_object.user;

      var post_args     = {};
      post_args.gender  = user.gender;
      post_args.bD      = user.birthDay;
      post_args.bM      = user.birthMonth;
      post_args.bY      = user.birthYear;
      post_args.img     = user.thumbnailURL;

      if (user.firstName != '') {
        post_args.fName = user.firstName;
        post_args.lName = user.lastName;
      }
      else {
        post_args.fName = user.nickname;
        post_args.lName = '';
      }

      post_args.UID       = event_object.UID;
      post_args.signature = event_object.signature;
      post_args.timestamp = event_object.timestamp;

      window.registration_params = post_args;

      show_form();
    }
  }
  else {
    alert("Sorry, the login provided does't seem valid.");
  }
}

// Display a status message according to the response.
function linkAccounts_callback(response) {
  window.la_response = response;
  if (DEBUG) {
    alert('linkAccounts response: ' + response.status + ', ' + response.statusMessage + ', ' + response.context.UID);
  }

  if (response.status == 'OK') {
    location.href = "index.php?page=my_handshakes";
  }
  else {
    //$('#register-dialog').dialog('close');
    alert("There has been an error.\n\nPlease try back again later.");
  }
}

function show_form() {
  if (DEBUG) {
    alert("showing form");
  }
  regdlg = window.open('/network/jscript/register-dialog.html', 'regdlg', 'width=480,height=480,scrollbars=yes,status=yes,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no');
  //$("#register-dialog").dialog();
  
}

function set_registration_fields() {
    var doc = document;
    if(typeof(regdlg) != "undefined") doc = regdlg.document;
  if ($('#registration-password',doc).val() != $('#registration-password2', doc).val()) {
    alert("Please make sure the passwords match and try again.");
    return;
  }

  if (DEBUG) {
    alert("setting registration fields. Username: " + $('#registration-username',doc).val() + " Pass: " + $('#registration-password',doc).val() + "Email: " + $('#registration-email',doc).val());
  }

  var winobj = window;
  if(typeof(window.registration_params) == 'undefined') winobj = window.opener;
  winobj.registration_params.username  = $('#registration-username',doc).val();
  winobj.registration_params.password  = $('#registration-password',doc).val();
  winobj.registration_params.email     = $('#registration-email',doc).val();

  if (DEBUG) {
    alert("calling register_user()");
  }

  register_user();
}

function register_user() {
var winobj = window;
  if(typeof(window.registration_params) == 'undefined') winobj = window.opener;

winobj.post_args = winobj.registration_params;
  $.ajax({
    type:     'post',
    url:      '/network/ajax/gigya_register.php',
    data:     winobj.post_args,
    cache:    false,
    dataType: 'json',
    error:    function(xhr, status, thrown) {
        var winobj = window;
        if(typeof(window.registration_params) == 'undefined') winobj = window.opener;
        winobj.error_response = {
        xhr: xhr,
        status: status,
        thrown: thrown
      };
      alert("There was an unknown error.\n\nPlease try again later.");
    },
    success:  function(recdata,b,c) {
      var new_user_id;
      new_user_id = recdata.user_id;
      if (DEBUG) {
        alert('the new user is created: ' + new_user_id);
      }

      // 2) link this user account to gigya's account
      var dateStr = recdata.timestamp;

      var url = "/network/ajax/gigya_verify_signature.php?UID=" + new_user_id + "&timestamp=" + dateStr;
      var signature = send_request(url);

      var params = {
        callback:   linkAccounts_callback,
        siteUID:    new_user_id,
        timestamp:  dateStr,
        signature:  signature,
        context:    {
          UID: new_user_id
        }
      };
      winobj.link_params = params;

      if (DEBUG) {
        alert('signature: "' + signature + '"');
      }

      gigya.services.socialize.linkAccounts(conf, params);
    }
  });
}

function unlink_accounts() {
  if (DEBUG) {
    alert("calling unlinkAccounts()");
  }

  try {
    gigya.services.socialize.unlinkAccounts(conf, {
      callback: function(response) {
window.unlink_response = response;

        if (DEBUG) {
          alert("in the unlinkAccounts callback (" + response.status + ")");
        }

        if (response.status == 'OK') {
          alert('The accounts have been unlinked.');
        }
        else {
          alert("There was an error unlinking the accounts.");
        }
      }
    });
  }
  catch (e) {
window.unlink_error = e;
    if (DEBUG) {
      alert("there was an error calling unlinkAccounts: " + e.toString());
    }
  }
}

