jQuery.fw = jQuery.fw || {}; // create the namespace

(function($) {
  jQuery.widget("fw.flashgameFavoriteBox", {

    init: function() {
		  this.status = 'initing';
      //this.settings = {};
      this.$container = $(this.element);
      var name_opts = this.$container.attr('name').split('|');
      this.options.gameid = name_opts[0];
      this.options.infavorite = name_opts[1];
	    this.status = 'done';
      this.update();
    },
    show: function(){
         this.update();
    },
    hide: function(){
         //Code Here
    },
    update: function(){
		this.$container.unbind('click');
		if (this.status == 'progress') {
			this.$container.html(this.options.texts.saving);
		}
		else {
			var linktext;
			if (!this.options.infavorite) {
				linktext = this.options.texts.add;
			}
			else {
				linktext = this.options.texts.remove;
			}
			this.$container.empty();
			$('<a href="javascript:void(0);"></a>').append(linktext).appendTo(this.$container);
			var self = this;
			this.$container.click(function(e){
				onClick.apply(self, []);
			});
		}
    }

  });
  function onClick(event){
  	var self = this;
		console.log('onClick()');
		if(this.status=='done'){
			var command = false;
			if(!this.options.infavorite){
				command = 'add';
			}else command = 'remove';

			this.command = command;
			this.status='progress';
			this.update();
			$.ajax({
	            type: "GET",
	            url: this.options.ajax_url,
	            data: {
					command: command,
					gameid: this.options.gameid
				},
	            success: function(data) { onData.apply(self, [data]) },
	            dataType: "json",
	            error: function(xhr, status, e){
					/*
	                //debugger;
	                if (errback) {
	                    errback(xhr, status, e)
	                } else {
	                    callback()
	                }
	                indicate(false)
	                */
	            }
	        });
		}
		return false;
	}
  function onData(data){
  	console.log('onData()');
	if (this.command == 'add') {
		this.options.infavorite=true;
	}
	else if (this.command == 'remove') {
		this.options.infavorite=false;
	}
	this.status='done';
	this.update();
  }
  function hoverHandler(event){
      //Handler Code
  };
  function outHandler(event){
      //Handler Code
  };
  function someOtherFunction(parameter){
      //Code Here
  };
  //....
})(jQuery);
jQuery.extend(jQuery.fw.flashgameFavoriteBox, {
    defaults: {
        // URL for ajax calls
        ajax_url:'/ajax/favorite',
        texts:{
          add: 'Add to Favorites ',
          remove:  'Remove from Favorites ',
          saving:  'saving...'
        }
    }
});

