/*
 * ajax stuff to go here...
*/

Drupal.behaviors.simpleEvent = function(context) {
  for (var base in Drupal.settings.simpleEvent) {
    if (!$('#'+ base + '.simple_replace_processed').size()) {
      var element_settings = Drupal.settings.simpleEvent[base];
      $(element_settings.selector).each(function() {
        element_settings.element = this;
        var simpleEvent = new Drupal.simpleEvent(base, element_settings);
      });

      $('#'+ base).addClass('simple_replace_processed');
    }
  }
};

// constructor.
Drupal.simpleEvent = function(base, options){
	switch(options.operation){
		case 'ahah':{
			var ahah = new Drupal.simpleEvents.ahah(base, options);
		  break;
		}
		default:{
			this.options = options;
		  this.element = options.element;
		  var _self = this;

		  $(options.element).bind(options.event, function(event) {
		    switch(_self.options.operation) {
		      case 'call':
		        if (_self.options.beforeCallback){
              eval(_self.options.beforeCallback)(_self, _self.options);
            }
		        var val = (eval(_self.options.callback)(_self, _self.options, event));
		        if (_self.options.afterCallback){
		        	eval(_self.options.afterCallback)(_self, _self.options);
		        }
		        return val;
		      case 'replace':
		        return Drupal.simpleEvents.simpleReplaceCallback(_self, _self.options);
		      case 'json':    
		        return false;
		        Drupal.simpleEvents.jsonCallback(_self, _self.options);
		      break;
		      default:
		      return _self.options.return_value ? _self.options.return_value : false;
		    }
		  });
		}
	}
}

Drupal.simpleEvents = {};
Drupal.simpleEvents.utils = {};

Drupal.simpleEvents.simpleReplaceCallback = function(_self, options){

	options.onComplete = options.onComplete || null;
	options.onBefore = options.onBefore || null;
	
	eval(options.onBefore)(_self, options);

	if (options.paramsCallback) {
		var params = eval(options.paramsCallback)(_self, options);
	}
	
	var url = options.url;
	if (options.filter) {
		url += ' '+options.filter;
	}
	$(options.target).load(url, params, function() {
	 if(options.onComplete){
	   eval(options.onComplete)(_self, options);
	   alert('load complete');
	 }
	});
	return _self.options.return_value ? _self.options.return_value : false;
}

Drupal.simpleEvents.jsonCallback = function(_self, options){
    var ajax_options = {
    url: options.submit_url,
    data: options.data,
    beforeSubmit: function() {
    	options.beforeSubmit(_self, options);
    },
    success: function(response, status) {
      // Sanity check for browser support (object expected).
      // When using iFrame uploads, responses must be returned as a string.

      if (typeof(response) == 'string') {
        response = Drupal.parseJson(response);
      }      
      if (options.onSubmitSuccess) {  
        eval(options.onSubmitSuccess)(_self, options, response, status);
      }
      //return _self.success(response, status);
    },
    complete: function(response, status) {
      if (status == 'error' || status == 'parsererror') {
        //return _self.error(response, ahah.url);
      }
      
    },
    dataType: 'json',
    type: 'POST'
  };
  $.ajax(ajax_options);
}

Drupal.simpleEvents.utils.imageWorking = function(_self, options) {
  if (options.workingTarget) {
  	var html = $('<div class="se_working"></div>');
  	if (options.workingMessage){
  	 html.append(options.workingMessage);
  	}
  	else if (options.workingImage){
  		html.append('<img src="'+options.workingImage+'"/>');
  	}
  	else {
  		html.append('Loading...');
  	}
  	$(options.workingTarget).html(html);
  } 
}

Drupal.simpleEvents.utils.thumbnailSetSuccess = function(_self, options, response, status) {
	if (status == "success") {
		var el = $(options.imgTarget);
		if (el) {
		  el.html(response.data)		
		}
	}
}

Drupal.simpleEvents.utils.formValue = function(_self, options) {
	// this is weak, there must be a better way.
	return {
		"value":$(options.paramsCallback_formElement).val()
	};
}

Drupal.simpleEvents.utils.imageSelectPopup = function(_self, options) {
	var width = options.width || 600;
  var height = options.height || 600;

  $(document).bind("onImageSelectEvent", function (event, val) {
    $(options.form_item).val(val);
    $(options.form_sumit_element).trigger('click');
    $(document).unbind("onImageSelectEvent");
  });

  _self.utilsPopupWin = window.open(options.url, 'UTILSPOPUP', "width="+width+",height="+height+",scrollbars=yes,resize=yes");
  if (_self.utilsPopupWin){
  	_self.utilsPopupWin.focus();
  	var popupCaller = {}
  	popupCaller._self = _self;
  	popupCaller.options = options;
  	_self.utilsPopupWin.popupCaller = popupCaller;
  }
  else {
    Drupal.simpleEvents.utils.notifyError("Sorry, there was a problem opening the popup window.  Please check your popup blocker.", true);
  }
  return false;
}

Drupal.simpleEvents.utils.thumbnailSelectPopup = function(_self, options) {
  var width = options.width || 600;
  var height = options.height || 600;
  var key_value = $('#'+options.node_key).val();
  var key_type = '1';
  if (typeof(key_value) == 'undefined' || key_value == 0) {
    key_value = $('#'+options.temp_key).val();
    key_type = '3';
  }

  $(document).bind("onThumbnailSelectEvent", function (event, val) {
    //FUCK IT!
    var key_value = $('#'+options.node_key).val();
    var key_type = '1';
    if (typeof(key_value) == 'undefined' || key_value == 0) {
      key_value = $('#'+options.temp_key).val();
      key_type = '3';
    }
    options.data = "file="+val+'&key_type='+key_type+'&key_value='+key_value;
    Drupal.simpleEvents.jsonCallback(_self, options);
    $(document).unbind("onThumbnailSelectEvent");
  });

  _self.utilsPopupWin = window.open(options.url+'/'+key_value+'/'+key_type, 'THUMBNAILPOPUP', "width="+width+",height="+height+',scrollbars=yes,resize=yes');
  if (_self.utilsPopupWin){
    _self.utilsPopupWin.focus();
    var popupCaller = {}
    popupCaller._self = _self;
    popupCaller.options = options;
    _self.utilsPopupWin.popupCaller = popupCaller;
  }
  else {
    Drupal.simpleEvents.utils.notifyError("Sorry, there was a problem opening the popup window.  Please check your popup blocker.", true);
  }
  return false;
}

Drupal.simpleEvents.utils.popupClose = function(_self, options) {
  if (_self.utilsPopupWin){
  	_self.utilsPopupWin.close();
  	return true;
  }
  else if (self.parent){
  	self.close();
  }
  return false;
}

Drupal.simpleEvents.utils.signalParent = function(_self, options) {
  var value = options.value;
  if (window.opener){
    eval("window.opener."+options.signal)(value);
  }
  else {
  	eval("window."+options.signal)(value);
  }
  return false;
}

Drupal.simpleEvents.utils.notifyError = function(message, show_default) {
	if (show_default){
		message += "\nIf the problem persists, please contact technical support.";
	}
  alert(message);
}

Drupal.simpleEvents.utils.switchTab = function(_self, options, event) {
	$("."+options.tabs_class).hide();
	$('.'+options.tabs_link_class).removeClass('active');
  $(_self.element).addClass('active');
	$(options.tab_container).show();
  return false;
}


/**
 * this is a copy of the ahah object, just with better features
 */
Drupal.simpleEvents.ahah = function(base, element_settings) {
  // Set the properties for this object.
  this.element = element_settings.element;
  this.selector = element_settings.selector;
  this.event = element_settings.event;
  this.keypress = element_settings.keypress;
  this.url = element_settings.url;
  this.wrapper = '#'+ element_settings.wrapper;
  this.effect = element_settings.effect;
  this.method = element_settings.method;
  this.progress = element_settings.progress;
  this.button = element_settings.button || { };
  this.target = element_settings.target || null;
  this.action_id = element_settings.action_id || null;
  this.action_value = element_settings.action_value || null;
  

  if (this.effect == 'none') {
    this.showEffect = 'show';
    this.hideEffect = 'hide';
    this.showSpeed = '';
  }
  else if (this.effect == 'fade') {
    this.showEffect = 'fadeIn';
    this.hideEffect = 'fadeOut';
    this.showSpeed = 'slow';
  }
  else {
    this.showEffect = this.effect + 'Toggle';
    this.hideEffect = this.effect + 'Toggle';
    this.showSpeed = 'slow';
  }

  // Record the form action and target, needed for iFrame file uploads.
  var form = $(this.element).parents('form');
  this.form_action = form.attr('action');
  this.form_target = form.attr('target');
  this.form_encattr = form.attr('encattr');

  // Set the options for the ajaxSubmit function.
  // The 'this' variable will not persist inside of the options object.
  var ahah = this;
  var options = {
    url: ahah.url,
    data: ahah.button,
    beforeSubmit: function(form_values, element_settings, options) {
      return ahah.beforeSubmit(form_values, element_settings, options);
    },
    success: function(response, status) {
      // Sanity check for browser support (object expected).
      // When using iFrame uploads, responses must be returned as a string.
      if (typeof(response) == 'string') {
        response = Drupal.parseJson(response);
      }
      return ahah.success(response, status);
    },
    complete: function(response, status) {
      if (status == 'error' || status == 'parsererror') {
        return ahah.error(response, ahah.url);
      }
    },
    dataType: 'json',
    type: 'POST'
  };

  // Bind the ajaxSubmit function to the element event.
  $(element_settings.element).bind(element_settings.event, function() {
  	try {
  		if (ahah.action_value && ahah.action_id) {
        $('#'+ahah.action_id).val(ahah.action_value); 
      }
      $(element_settings.element).parents('form').ajaxSubmit(options);
  	}
  	catch(e){
  		debugger;
  	}
    return false;
  });
  
  // If necessary, enable keyboard submission so that AHAH behaviors
  // can be triggered through keyboard input as well as e.g. a mousedown
  // action.
  if (element_settings.keypress) {
    $(element_settings.element).keypress(function(event) {
      // Detect enter key.
      if (event.keyCode == 13) {
        $(element_settings.element).trigger(element_settings.event);
        return false;
      }
    });
  }
};

/**
 * Handler for the form redirection submission.
 */
Drupal.simpleEvents.ahah.prototype.beforeSubmit = function (form_values, element, options) {
  // Disable the element that received the change.


  $(this.element).addClass('progress-disabled').attr('disabled', true);

  // Insert progressbar or throbber.
  if (this.progress.type == 'bar') {
    var progressBar = new Drupal.progressBar('ahah-progress-' + this.element.id, eval(this.progress.update_callback), this.progress.method, eval(this.progress.error_callback));
    if (this.progress.message) {
      progressBar.setProgress(-1, this.progress.message);
    }
    if (this.progress.url) {
      progressBar.startMonitoring(this.progress.url, this.progress.interval || 1500);
    }
    this.progress.element = $(progressBar.element).addClass('ahah-progress ahah-progress-bar');
    this.progress.object = progressBar;
    $(this.element).after(this.progress.element);
  }
  else if (this.progress.type == 'throbber') {
    this.progress.element = $('<div class="ahah-progress ahah-progress-throbber"><div class="throbber">&nbsp;</div></div>');
    if (this.progress.message) {
      $('.throbber', this.progress.element).after('<div class="message">' + this.progress.message + '</div>')
    }
    $(this.element).after(this.progress.element);
  }
};

/**
 * Handler for the form redirection completion.
 */
Drupal.simpleEvents.ahah.prototype.success = function (response, status) {
  var wrapper = $(this.wrapper);
  var form = $(this.element).parents('form');


  // Restore the previous action and target to the form.
  form.attr('action', this.form_action);
  this.form_target ? form.attr('target', this.form_target) : form.removeAttr('target');
  this.form_encattr ? form.attr('target', this.form_encattr) : form.removeAttr('encattr');

  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  $(this.element).removeClass('progress-disabled').attr('disabled', false);


  if (response.status == false){
    alert('Sorry, there was an error.  Please contact technical support.  Here is the message from the server:\n'+response.data);
    return;
  }

  var new_content = null;

  // Manually insert HTML into the jQuery object, using $() directly crashes
  // Safari with long string lengths. http://dev.jquery.com/ticket/1152
  
  if(response.data){
	  new_content = $('<div></div>').html(response.data);
	
	  // Add the new content to the page.
	  Drupal.freezeHeight();
	  if (this.method == 'replace') {
	    wrapper.empty().append(new_content);
	  }
	  else {
	    wrapper[this.method](new_content);
	  }
    if (($.browser.safari && $("tr.ahah-new-content", new_content).size() > 0)) {
      new_content.show();
    }
    else if ($('.ahah-new-content', new_content).size() > 0) {
      $('.ahah-new-content', new_content).hide();
      new_content.show();
      $(".ahah-new-content", new_content)[this.showEffect](this.showSpeed);
    }
    
    // Attach all javascript behaviors to the new content, if it was successfully
	  // added to the page, this if statement allows #ahah[wrapper] to be optional.
	  if (new_content && new_content.parents('html').length > 0) {
	    Drupal.attachBehaviors(new_content);
	  }    
  }
  
  var target_content = $('<div></div>').html(response.target);
  if (this.target){
    var target = $(this.target);
  
    target.empty().append(target_content);

	  // Immediately hide the new content if we're using any effects.
	  if (this.showEffect != 'show') {
	    target_content.hide();
	  }
	  if (($.browser.safari && $("tr.ahah-new-content", new_content).size() > 0)) {
	    target_content.show();
	  }
	  else if (this.showEffect != 'show') {
	    target_content[this.showEffect](this.showSpeed);
	  }
  }

      //Inject inline scripts
  if (response.scripts != "") {
    injectScript(response.scripts);
    Drupal.attachBehaviors($(this.wrapper));
  }

  if (response.messages) {
  	alert(response.messages);
  }

  Drupal.unfreezeHeight();
};

/**
 * Handler for the form redirection error.
 */
Drupal.simpleEvents.ahah.prototype.error = function (response, uri) {
  alert(Drupal.ahahError(response, uri));
  // Resore the previous action and target to the form.
  $(this.element).parent('form').attr( { action: this.form_action, target: this.form_target} );
  // Remove the progress element.
  if (this.progress.element) {
    $(this.progress.element).remove();
  }
  if (this.progress.object) {
    this.progress.object.stopMonitoring();
  }
  // Undo hide.
  $(this.wrapper).show();
  // Re-enable the element.
  $(this.element).removeClass('progess-disabled').attr('disabled', false);
};


/**
 * Image management events
 */

if (!self.ImageHandler){
	ImageHandler = {};
}
if (!self.ImageHandler.events){
	ImageHandler.events = {};
}
ImageHandler.events.onImageSelected = function(val){
  $(document).trigger("onImageSelectEvent", val);
}
ImageHandler.events.onThumbnailSelected = function(val) {
  $(document).trigger("onThumbnailSelectEvent", val);	
}

