/*
    SSATB Javascript Utility Functions 
    c. 2009 AECOM Environment
*/
// requires dojo core (dojo.xd.js)
var SSATB = SSATB || {};
SSATB.Profile = function(){
  // Load custom content handler for dojo.xhr
  dojo.mixin(dojo._contentHandlers, {
    "json-domino-auth": function(xhr){
      //console.debug(xhr);
      var getAuthenticationStatus = function( xhr ) {
        //console.debug( document.cookie); 
        var hasToken = ( document.cookie.match(/DomAuthSessId|LtpaToken/) );
        //console.debug( xhr.getAllResponseHeaders() );
        var response = xhr.getResponseHeader("x-Domino-Auth-Message");// domcfg/DCLF
        var result = {  code : "",
                        reasonType : (response ? response.split(";")[0] : ""), 
                        message : (response ? response.split(";")[1] : "") };
        //console.debug( result );
        result.code = (!hasToken) ? "unauthenticated" : ( ( result.reasonType == "" ) ? "authorized" : "unauthorized" );
        return result;
      };
  
      var auth = getAuthenticationStatus(xhr);
      if ( auth.code != "authorized" )  {
        var error = new Error;
        error.message = auth.message;
        error.authResult = auth;
        error.status = 401 ; // http not authorized
        throw error;
      }
      // all good, return normal json
      return dojo._contentHandlers.json(xhr);
    },
    "json-in-body" : function( xhr ) {
      dojo.jow = xhr.responseText;
       //console.debug("json-in-body");
       var extractBody = function( html ){
          return html.replace(/\n/g,"").replace(/(?:.*)(?:<body.*>)(.*)(?:<\/body>)(?:.*)/i,'$1');
       };
       return dojo.fromJson( extractBody( xhr.responseText ));  
    }
  });
  var deleteCookie = function( name ) {
    document.cookie = name + "=;path=/;expires=Thu, 01-Jan-1970 00:00:01 GMT"
  };
  return {
    loadJsonFromUrl : function(url, load , error ) {
      //console.debug("loadJsonFromUrl ");
      var argsLoad  = { url: url , 
      									timeout:6000,
                        load : load , error: error , handleAs: "json-domino-auth" };
      var dominoDeferred = new dojo.xhrGet(argsLoad);
      return dominoDeferred;
    },
    loginAndLoadJsonFromUrl : function(id, pwd, url, load , error ) {
      //console.debug("loginAndLoadJsonFromUrl ");
      var argsLogin = { url: url.split("?")[0]+"?Login",
      									timeout:6000,
                        postData: dojo.objectToQuery( {UserName:id , Password:pwd , redirectTo: url } ),
                        load : load , error: error , handleAs: "json-domino-auth" };
      var dominoDeferred = new dojo.xhrPost(argsLogin);
      return dominoDeferred;
    },
    logout : function() {
      //console.debug( "logout");
      deleteCookie("DomAuthSessId");
      deleteCookie("LtpaToken");
    },
    save: function( url , objMustMatchForm , ok, error) {
      var argsSave = {   url: url ,
      									timeout:10000,
                        postData: dojo.objectToQuery( dojo.mixin( { __click:0 } , objMustMatchForm ) ),
                        handleAs : "json-in-body",
                        load : ok , error: error };
      //console.debug( argsSave );
      var deferred = new dojo.xhrPost(argsSave);
      return deferred;
    }
  }
}();


/* SSATB Profile management for FMI *************** */

var FM = {};

FM.Profile = function(){
  var baseUrl = "/profiles.nsf";
  var profileUrl = "/CurrentProfile?ReadForm";
  var saveUrl = function( username ) {
    return "/SaveProfile/" + username.replace(/\//g, "-")+"?editdocument"
  };
  var currentProfile = {};
  
  var processValidData = function( response ) {
    //console.debug( "processvalidData" );
    //console.debug( response );
    FM.Profile.currentProfile = response.profile || {} ;
    // Your Code Here - probably calls Flash?
  }
  var processLoadComplete = function(response){
  log("processLoadComplete()");
	FM.Profile.currentProfile = response.profile || {} ;//commented for local testing
	cbLoadComplete(FM.Profile.currentProfile);//commented for local testing
	//cbLoadComplete({ success:true,profile:{UserName:"012345678/012345678/Folio",SavedSearches:["","Sun Jun 21 2009 23:41:06 GMT-0400 (Eastern Daylight Time)","Sun Jun 21 2009 23:41:46 GMT-0400 (Eastern Daylight Time)","Sun Jun 21 2009 23:41:50 GMT-0400 (Eastern Daylight Time)","Mon Jun 22 2009 13:56:13 GMT-0400 (Eastern Daylight Time)","Tue Jun 30 2009 14:22:49 GMT-0400 (Eastern Daylight Time)","Thu Jul 09 2009 16:03:51 GMT-0400 (Eastern Daylight Time)"]}});//temporary. for testing
  }
  var processLoginAndLoadComplete = function(response){
  	log("processLoginAndLoadComplete()")
	FM.Profile.currentProfile = response.profile || {} ;//commented for local testing
	cbLoginAndLoadComplete(FM.Profile.currentProfile);//commented for local testing
	//cbLoginAndLoadComplete({ success:true,profile:{UserName:"012345678/012345678/Folio",SavedSearches:["","Sun Jun 21 2009 23:41:06 GMT-0400 (Eastern Daylight Time)","Sun Jun 21 2009 23:41:46 GMT-0400 (Eastern Daylight Time)","Sun Jun 21 2009 23:41:50 GMT-0400 (Eastern Daylight Time)","Mon Jun 22 2009 13:56:13 GMT-0400 (Eastern Daylight Time)","Tue Jun 30 2009 14:22:49 GMT-0400 (Eastern Daylight Time)","Thu Jul 09 2009 16:03:51 GMT-0400 (Eastern Daylight Time)"]}});//temporary. for testing
  }
  var processHandleSave = function(response){
  	log("processHandleSave");
	FM.Profile.currentProfile = response.profile || {} ; //commented for local testing
	cbSaveComplete({success:true});//temporary. for testing
  }
  
  var handleXhrError = function( error , ioArgs ) {
    //console.debug("handleXhrError");
    //console.debug(error);
    //console.debug(ioArgs);
    if( error.status == 401 ) { console.debug ("not authorized"); } else { console.debug( error.message ); }
    // Your Code Here - probably calls Flash?
  };

  var handleLoadXhrError = function( error , ioArgs ) {
    if( error.status == 401 ) { console.debug ("not authorized"); } else { console.debug( error.message ); }
    cbLoadFail(error);//callback to flash
  };
  var handleLoginAndLoadXhrError = function( error , ioArgs ) {
    if( error.status == 401 ) { console.debug ("not authorized"); } else { console.debug( error.message ); }
   cbLoginAndLoadFail(error);//callback to flash
  };
  var handleSaveXhrError = function( error , ioArgs ) {
    if( error.status == 401 ) { console.debug ("not authorized"); } else { console.debug( error.message ); }
    cbSaveFail(error);//callback to flash
  };
    
  return {
    currentProfile : currentProfile,
    setBaseUrl : function(url) { 
      baseUrl = url ;
    },
    load : function(){ 
      SSATB.Profile.loadJsonFromUrl( baseUrl+profileUrl , processLoadComplete , handleLoadXhrError);
    },
    loginAndLoad: function( id , pwd ) {
      SSATB.Profile.loginAndLoadJsonFromUrl( id , pwd , baseUrl+profileUrl , processLoginAndLoadComplete , handleLoginAndLoadXhrError);
    },
    save : function(profileUpdate){
    	this.currentProfile = dojo.mixin(this.currentProfile, profileUpdate);
			SSATB.Profile.save( baseUrl + saveUrl( this.currentProfile.UserName ) , this.currentProfile , processHandleSave , handleSaveXhrError );
    }
  }
}();

//wrappers for Flash to call
function load(){ FM.Profile.load(); }
function loginAndLoad(id,pwd){ FM.Profile.loginAndLoad(id,pwd); }
function save(o){ 
	if(window.console)console.log("save called with:",o);
	FM.Profile.save(o); 
}


