//upload.xul, download.xul, and browser.xul(Overlay)
var mAuthToken = null;

var gUploadService=
{
  _channel:null,
  _callback:null,
  _data:"",
  _scheme:"",
  _errorData:"",

  start:function(aStr,aURI,aType,aCallback)
  {


	aType = "application/x-www-form-urlencoded";
	
	var mGoogleUser = "tommut@gmail.com";
	var mGooglePass = "FOO";
	var source = "rf";
	
	aStr =  "Email=" + encodeURIComponent(mGoogleUser) +
                                  "&Passwd=" + encodeURIComponent(mGooglePass) +
                                  "&accountType=HOSTED_OR_GOOGLE" +
                                  "&source=" + encodeURIComponent(source) +
                                  "&service=cl";
								  
	  aStr =  "Email=" + mGoogleUser +
                                  "&Passwd=" + encodeURIComponent(mGooglePass) +
                                  "&accountType=HOSTED_OR_GOOGLE" +
                                  "&source=" + encodeURIComponent(source) +
                                  "&service=cl";
	
dump( "UPLOADING: " + aStr + " -- -" + aType + " -- " + aURI + "\n" );
    if( !aStr || !aURI)
      return false;
    this._callback=aCallback;
    this._scheme=aURI.scheme;
	
	
	
	
	
	
	
	
	
	
	        // create the channel
            var ioService = Components.classes["@mozilla.org/network/io-service;1"].
                            getService(Components.interfaces.nsIIOService);

            var uristring = "https://www.google.com/accounts/ClientLogin";
//            if (this.mQueryParameters.length > 0) {
//                uristring += "?" + this.mQueryParameters.join("&");
//            }
            var uri = ioService.newURI(uristring, null, null);
            var aChannel = ioService.newChannelFromURI(uri);

            //this.prepareChannel(channel); 
			
			
			
			      // No caching
        aChannel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;

        // Set upload Data
       // if (this.mUploadData) {
	   var mUploadData = "Email=tommut@gmail.com" +
                                  "&Passwd=FOO"+
                                  "&accountType=HOSTED_OR_GOOGLE" +
                                  "&source=reminderfox"+
                                  "&service=cl";
		var mUploadContent =  "application/x-www-form-urlencoded";
		 var method = "POST";
            var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
                            createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
            converter.charset = "UTF-8";
dump( "GOIN ON 1\n" );
            var stream = converter.convertToInputStream(mUploadData);
            aChannel = aChannel.QueryInterface(Components.interfaces.nsIUploadChannel);
            aChannel.setUploadStream(stream, mUploadContent, -1);
     //   }

dump( "GOIN ON 2\n" );
        aChannel  = aChannel.QueryInterface(Components.interfaces.nsIHttpChannel);

//        // Depending on the preference, we will use X-HTTP-Method-Override to
//        // get around some proxies. This will default to true.
//        if (getPrefSafe("calendar.google.useHTTPMethodOverride", true) &&
//            (this.method == "PUT" || this.method == "DELETE")) {
//
//            aChannel.requestMethod = "POST";
//            aChannel.setRequestHeader("X-HTTP-Method-Override",
//                                      this.method,
//                                      false);
//            if (this.method == "DELETE") {
//                // DELETE has no body, set an empty one so that Google accepts
//                // the request.
//                aChannel.setRequestHeader("Content-Type",
//                                          "application/atom+xml; charset=UTF-8",
//                                          false);
//                aChannel.setRequestHeader("Content-Length", 0, false);
//            }
//        } else {
            aChannel.requestMethod = method;
        //}
			
			
			
			dump( "GOIN ON 3\n" );
			
			

            aChannel = aChannel.QueryInterface(Components.interfaces.nsIHttpChannel);
            aChannel.redirectionLimit = 3;
dump( "SEDING\n" );



/** this opens stream loader */

     this.streamLoader=Components.classes["@mozilla.org/network/stream-loader;1"]
                    .createInstance(Components.interfaces.nsIStreamLoader);
                 
        aChannel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
        
        	// Required to be trunk and branch compatible.
            	// FF3
                this.streamLoader.init(this );
			    aChannel.asyncOpen( this.streamLoader, null );



/** this opens the channell - the other opens on stream loader */
	  //aChannel.asyncOpen(this, null);
	  
	  
	  
	  
   //   this._callback(reminderFox_getBundle().getString("rf.net.sending.label"),status);
	  dump( "SENT?\n" );
     // this._data=chunk;
	
	
	
	if ( true ) 
	return true;
	
	
	
	
	
	
	
	
	
	
	
	
//	
//	
//    const ioService  = Components.classes["@mozilla.org/network/io-service;1"]
//                      .getService(Components.interfaces.nsIIOService);
//    const stringStream=Components.classes["@mozilla.org/io/string-input-stream;1"]
//                      .createInstance(Components.interfaces.nsIStringInputStream);
//    var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
//                              .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
//    converter.charset =  "UTF-8";
//    this._channel = ioService.newChannelFromURI( aURI )
//                      .QueryInterface(Components.interfaces.nsIUploadChannel);
//					  
//					  
// this._channel  = this._channel.QueryInterface(Components.interfaces.nsIHttpChannel);					  
//					  
//	this._channel.requestMethod = "POST";
//	dump( "SET TO POST\n" ); 			  
//					  
//					  
//    // const stringStream = converter.convertToInputStream(aStr);  // Firefox 1.5+ only	
//
//   var chunk = null;
//   try {
//           chunk = converter.ConvertFromUnicode(aStr);
//   } catch( e ) {
//          chunk = aStr;
//    }
//    try{
//      stringStream.setData(chunk, chunk.length);
//      this._channel.setUploadStream(stringStream,aType,-1);
//      this._channel.asyncOpen(this, null);
//      this._callback(reminderFox_getBundle().getString("rf.net.sending.label"),status);
//      this._data=chunk;
//
//    //  stringStream.close();  // don't call close() - https://bugzilla.mozilla.org/show_bug.cgi?id=423291
//      return true;
//    }catch(e){window.alert("__network__\n\n"+e);}
    return false;
  },


   onResult: function (aOperation, aData) {
                    dump( "ON RESULT...\n" );
                }
				,
  cancel:function()
  {
    if(this._channel)
      this._channel.cancel(0x804b0002);
  },

  onDataAvailable: function (channel, ctxt, input, sourceOffset, count){
    const sis=Components.classes["@mozilla.org/scriptableinputstream;1"]
                      .createInstance(Components.interfaces.nsIScriptableInputStream);

    sis.init(input);
    this._errorData +=sis.read(count);
	
	dump( "DATA IS AVAIL: " + this._errorData + "\n" );
	
  },
  onStartRequest: function (channel, ctxt){  },
  
  
  
     /**
     * @see nsIStreamLoaderObserver
     */
    onStreamComplete: function (aLoader,
                                                    aContext,
                                                    aStatus,
                                                    aResultLength,
                                                    aResult) {

dump( "STREAM COMPLETE!\n" );
        if (!aResult || !Components.isSuccessCode(aStatus)) {
            this.fail(aStatus, aResult);
            return;
        }

        var httpChannel = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel);
		
		
		      this.length=aResultLength;
      if(typeof(aResult)=="string") {
        this.data=aResult;
		dump( "THIS STRING: " + this.data + "\n" );
		}
      else
      {
        while(aResult.length > (256*192) )
        {
          this.data += String.fromCharCode.apply(this,aResult.splice(0,256*192));
        }
        this.data += String.fromCharCode.apply(this,aResult);
		
		
		
		            var start = this.data.indexOf("Auth=");
            if (start == -1) {
//                // The Auth token could not be extracted
//                this.mLoggingIn = false;
//                this.invalidate();
//
//                // Retry login
//                this.loginAndContinue(aOperation.calendar);
            } else {
             	mAuthToken = this.data.substring(start + 5, this.data.length - 1);
dump("mAuthToken:" + mAuthToken + "\n" );
//                this.mLoggingIn = false;
//
//                if (this.persist) {
//                    try {
//                        passwordManagerSave(this.mGoogleUser,
//                                            this.mGooglePass);
//                    } catch (e) {
//                        // This error is non-fatal, but would constrict
//                        // functionality
//                        LOG("Error adding password to manager");
//                    }
//                }
//
//                // Process Items that were requested while logging in
//                var request;
//                // Extra parentheses to avoid js strict warning.
//                while ((request = this.mItemQueue.shift())) {
//                    LOG("Processing Queue Item: " + request.uri);
//                    request.commit(this);
//                }
            }
		
		
		dump( "OTHER DATA: " + this.data +"\n" );
      }

//        // Convert the stream, falling back to utf-8 in case its not given.
//        let result = cal.convertByteArray(aResult, aResultLength, httpChannel.contentCharset);
//        if (result === null) {
//            this.fail(Components.results.NS_ERROR_FAILURE,
//                      "Could not convert bytestream to Unicode: " + e);
//            return;
//        }

        // Calculate Google Clock Skew
        var serverDate = new Date(httpChannel.getResponseHeader("Date"));
       // var curDate = new Date();
dump( "SERVERDATE: " + serverDate + "\n" );
        // The utility function getCorrectedDate in calGoogleUtils.js recieves
        // its clock skew seconds from here. The clock skew is updated on each
        // request and is therefore quite accurate.
 //       getCorrectedDate.mClockSkew = curDate.getTime() - serverDate.getTime();

        // Remember when this request happened
    //    this.requestDate = jsDateToDateTime(serverDate);
		
		dump( "MY STATUS: " + httpChannel.responseStatus + "\n" );

        // Handle all (documented) error codes
        switch (httpChannel.responseStatus) {
            case 200: /* No error. */
            case 201: /* Creation of a resource was successful. */
                // Everything worked out, we are done
				dump( "SUCCESS!\n" );
              //  this.succeed(result);
                break;

            case 401: /* Authorization required. */
            case 403: /* Unsupported standard parameter, or authentication or
                         Authorization failed. */
                LOG("Login failed for " + this.mSession.userName +
                    " HTTP Status " + httpChannel.responseStatus );

                // login failed. auth token must be invalid, password too

                if (this.type == this.MODIFY ||
                    this.type == this.DELETE ||
                    this.type == this.ADD) {
                    // Encountering this error on a write request means the
                    // calendar is readonly
                    this.fail(Components.interfaces.calIErrors.CAL_IS_READONLY, result);
                } else if (!this.reauthenticate) {
                    // If no reauth was requested, then don't invalidate the
                    // whole session and just bail out
                    this.fail(kGOOGLE_LOGIN_FAILED, result);
                } else if (this.type == this.LOGIN) {
                    // If this was a login request itself, then fail it.
                    // That will take care of logging in again
                    this.mSession.invalidate();
                    this.fail(kGOOGLE_LOGIN_FAILED, result);
                } else {
                    // Retry the request. Invalidating the session will trigger
                    // a new login dialog.
                    this.mSession.invalidate();
                    this.mSession.asyncItemRequest(this);
                }

                break;
            case 409: /* Specified version number doesn't match resource's
                         latest version number. */

                // 409 Conflict. The client should get a newer version of the
                // event
                // and edit that one.

                // TODO Enhancement tracked in bug 362645
                // Fall through, if 409 is not handled then the event is not
                // modified/deleted, which is definitly an error.
            default:
                // The following codes are caught here:
                //  400 BAD REQUEST: Invalid request URI or header, or
                //                   unsupported nonstandard parameter.
                //  404 NOT FOUND: Resource (such as a feed or entry) not found.
                //  500 INTERNAL SERVER ERROR: Internal error. This is the
                //                             default code that is used for
                //                             all unrecognized errors.
                //

                // Something else went wrong
                var error = "A request Error Occurred. Status Code: " +
                            httpChannel.responseStatus + " " +
                            httpChannel.responseStatusText + " Body: " +
                            result;

                this.fail(Components.results.NS_ERROR_FAILURE, error);
                break;
        }
		
		 if(this._callback) {
      this._callback(reminderFox_getBundle().getString("rf.net.done"),aStatus);  
      }
    }, 
  
  
  
  
  
  
  onStopRequest: function (channel, ctxt, status)  {
    if(this._scheme != "ftp"){
      var res=0;
      try{
        res = channel.QueryInterface(Components.interfaces.nsIHttpChannel)
                       .responseStatus;
					   
	dump( "RESponse: " + res + "\n" );					   
					   
      }catch(e){}
      if(res==200||res==201 || res==204)
        status=0;
      /*
        200:OK
        201:Created
        204:No Content
        This is an uploading channel, no need to "GET" the file contents.
      */
      if(this._errorData)
        status=res;
      if(this._errorData && res==200)
        alert(this._errorData);
    }
    
    if(this._callback) {
      this._callback(reminderFox_getBundle().getString("rf.net.done"),status);  
      }
  }
};

var gDownloadService=
{
  _channel:null,
  streamLoader:null,
  data:null,
  length:null,

  _callback:null,
  _startTime:0,
  _endTime:0,

  start:function(aURI,aCallback)
  {
    if( !aURI )
      return false;

    this._callback=aCallback;

    try{
      var ioService  = Components.classes["@mozilla.org/network/io-service;1"]
                      .getService(Components.interfaces.nsIIOService);
      this.streamLoader=Components.classes["@mozilla.org/network/stream-loader;1"]
                    .createInstance(Components.interfaces.nsIStreamLoader);
                 
      this._channel = ioService.newChannelFromURI( aURI );
      if(aURI.scheme=="http" || aURI.scheme=="https")
        this._channel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
        
        	// Required to be trunk and branch compatible.
            if (Components.interfaces.nsIStreamLoader.number ==
                "{31d37360-8e5a-11d3-93ad-00104ba0fd40}") {
            	//  FF2, seamonkey, etc
                this.streamLoader.init(this._channel, this , null);
            } else if (Components.interfaces.nsIStreamLoader.number ==
                      "{8ea7e890-8211-11d9-8bde-f66bad1e3f3a}") {
            	// FF3
                this.streamLoader.init(this );
			    this._channel.asyncOpen( this.streamLoader, null );
            }
      this._startTime=(new Date()).getTime();
    }catch(e){ alert(e); return false;}
    return true;
  },

  cancel:function()
  {
    if(this._channel)
      this._channel.cancel(0x804b0002);
  },
  
   onStreamComplete :function ( loader , ctxt , status , resultLength , result )
  {
    this.data="";
    this._endTime=(new Date()).getTime();
    if(status==0)
    {
      this.length=resultLength;
      if(typeof(result)=="string")
        this.data=result;
      else
      {
        while(result.length > (256*192) )
        {
          this.data += String.fromCharCode.apply(this,result.splice(0,256*192));
        }
        this.data += String.fromCharCode.apply(this,result);
      }
    }

    if(this._callback)
      this._callback(reminderFox_getBundle().getString("rf.net.done"),status);
  },

  get time(){
    return this._endTime-this._startTime;
  }
};


//upload.xul, download.xul, and browser.xul(Overlay)
var gNewEventUploadService=
{
  _channel:null,
  _callback:null,
  _data:"",
  _scheme:"",
  _errorData:"",

  start:function(aStr,aURI,aType,aCallback)
  {


	aType = "application/atom+xml";
	
	var mGoogleUser = "tommut@gmail.com";
	var mGooglePass = "FOO";
	var source = "rf";
	
	
	aStr = "<entry xmlns='http://www.w3.org/2005/Atom'\n" + 
	"xmlns:gCal='http://schemas.google.com/gCal/2005'\n" +
    "xmlns:gd='http://schemas.google.com/g/2005'>\n" + 
  "<category scheme='http://schemas.google.com/g/2005#kind'\n" + 
    "term='http://schemas.google.com/g/2005#event'></category>\n" + 
  "<title type='text'>Tennis with Beth</title>\n" + 
  "<content type='text'>Meet for a quick lesson.</content>\n" + 
  "<gd:transparency\n" + 
  "  value='http://schemas.google.com/g/2005#event.opaque'>\n" + 
  "</gd:transparency>\n" + 
  "<gd:eventStatus\n" + 
 "   value='http://schemas.google.com/g/2005#event.confirmed'>\n" + 
 " </gd:eventStatus>\n" + 
 "<gCal:uid value='eTOMuo7rrbo6a27p2ok1125ot5sl4@google.com'/>\n" +
 " <gd:extendedProperty name='X-ReminderFox-ListName' value='listname' /> \n" + 
 " <gd:where valueString='Rolling Lawn Courts'></gd:where>\n" + 
 " <gd:when startTime='2006-04-17T15:00:00.000Z'\n" + 
 "   endTime='2006-04-17T17:00:00.000Z'></gd:when>\n" + 
"</entry>\n";

	
dump( "********************\n\nUPLOADING new one : " + aStr + " -- -" + aType + " -- " + aURI + "\n" );
//    if( !aStr || !aURI)
//      return false;
    this._callback=aCallback;
 //   this._scheme=aURI.scheme;
	
	
	
	        // create the channel
            var ioService = Components.classes["@mozilla.org/network/io-service;1"].
                            getService(Components.interfaces.nsIIOService);

            var uristring = "https://www.google.com/calendar/feeds/default/private/full";
//            if (this.mQueryParameters.length > 0) {
//                uristring += "?" + this.mQueryParameters.join("&");
//            }
            var uri = ioService.newURI(uristring, null, null);
            var aChannel = ioService.newChannelFromURI(uri);

            //this.prepareChannel(channel); 
			
			
			
			      // No caching
        aChannel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;

        // Set upload Data
       // if (this.mUploadData) {
	   var mUploadData = aStr;
		var mUploadContent =  aType;
		 var method = "POST";
		 
		 
		 
            var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].
                            createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
            converter.charset = "UTF-8";
dump( "GOIN ON 1A\n" );
            var stream = converter.convertToInputStream(mUploadData);
            aChannel = aChannel.QueryInterface(Components.interfaces.nsIUploadChannel);
            aChannel.setUploadStream(stream, mUploadContent, -1);
     //   }

dump( "GOIN ON 2A\n" );
        aChannel  = aChannel.QueryInterface(Components.interfaces.nsIHttpChannel);

//        // Depending on the preference, we will use X-HTTP-Method-Override to
//        // get around some proxies. This will default to true.
//        if (getPrefSafe("calendar.google.useHTTPMethodOverride", true) &&
//            (this.method == "PUT" || this.method == "DELETE")) {
//
//            aChannel.requestMethod = "POST";
//            aChannel.setRequestHeader("X-HTTP-Method-Override",
//                                      this.method,
//                                      false);
//            if (this.method == "DELETE") {
//                // DELETE has no body, set an empty one so that Google accepts
//                // the request.
//                aChannel.setRequestHeader("Content-Type",
//                                          "application/atom+xml; charset=UTF-8",
//                                          false);
//                aChannel.setRequestHeader("Content-Length", 0, false);
//            }
//        } else {
            aChannel.requestMethod = method;
        //}
			
			// if (this.mSession.authToken) {
			
			dump( "REQUEST HEADER: " + "GoogleLogin auth="
                                      +  mAuthToken + "\n" );
            aChannel.setRequestHeader("Authorization",
                                      "GoogleLogin auth="
                                      +  mAuthToken,
                                      false);
			dump( "CHANNEL HEADER: " + 				aChannel.getRequestHeader("Authorization" ) + "\n" );	  
			
      //  }
			
			dump( "GOIN ON 3\n" );
			
			

            aChannel = aChannel.QueryInterface(Components.interfaces.nsIHttpChannel);
            aChannel.redirectionLimit = 3;
dump( "SENDING 222222222222222\n" );



/** this opens stream loader */

     this.streamLoader=Components.classes["@mozilla.org/network/stream-loader;1"]
                    .createInstance(Components.interfaces.nsIStreamLoader);
                 
        aChannel.loadFlags |= Components.interfaces.nsIRequest.LOAD_BYPASS_CACHE;
        
        	// Required to be trunk and branch compatible.
            	// FF3
                this.streamLoader.init(this );
			    aChannel.asyncOpen( this.streamLoader, aChannel );



/** this opens the channell - the other opens on stream loader */
	  //aChannel.asyncOpen(this, null);
	  
	  
	  
	  
  //    this._callback(reminderFox_getBundle().getString("rf.net.sending.label"),status);
	  dump( "SENT?\n" );
     // this._data=chunk;
	
	
	
	if ( true ) 
	return true;
	
	
	
	
	
	
	
	
	
	
	
	
//	
//	
//    const ioService  = Components.classes["@mozilla.org/network/io-service;1"]
//                      .getService(Components.interfaces.nsIIOService);
//    const stringStream=Components.classes["@mozilla.org/io/string-input-stream;1"]
//                      .createInstance(Components.interfaces.nsIStringInputStream);
//    var converter = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"]
//                              .createInstance(Components.interfaces.nsIScriptableUnicodeConverter);
//    converter.charset =  "UTF-8";
//    this._channel = ioService.newChannelFromURI( aURI )
//                      .QueryInterface(Components.interfaces.nsIUploadChannel);
//					  
//					  
// this._channel  = this._channel.QueryInterface(Components.interfaces.nsIHttpChannel);					  
//					  
//	this._channel.requestMethod = "POST";
//	dump( "SET TO POST\n" ); 			  
//					  
//					  
//    // const stringStream = converter.convertToInputStream(aStr);  // Firefox 1.5+ only	
//
//   var chunk = null;
//   try {
//           chunk = converter.ConvertFromUnicode(aStr);
//   } catch( e ) {
//          chunk = aStr;
//    }
//    try{
//      stringStream.setData(chunk, chunk.length);
//      this._channel.setUploadStream(stringStream,aType,-1);
//      this._channel.asyncOpen(this, null);
//      this._callback(reminderFox_getBundle().getString("rf.net.sending.label"),status);
//      this._data=chunk;
//
//    //  stringStream.close();  // don't call close() - https://bugzilla.mozilla.org/show_bug.cgi?id=423291
//      return true;
//    }catch(e){window.alert("__network__\n\n"+e);}
    return false;
  },


   onResult: function (aOperation, aData) {
                    dump( "ON RESULT...\n" );
                }
				,
  cancel:function()
  {
    if(this._channel)
      this._channel.cancel(0x804b0002);
  },

  onDataAvailable: function (channel, ctxt, input, sourceOffset, count){
    const sis=Components.classes["@mozilla.org/scriptableinputstream;1"]
                      .createInstance(Components.interfaces.nsIScriptableInputStream);

    sis.init(input);
    this._errorData +=sis.read(count);
	
	dump( "DATA IS AVAIL: " + this._errorData + "\n" );
	
  },
  onStartRequest: function (channel, ctxt){  },
  
  
  
     /**
     * @see nsIStreamLoaderObserver
     */
    onStreamComplete: function (aLoader,
                                                    aContext,
                                                    aStatus,
                                                    aResultLength,
                                                    aResult) {

dump( "STREAM COMPLETE!\n" );
        if (!aResult || !Components.isSuccessCode(aStatus)) {
            this.fail(aStatus, aResult);
            return;
        }

        var httpChannel = aLoader.request.QueryInterface(Components.interfaces.nsIHttpChannel);
		
		
		      this.length=aResultLength;
      if(typeof(aResult)=="string") {
        this.data=aResult;
		dump( "THIS STRING: " + this.data + "\n" );
		}
      else
      {
        while(aResult.length > (256*192) )
        {
          this.data += String.fromCharCode.apply(this,aResult.splice(0,256*192));
        }
        this.data += String.fromCharCode.apply(this,aResult);
		dump( "OTHER DATA: " + this.data +"\n" );
      }

//        // Convert the stream, falling back to utf-8 in case its not given.
//        let result = cal.convertByteArray(aResult, aResultLength, httpChannel.contentCharset);
//        if (result === null) {
//            this.fail(Components.results.NS_ERROR_FAILURE,
//                      "Could not convert bytestream to Unicode: " + e);
//            return;
//        }

        // Calculate Google Clock Skew
        var serverDate = new Date(httpChannel.getResponseHeader("Date"));
       // var curDate = new Date();
dump( "SERVERDATE: " + serverDate + "\n" );
        // The utility function getCorrectedDate in calGoogleUtils.js recieves
        // its clock skew seconds from here. The clock skew is updated on each
        // request and is therefore quite accurate.
 //       getCorrectedDate.mClockSkew = curDate.getTime() - serverDate.getTime();

        // Remember when this request happened
    //    this.requestDate = jsDateToDateTime(serverDate);
		
		dump( "MY STATUS: " + httpChannel.responseStatus + "\n" );

        // Handle all (documented) error codes
        switch (httpChannel.responseStatus) {
            case 200: /* No error. */
            case 201: /* Creation of a resource was successful. */
                // Everything worked out, we are done
				dump( "SUCCESS!\n" );
              //  this.succeed(result);
                break;

            case 401: /* Authorization required. */
            case 403: /* Unsupported standard parameter, or authentication or
                         Authorization failed. */
                LOG("Login failed for " + this.mSession.userName +
                    " HTTP Status " + httpChannel.responseStatus );

                // login failed. auth token must be invalid, password too

                if (this.type == this.MODIFY ||
                    this.type == this.DELETE ||
                    this.type == this.ADD) {
                    // Encountering this error on a write request means the
                    // calendar is readonly
                    this.fail(Components.interfaces.calIErrors.CAL_IS_READONLY, result);
                } else if (!this.reauthenticate) {
                    // If no reauth was requested, then don't invalidate the
                    // whole session and just bail out
                    this.fail(kGOOGLE_LOGIN_FAILED, result);
                } else if (this.type == this.LOGIN) {
                    // If this was a login request itself, then fail it.
                    // That will take care of logging in again
                    this.mSession.invalidate();
                    this.fail(kGOOGLE_LOGIN_FAILED, result);
                } else {
                    // Retry the request. Invalidating the session will trigger
                    // a new login dialog.
                    this.mSession.invalidate();
                    this.mSession.asyncItemRequest(this);
                }

                break;
            case 409: /* Specified version number doesn't match resource's
                         latest version number. */

                // 409 Conflict. The client should get a newer version of the
                // event
                // and edit that one.

                // TODO Enhancement tracked in bug 362645
                // Fall through, if 409 is not handled then the event is not
                // modified/deleted, which is definitly an error.
            default:
                // The following codes are caught here:
                //  400 BAD REQUEST: Invalid request URI or header, or
                //                   unsupported nonstandard parameter.
                //  404 NOT FOUND: Resource (such as a feed or entry) not found.
                //  500 INTERNAL SERVER ERROR: Internal error. This is the
                //                             default code that is used for
                //                             all unrecognized errors.
                //

                // Something else went wrong
                var error = "A request Error Occurred. Status Code: " +
                            httpChannel.responseStatus + " " +
                            httpChannel.responseStatusText + " Body: " +
                            result;

                this.fail(Components.results.NS_ERROR_FAILURE, error);
                break;
        }
    }, 
  
  
  
  
  
  
  onStopRequest: function (channel, ctxt, status)  {
    if(this._scheme != "ftp"){
      var res=0;
      try{
        res = channel.QueryInterface(Components.interfaces.nsIHttpChannel)
                       .responseStatus;
					   
	dump( "RESponse: " + res + "\n" );					   
					   
      }catch(e){}
      if(res==200||res==201 || res==204)
        status=0;
      /*
        200:OK
        201:Created
        204:No Content
        This is an uploading channel, no need to "GET" the file contents.
      */
      if(this._errorData)
        status=res;
      if(this._errorData && res==200)
        alert(this._errorData);
    }
    
    if(this._callback) {
      this._callback(reminderFox_getBundle().getString("rf.net.done"),status);  
      }
  }
};

