/**
 * Used to workaround with items
 * @class items
 */
(function () {
    
    var G = Allthat.namespace('Allthat.GUI'),
    E = Allthat.namespace('Allthat.Entity');
    
    E.QueryClass = new Class({
        Implements : [Events, Options],
        options : {
            authorized : false
        },
	    
        initialize : function (options) {
            this.setOptions(options);

            this.addItemToList();

            this.fireEvent('initialize');

            // Attach add item to clicking the "save" button
            jQuery('#save_query').bind('click', this.saveQuery);
        },

        addItemToList : function(){
            var addToListForm = $('add_tomylist_form');
            if (addToListForm) {
                addToListForm.addEvent('submit', function () {
                    if ($('selected_wishlist').value==""){
                        alert('Please add wishlist before use this feature !!');
                    }
                    Allthat.Entity.Wishlist.add_item($('additem_query_id').value,$('selected_wishlist').value);
                    return false;
                });
            }
        },

        /**
     * bind event listeners to the events (edit, show results, delete, etc.)
     * @method bindEventListeners
     */
        bindEventListeners : function () {
            if (!window.toggleStatus) {window.toggleStatus = new Array();}

            $$('.wish_row').each(function (block) {
                // get metadata (query id, wishlist id and allthat)
                var meta = eval('(' + block.getElement('.meta').get('html') + ')'),
                queryId = meta.queryId,
                wishlistId = meta.wishlistId;

                // bind delete link events
                var deleteLink = block.getElement('a.x');
                if (Allthat.authorized && deleteLink) {
                    deleteLink.addEvent('click', function (e) {
                        Allthat.Entity.Query.destroy(queryId, wishlistId);

                        if (e.preventDefault) e.preventDefault();
                        return false;
                    });
                }
                toggleStatus[queryId] = 'unloaded';

                var showResultsLink = block.getElement('.item_title a.results_toggle');
                var showResultsLinkCount = block.getElement('#view_' + queryId + ' a.results_count'); // id is always unique
                var statusQuery = block.getElement('.status_query');
                if (showResultsLink) {
                    showResultsLink.addEvent('click', function (e) {
                        Allthat.Entity.Item.toggle(queryId, showResultsLink);
                        if (e.preventDefault) e.preventDefault();
                        return false;
                    });
                }
                if (showResultsLinkCount && showResultsLink) {
                    showResultsLinkCount.addEvent('click', function (e) {
                        Allthat.Entity.Item.toggle(queryId, showResultsLink);
                        if (e.preventDefault) e.preventDefault();
                        return false;
                    });
                }

                if (statusQuery) {
                    statusQuery.addEvent('click', function (e) {
                        Allthat.Entity.Item.toggle(queryId, showResultsLink);
                        if (e.preventDefault) e.preventDefault();
                        return false;
                    });
                }

                /*
                var anotherOneShowResultLink = block.getElement('.item_details span.results_toggle');
                if (anotherOneShowResultLink) {
                    anotherOneShowResultLink.addEvent('click', function (e) {

                        var yellowAlert = block.getElement('.item_details span.results_toggle .new_item');
                        if ( yellowAlert ){
                            yellowAlert.setStyle('display','none');
                        }

                        Allthat.Entity.Item.show(queryId, anotherOneShowResultLink);

                        if (e.preventDefault) e.preventDefault();
                        return false;
                    });
                }
                */
                // edit item link
                var editLink = $('edit_' + queryId + '_link');
                if (editLink) {
                    editLink.addEvent('click', function (e) {
                        Allthat.Entity.Query.makeEditable(queryId, wishlistId);

                        if (e.preventDefault) e.preventDefault();
                        return false;
                    });
                }

                // update item link

                var updateLink = $('update_' + queryId + '_link');
                if (updateLink) {
                    updateLink.addEvent('click', function (e) {
                        Allthat.Entity.Query.updateQuery(queryId, wishlistId);
                        if (e.preventDefault) e.preventDefault();
                        return false;
                    });
                }

                // cancel item link

                var cancelLink = $('cancel_' + queryId);
                if (cancelLink) {
                    cancelLink.addEvent('click', function (e) {
                        this.setStyle('display', 'none');
                        Allthat.Entity.Query.cancel(queryId);
                        if (e.preventDefault) e.preventDefault();
                        return false;
                    });
                }

                // bind add item to wishlist link events
                var additemLink = $('add_to_' + queryId + '_link');
                if (additemLink) {
                    additemLink.addEvent('click', function (e) {
                        Allthat.Entity.Query.fetch_wishlists(queryId,additemLink);

                        if (e.preventDefault) e.preventDefault();
                        return false;
                    });
                }

            }, this);
        },
        /**
     * Fill advanced add item box with appropriate values and focus user input on the item name field
     * @method fillInAdvancedForm
     */
        fillInAdvancedForm : function () {
            $('add_item_advanced_textbox').set('value', $('add_item_textbox').get('value'));
            $('adv_wishlist_id').set('value', $('query_wishlist_id').get('value'));
            $('add_item_advanced_textbox').focus();
        
            this.checkall();
        
            this.fireEvent('fillInAdvancedForm');
        },
        /**
     * initialize checkgroup
     * @method checkall
     */
        checkall : function () {

            this.initializeAddOrEditQueryForm();
            new Allthat.Widget.Checkgroup({
                masterSelector : '#adv_addbox_container .where_look_master',
                childSelector : '#adv_addbox_container .where_look_child'
            });
        },
        /**
     * bind event listener to the submit event of the add/edit form
     * @method initializeAddOrEditQueryForm
     */
        initializeAddOrEditQueryForm : function () {
            // edit form
            $('adv_addbox_form_elem').addEvent('submit', function (e) {
                var meta = $(this).getElement('.meta'), // get dom element with class meta, which contains JSON object with wishlist and (if available) query id
                wishlistId = $('query_wishlist_id').get('value');
	
                // validate query
                if ($('add_item_advanced_textbox').get('value').trim().length == 0) {
                    $('error_for_empty_item_name').removeClass('hide');
                } else {
                    $('error_for_empty_item_name').addClass('hide');
                    if (meta) {
                        try { // try to eval JSON object
                            meta = eval('(' + meta.innerHTML + ')');
                        } catch (e) {
                            return false; // silently ignore
                        }
                        if (meta.queryId) { // edit
                            Allthat.Entity.Query.save(wishlistId, meta.queryId, this.get('id'));
                        } else {
                            Allthat.Entity.Query.save(wishlistId, null, this.get('id'));
                        }
                    }
                }
            
                if (e.preventDefault) e.preventDefault();
                return false;
            });
        
            this.fireEvent('initializeAddOrEditQueryForm');
        },

        // Function called when the user clicks the save button
        saveQuery : function() {
            wishlistId = $('query_wishlist_id').get('value');
            queryId = null;
            queryText = $('new_item').get('value');
            checked = jQuery('#send_to_wall').attr('checked');

            if (queryText != LOREM_IPSUM_TEXT) {
                //maxPrice = $('new_item_max').get('value');
                //minPrice = $('new_item_min').get('value');
	
                Allthat.Entity.Query.saveInline(wishlistId, queryId, queryText,checked);
             // reset the search box
                var item = $('new_item');
                item.set('value','');
                item.fireEvent('blur');
            //$('new_item_max').set('value','');
            //$('new_item_min').set('value','');
            }
              if (jQuery('#user_fb_share').attr('checked')) {
               jQuery('#send_to_wall').attr("checked","checked");
              } else {
                    jQuery('#send_to_wall').attr("checked","");
              }
             
        },
	
        makeEditable: function(queryId, wishlistId) {
            var query = $('query_' + queryId);
            var searchHref = query.getElement(".bluebold a");
            searchHref.setStyle('display', 'none');
            var searchInput = query.getElement(".bluebold input");
            searchInput.setStyle('display', 'inline');
            searchInput.addEvent('keypress', function(event) {
                var submitted =
                Allthat.Entity.Query.enterSubmits(event, queryId, wishlistId);
                if (!submitted) {
                    // clear the min and max price when the user edits the query text
                    Allthat.Entity.Query.clearMinMax(queryId);
                }
            });
	  
            var priceRange = query.getElement('#price_range_' + queryId);
            var minMaxText = priceRange.getElements('span');
            minMaxText.setStyle('display', 'none');
            var minMaxInput = priceRange.getElements('input');
            minMaxInput.setStyle('display', 'inline');
	  
            var view = $('view_' + queryId);
            view.setStyle('display', 'none');
//            query.getElement('.fifth .green').setStyle('padding-top', '0px')
            var edit = $('edit_' + queryId);
            edit.setStyle('display', 'inline');

            var cancel = $('cancel_' + queryId);
            cancel.setStyle('display', 'inline');

            var text = $('note_text_' + queryId);
            text.setStyle('display', 'none');

            var editLink = $('edit_' + queryId + '_link');
            editLink.setStyle('display', 'none');
	  
            $('inline_results_' + queryId).setStyle('display', 'none');
            $('result_sort_' + queryId).setStyle('display','none');
        },
  
        enterSubmits: function(event, queryId, wishlistId) {
            if (event.code == 13 && this.value != '') {
                Allthat.Entity.Query.updateQuery(queryId, wishlistId);
                return true;
            } else {
                return false;
            }
        },
  
        clearMinMax: function(queryId) {
            $("min_price_upd_" + queryId).setProperty('value', null);
            $("max_price_upd_" + queryId).setProperty('value', null);
        },
  
        updateQuery: function(queryId, wishlistId) {
            var queryText = $("query_upd_" + queryId).getProperty('value');
            var minPrice = $("min_price_upd_" + queryId).getProperty('value');
            var maxPrice = $("max_price_upd_" + queryId).getProperty('value');
             checked = jQuery('#send_to_wall').attr('checked');
            // Get rid of any results that we're showing
            toggleStatus[queryId] == 'unloaded';
            Allthat.Entity.Query.saveInline(wishlistId, queryId, queryText,checked, minPrice, maxPrice);
        },
        
        bindMouseOverToTheDeleteButton : function () {
            var MouseOver = new Class({
                Implements : [Options],
                options : {
                    target : '.x_reveal, .edit_reveal',
                    showSelectors : ['.x'],
                    body : $$('body')[0]
                },
                initialize : function (options) {
                    this.setOptions(options);
                
                    this.boundShow = this.show.bind(this);
 
                    this.options.body.addEvent('mouseover', this.boundShow);
                },
                show : function (e) {
                    var el = $(e.target);
                    if (el.match(this.options.target)) {
                        if (el != this.shown) {
                            this.hide();
                        }
                        this.shown = el;
                        this.options.showSelectors.each(function (selector) {
                            var toShow = el.getElement(selector);
                            if (toShow) {
                                toShow.setStyle('display', 'block');
                            }
                        }, this);
                    }
                },
                hide : function () {
                    var el = this.shown;
                    if (el) {
                        this.options.showSelectors.each(function (selector) {
                            var toHide = el.getElement(selector);
                            if (toHide) {
                                toHide.setStyle('display', 'none');
                            }
                        }, this);
                    }
            
                }
            });
        
            new MouseOver();
        },
        /**
     * Update queries
     * @method update
     */
        update : function (wishlistId, queryId) {
            var url = '/queries?wishlist_id=' + wishlistId;
            if (Allthat.isIE7) {
                url = url + '&UUID=' + Allthat.generateUUID();
            }
      
            new Request.HTML({
                url : url,
                method : 'get',
                update : 'wishlist_'+wishlistId,
                onSuccess : function () {
                    Allthat.Entity.Query.bindEventListeners();
                    if (queryId) {
                        Allthat.Entity.Query.setLoading(queryId);
                    }
                }
            }).send();
        },
    
        /**
     * Mark the query as "loading"
     * @method setLoading
     */
        setLoading: function (queryId) {
            // put the loading image on the toggle
            var toggleElement =
            $("query_" + queryId).getElement(".results_info .results_toggle");
            toggleElement.removeClass('collapsed');
            toggleElement.addClass('loading');
	    
            // show the "we are searching the web" text
            $("view_" + queryId).setStyle('display','none');
            $("working_" + queryId).setStyle('display','inline');
        },
    
        /**
     * Mark the query as having finished loading
     * @method setLoading
     */
        setLoaded: function (queryId, numItems) {
            // show the number of results
            $("working_" + queryId).setStyle('display','none');
            $("view_" + queryId).setStyle('display','inline');
	    
            // Expand the toggle if the search returned results
            var toggleElement =
            $("query_" + queryId).getElement(".results_info .results_toggle");
            toggleElement.removeClass('loading');
            if (numItems > 0) {
                Allthat.Entity.Item.toggle(queryId, toggleElement);
            } else {
                toggleElement.addClass('collapsed');
            }
        },
	    
        /**
	 * Brings the queries for the following wishedlist
	 * @method fetch_queries
	 */
        fetch_queries : function (user,wishlistId) {
            var url = '/queries/followlist_queries/'+ wishlistId;
	    
            if (Allthat.isIE7) {
                url = url + '&UUID=' + Allthat.generateUUID();
            }
	    
            new Request.HTML({
                url : url,
                method : 'get',
                update : 'followlist_'+user+'_'+wishlistId,
                onSuccess : function () {
                    Allthat.Entity.Query.bindEventListeners();
                }
            }).send();
        },
	    
        /**
	 * Brings the names of the wishlists
	 * @method fetch_wishlists
	 */
        fetch_wishlists : function (queryId,additemLink) {
            var url = '/followlists/show_lists';
            $('additem_query_id').value=queryId;
            $('add_to_' + queryId + '_link').set('text','+ Add to my AllThat');
   
            if (Allthat.isIE7) {
                url = url + '?UUID=' + Allthat.generateUUID();
            }
         
            new Request.HTML({
                url : url,
                method : 'get',
                update : 'add_itemtomylist_container',

                onSuccess : function () {
                    Allthat.Widget.Popup.create(additemLink, {
                        uniqueId : 'add_to_' + queryId+'_link',
                        targetId : 'additem_towishlist_outer',
                        toggleSelector : '.wishlist .addto_list',
                        closeSelector : '#additem_towishlist_outer .close',
                        topOffset : 10,
                        leftOffset : -140,
                        clickClose : false,
                        relativeOffset : true,
                        group : 'add'
                    });
                }
            }).send();
        },

        /**
	 * Add new query and load it into result list
	 * @method saveInline
	 * @param wishlistId {Number} id of the current wishlist
	 * @param queryId {Number} id of the query (if we edit it). Can be null
	 * @param formId {String} html elemen id of the form (used to collect form fields values)
	 * @param advanced {Boolean}
	 */
        saveInline : function (wishlistId, queryId, queryText, checked, minPrice, maxPrice) {
				
            url = (queryId) ? '/queries/update/' + queryId : '/queries/create';

            $('saving_query').setStyle('display', 'block');
    
            new Request({
                url : url,
                method : 'post',
                onSuccess : function (transport) {
                    Allthat.Entity.Query.update(wishlistId, transport);
                    Allthat.Entity.Query.updateStatus(transport);
    
                    $('saving_query').setStyle('display', 'none');
                },
                onFailure : function (transport) {
                    $('saving_query').setStyle('display', 'none');
                    //$('add_item_textbox').set('value', '');
                    if (transport[0] == 'query_limit_reached') {
                        alert("Oops! You have reached your limit of 100 items. Please delete some items before adding new ones.");
                    } else {
                        alert('There was a problem saving this item to your wishlist.');
                    }
                }
            }).send('query[query_text]=' + encodeURIComponent(queryText) + '&query[min_price]=' + minPrice + '&query[max_price]=' + maxPrice + '&wishlist=' + wishlistId + '&id=' + queryId + '&post_wall=' + checked);
        },

        /**
        * cancel editing the query
        */
        cancel : function (queryId) {
            var query = $('query_' + queryId);
            var priceRange = query.getElement('#price_range_' + queryId);
            var minMaxText = priceRange.getElements('span');
            minMaxText.setStyle('display', 'inline');

            var edit = $('edit_' + queryId);
            edit.setStyle('display', 'none');
            
//            query.getElement('.fifth .green').setStyle('padding-top', '5px')
            var editLink = $('edit_' + queryId + '_link');
            editLink.setStyle('display', 'inline');

            var queryText = query.getElement('.bluebold .results_toggle');
            queryText.setStyle('display', 'inline');

            var inputs = query.getElements('input:not([type="submit"])');
            inputs.setStyle('display', 'none');

            var text = $('note_text_' + queryId);
            text.setStyle('display', 'inline');

            var results = query.getElement('#view_' + queryId);
            results.setStyle('display', 'inline');
        },
        /**
        * Delete query from wishlist and hide appropriate div. I wish I could name it "delete", but delete is reserved word.
        * @method destroy
        */
        destroy : function (queryId, wishlist_id) {
            new Request({
                url : '/queries/' + queryId,
                method : 'delete',
                onSuccess : function () {
                    $('query_row_' + queryId).destroy();
                    toggleStatus[queryId] = ""
            
                    // Show the user ed text if all items are deleted
                    if (jQuery('.wishlist .query_item').length == 0) {
                        Allthat.showUserEdText();
                    }
                    var popup = Allthat.Widget.Popup.POPUPS['results_' + queryId];
                    if (popup) {
                        popup.hide();
                    }
                },
                onFailure: function(transport){
                    alert('Could not delete query.');
                }
            }).send();
        },
        
        /**
    * request from server status of the item query every three seconds till server respond "up_to_date"
    * @method updateStatus
    * @param queryId {Number} id of the query
    */
        updateStatus : function (queryId) {
            var updater = setInterval(function () {
                new Request.JSON({
                    update : 'items',
                    url : '/queries/' + queryId + '/query_status' + '?UUID=' + Allthat.generateUUID(),
                    method : 'get',
                    onSuccess : function (response) {
                        var query_status = response.query_status,
                        query_id = response.query_id,
                        num_items = response.num_items,
                        num_new_items = response.num_new_items,
                        image_uri = response.image_uri,
                        price_range = response.price_range;
                        $('price_range_' + query_id).set('html', price_range);

                        if (image_uri) {
                            $('query_img_' + query_id).setProperty('src', image_uri);
                        } else {
                            $('query_img_' + query_id).setProperty('src', '/images/no-image.gif');
                        }

                        if (query_status == 1) {
                            $('results_count_' + query_id).set('html', num_items + " results");
                            $('query_img_' + query_id).setProperty('src', image_uri);
                            $clear(updater);
                            Allthat.Entity.Query.setLoaded(query_id, num_items);
                            $('new_items_'+query_id).set('html', num_items + " results");
                            var size = num_new_items.toString().length*5+40;
                            $('new_items_'+query_id).setStyle('width', size);
                        } else {
                            $('results_count_' + query_id).set('html', "finding results (" + num_items + " so far)");
                        }
                    }/*,
          onFailure : function(response) {alert('/queries/' + queryId + '/query_status' + '?UUID=' + Allthat.generateUUID());}*/
                }).send();
            }, 3000); // run updater every three seconds
        }
    });
    
})();
