(function () {
    
    var G = Allthat.namespace('Allthat.GUI'),
        E = Allthat.namespace('Allthat.Entity'),
        W = Allthat.namespace('Allthat.Widget');
    
    E.WishlistClass = new Class({
      Implements : [Events, Options],
      
      options : {
          authorized : false
      },
      
      initialize : function (options) {
        this.setOptions(options);
          
        //this.initializeAddWishlistLink();
          
        //this.update();
        this.openAddBox();

        this.fireEvent('initialize');

  			// attach handler to add box
  			window.new_item = $('new_item');
  			new_item.value = LOREM_IPSUM_TEXT;
  			new_item.addEvent('focus', this.setupNewItem);
  			new_item.addEvent('blur', this.restoreLoremIpsum);
  			new_item.addEvent('keypress', this.enterSubmits);
  			window.price_range = $('price_range');
                        var mouseOver = 0;
                        jQuery("#share_fb_box").bind('mouseover', function(){
                            mouseOver = 1;
                        });
                        jQuery("#share_fb_box").bind('mouseleave', function(){
                            mouseOver = 0;
//                            jQuery("#share_fb_box").slideUp("fast");
                        });
                        jQuery("#new_item").focus(function(){
                            jQuery("#share_fb_box").slideDown("fast");
                        });
                        jQuery("#new_item").blur( function(){
                            if (mouseOver == 0){
                                jQuery("#share_fb_box").slideUp("fast");
                            }
                        });


                                  
     
      },

      setupNewItem : function() {
		    this.set('class', 'textbox_inline_active');
	      if (this.value == LOREM_IPSUM_TEXT) {
		      this.value = "";
		    }
		
		    // Display the min and max
		    price_range.setStyle('display', 'block');
	    },
	
	    restoreLoremIpsum : function() {
		    this.set('class', 'textbox_inline');
          if (this.value.trim() == "") {
	        this.value = LOREM_IPSUM_TEXT;
	      }
      },
      
      enterSubmits : function(event) {
        if (event.code == 13 && this.value != '') {
          Allthat.Entity.Query.saveQuery();
          this.blur();
        }
      },
        
        /**
         * bind click event listener to the "Add wishlist" button
         * @method initializeAddWishlistLink
         */
        initializeAddWishlistLink : function () {
            var addWishlistLink = $('add_wishlist_link'),
            
            // define what window should be shown - sign in or wishlist name
            c = (this.options.authorized) ? function (e) {
                    W.Popup.create(addWishlistLink, {
                        uniqueId : 'add_wish_list', 
                        toggleSelector : '#add_wis a', 
                        closeSelector : '#add_wishlist2_outer .close', 
                        targetId : 'add_wishlist2_outer', 
                        topOffset : 10, 
                        leftOffset : -200, 
                        clickClose : 0, 
                        group : 'wishlist', 
                        execute : G.selectWishlist
                    });
                    
                    if (e.preventDefault) e.preventDefault();
                    return false;
                } : 
                function (e) {
                    
                    W.Popup.create(addWishlistLink, {
                        uniqueId : 'signup_popup_link', 
                        toggleSelector : '#signup_popup_link', 
                        closeSelector : '#signup_popup_close', 
                        targetId : 'signup_outer', 
                        topOffset : 10, 
                        leftOffset : -48, 
                        group : 'nav', 
                        execute : G.selectSignup
                    }, true);
                    
                    if (e.preventDefault) e.preventDefault();
                    return false;
                };
            
            addWishlistLink.addEvent('click', c.bind(this));
            
            // bind event listener to the submit event of the add wishlist form:
            if (this.options.authorized) { // I use authorized as a condition cause it's mean that this element exist
                $('add_wishlist_form').addEvent('submit', function () {
                    Allthat.Entity.Wishlist.save();
                    return false;
                });
            }
        },
        
        openAddBox : function () {
            this.initializeControls();
            
            /*if (Allthat.wishlist_init) {
                Allthat.Widget.Reveal.create({
                    toggleSelector : '#wishlist_' + Allthat.wishlist_init + '_link', 
                    revealSelector : '#wishlist_' + Allthat.wishlist_init
                });
            }*/
            
            
            this.fireEvent('wishlistsLoaded');
        },
        
        initializeControls : function () {
          var blocks = $$('.wishlist_block'), // whole wishlist blocks
          getIdRegex = /^[\w\W]+_(\d+)_[\w\W]+$/; // for the speed purposes, better compile regex before use it. This regexp used to get wishlist id from the block html element id.
                
          // delete old occurents of the edit_wishlist popup, if any
            
          Allthat.Widget.Popup.remove('edit_wishlist');
            
          blocks.each(function (block) {               
            var user = block.get('user'); //brings the username
            var crypted_id = block.get('crypted'); //brings the crypted id
            var result = block.get('id').match(getIdRegex);
            if (result) {
              var id = parseInt(result[1], 0);

              // bind "createReveal" function to the click on the name of the wishlist
              var a = $('wishlist_' + id + '_link');

              Allthat.Entity.Query.update(id, null);

              /*
              // bind edit_wishlist and delete event listeners
              if (Allthat.authorized) {
                var spaceRegex = /&nbsp;/g,
                name = a.innerHTML.replace(spaceRegex, ''),
                editLink = $('edit_' + id);
                var wishlistNamePosition =
                  $('wishlist_' + id + '_control').getPosition();
              }
              */
            }
            this.fireEvent('controlsInitialize');
          }, this);
        },
        
        /**
         * Delete wishlist with specified id
         * I wish I could name this "delete", but it's reserved word
         * @method destroy
         * @param {Number} id of the wishlist
         */
        destroy : function (id) {
            if (confirm('Are you sure you would like to delete this wishlist?')) {
                new Request({
                    method : 'delete',
                    url : '/wishlists/' + id,
                    onSuccess : function () {
                        Allthat.Entity.Wishlist.update();
                    }
                }).send();
            }
        },
        /**
         * Add new wishlist
         * @method save
         */
        save : function () {
            var wishlistId = $('wishlist_id').get('value'),
                url = (wishlistId) ? '/wishlists/update/' + wishlistId : '/wishlists/create';
            
            $('add_wishlist_form').set('send', {
                method : 'post',
                onSuccess : function () {
                    Allthat.Entity.Wishlist.update();
                    $('wishlistName').set('value', '');
                    $('add_wishlist2_outer').addClass('hide');
                }
            }).send(url);
        },

        /**
         * Add item to wishlist
         * @method additem
         */
        add_item : function (queryId,wishlistId) {
		url = '/queries/add_tomylist/'+queryId+'?wishlist_id='+wishlistId ;

                $$('.additem_tolist_spinner').each(function (spinner) {
			spinner.setStyle('display', 'block');
		    });

		$('add_wishlist_form').set('send', {
			onSuccess : function () {

			    Allthat.Entity.Query.update(wishlistId, null);
          var revealObject = Allthat.Widget.Reveal.REVEALS['#wishlist_' + wishlistId + '_link'];
                    
			    if (!revealObject) {
				var reveal_selector = '#wishlist_' + wishlistId;
				var toggle_selector = '#wishlist_' + wishlistId + '_link';
				Allthat.Widget.Reveal.create({
					revealSelector : reveal_selector, 
					    toggleSelector : toggle_selector
					    });
				var revealObject = Allthat.Widget.Reveal.REVEALS[toggle_selector];
			    }

			    if (!revealObject.visible) {
				revealObject.toggle();
			    }
                             
                            $$('.additem_tolist_spinner').each(function (spinner) {
				    spinner.setStyle('display', 'none');
				});

			    $('additem_towishlist_outer').addClass('hide');
                            $('add_to_' + queryId + '_link').set('text','+ Add to my List');

			},
		        onFailure: function(transport){ 
			    $$('.additem_tolist_spinner').each(function (spinner) {
				    spinner.setStyle('display', 'none');
				});
			    alert('Can not add duplicate items !!');
			}
		    }).send(url);
	    },

        /**
         * Update wishlist
         * @method update
         */
        update : function () {
            var url = '/wishlists/index.html';
            
            if (Allthat.isIE7) {
              url = url + '?UUID=' + Allthat.generateUUID();
            }

            new Request.HTML({
                url : url,
                method : 'get',
                onSuccess : function () {
                    Allthat.Entity.Wishlist.openAddBox();
                },
                update : 'wishlist_guts'
            }).send();
        }

    });
    
})();
