var ticket_id;

if(!Zendesk) var Zendesk = {};
Zendesk.resources = [];
Zendesk.Resource = Class.create();
	
Zendesk.Resource.prototype = {
  initialize : function(options) {  		  	
    this.options      = options || {};   
    this.options.user = options.user || Cookie.get(this.options.anchor + '_user')
    this.options.pass = options.pass || Cookie.get(this.options.anchor + '_pass') 
    this.content_anchor = $$('#' + this.options.anchor + ' #content')[0]
    this.title_anchor   = $$('#' + this.options.anchor + ' #title')[0]  
     
 		Ajax.Responders.register({ onException: function(r, e) { alert("Exception:\n\n" + e) }});          

		if (this.options.title) {
		  this.title_anchor.innerHTML = this.options.title;
		}
		
    this.render();             		     				           
  },
  submit_credentials : function(form) {  
		this.options.user = form['username'].value;
		this.options.pass = form['password'].value;  	
		if (this.options.user.blank() && this.options.pass.blank())
			alert('Please provide both a username and a password');
		else {
  		Cookie.set(this.options.anchor + '_user', this.options.user);
  		Cookie.set(this.options.anchor + '_pass', this.options.pass); 
    	this.render();   		
  	}  	
  },  
  logout : function() { 
    options = this.options;
    Cookie.erase(options.anchor + '_user');
    Cookie.erase(options.anchor + '_pass');
    this.options.user = this.options.pass = null;
    this.render();
  },
  submit_data : function(form) {
  	control = this;
  	var parameters = Form.serialize(form);
  	parameters += "&user=" + control.options.user + "&pass=" + control.options.pass + "&domain=" + control.options.domain + "&use_ssl=" + control.options.use_ssl;
  	if (ticket_id) {
  	  parameters += "&ticket_id=" + ticket_id;
	  }
    if ( parameters.indexOf("media_type=") == 0 ) {
      var media_type = control.options.media_type || 'application/xml';
      parameters += "&media_type=" + media_type;
    }
		new Ajax.Request('/proxy.js', {asynchronous:true, evalScripts:true, parameters:parameters,
			onSuccess: function(transport) { control.resource_write_success(transport, control); enable_submit(form); },
    	onFailure: function(transport) { control.resource_failure(transport, control); enable_submit(form); }
    }); 
    disable_submit(form)
  },
  render : function() { 
  	control = this;	
  	options = control.options; 	
  	if (options.login_content != null && !(options.user && options.pass)) 
  		control.content_anchor.innerHTML = options.login_content();
		else {					  				
			control.content_anchor.innerHTML =	options.application_content();		  	
  		options.application_resources.each(function(resource){control.request(resource)});
		}		
  },
  request : function(options) {
  	control = this; 		
  	if (options.resource == null) {
  		if (options.on_success != null) {
  		  options.on_success();
  		}
  	}
  	else {	  		
	  	media_type = options.media_type || 'application/json';
			new Ajax.Request('/proxy.js', {
	  		method: 'get',
				parameters: {user: control.options.user, pass: control.options.pass, 
										 domain: control.options.domain, use_ssl: control.options.use_ssl, 
										 resource: options.resource, media_type: media_type, cache_gets: control.options.cache_gets},
	  		onSuccess: function(transport) { control.resource_read_success(transport, control, options); },
	    	onFailure: function(transport){ control.resource_failure(transport, control); }
	    });	
    }	
  },
  resource_failure : function(transport, control) {
    if (transport.status == 401) {  
			control.options.user = null; control.options.pass = null;					 		
			Cookie.erase(control.options.anchor + '_user'); Cookie.erase(control.options.anchor + '_pass'); 		
			if (control.content_anchor.innerHTML != control.options.login_content())			
				alert("Username and password are not correct. Please re-enter.");
			control.render();	}
    else {
    	alert(transport.responseJSON.error)
  	}
  },
  //Called when data has been read
  resource_read_success : function(transport, control, options) {
    if(options != null && options.on_success != null) {
      options.on_success(transport.responseJSON);      
    }
  },
  //Called when data has been written
  resource_write_success : function(transport, control) {
    if(transport.responseJSON.audit != null) {
		  new Ajax.Request('/events/create.js', {
  		  method: 'post', asynchronous:true,
			  parameters: { ticket_id: transport.responseJSON.audit.ticket_id,
			                value:     transport.responseJSON.audit.value,
			                reference: transport.responseJSON.audit.reference,
			                via_id:    transport.responseJSON.audit.via_id },
  		  onSuccess: function(transport) { },
    	  onFailure: function(transport){ alert('Failed to register event: '+transport.responseJSON.error); }
      });	
    }
  }  
}	


function enable_submit(form) {
	form['submit'].value = form['submit'].getAttribute('originalValue'); 
	form.enable();		
	form.reset();
}

function disable_submit(form) {
	form['submit'].setAttribute('originalValue', form['submit'].value);	
	form.disable();		
	form['submit'].value = 'Submitting...';		
}


