/**
 * Application front-end controller class
 *
 * @author Akiva Levy <akiva@sixthirteendesign.com>
 * @version 0.0.1
 */

var app = {

  /**
   * Common JS actions for every page
   */

	common: {

    /**
     * Initialize function, called prior to any other action for every page 
     * load
     */

		init: function () {
			// ...
		},

    /**
     * Finalize method triggered after every other action
     */

		finalize: function () {
			// ...
		}

	},

  /**
   * Search page controller
   */

	search: {

    /**
     * Initialize
     */

		init: function () {

      /**
       * Custom common selector for autocomplete text matching
       * Used to enhance jQuery UI autocomplete
       */

      /*
      $.expr[':'].textEquals = function (a, i, m) {
        return $(a).text().match("^" + m[3] + "$");
      };
      */

      /**
       * Events for dynamic movie search form filters
       */

      $('#filtersForm')
        .delegate('#filtersList', 'adjustNames', function (e) {
          // adjustName event, used to update each form filters name attr
          $(e.target).children('li').each(function (i, el) {
            $(el).attr('data-filter-item', i)
              .children('[name]')
                .each(function () {
                  // Check for an existing array key within the name field
                  // If present, remove and reapply
                  var el = $(this),
                      elName = el.attr('name'),
                      elParentDataId = el.closest('li')
                        .attr('data-filter-item');
                  el.attr(
                    'name', 
                    elName.replace(
                      /filters[[\d]+]/, 
                      'filters[' + elParentDataId + ']'
                    )
                  );
                })
              .end();
          });
        })
        .delegate('#addFilterButton', 'click', function () {
          // When the add filter button has been clicked, add a new
          // list item to the form, with a cloned filter from the templates 
          // for the user to interact with
          var filterItem = $('<li>')
            .addClass('filterItem')
            .appendTo('#filtersList');
          // Clone from template and append to the new filter div
          $('div.template.filterChooser')
            .children()
            .clone()
            .appendTo(filterItem);
          $('#filtersList').trigger('adjustNames');
        })
        .delegate('select.filterChooser', 'change', function () {
          // When the filter chooser has been changed, insert the 
          // appropriate qualifiers via cloning from the templates
          var filterType = $(':selected', this).attr('data-filter-type');
          var filterItem = $(this).closest('.filterItem');
          $('.qualifier', filterItem).remove();
          $('div.template.' + filterType)
            .children()
            .clone()
            .addClass('qualifier')
            .appendTo(filterItem);
          $('#filtersList').trigger('adjustNames');
          // If the new filter is one of the autocompleting filters (actor, 
          // director, country, keyword), trigger the autosuggest on the item
          /*
          if (/^keywordChooser|countryChooser$/.test(filterType)) {
            var container = $(this).closest('li');
            $(this).next().autocomplete({
              source: "/keywords.json",
              minLength: 1,
              delay: 200,
              appendTo: container,
              // position: { 
              //   my: "left top", 
              //   at: "left bottom", 
              //   collision: "none" 
              // },
              create: function (event, ui) {
                // console.log('Created!');
              },
              //search: function (event, ui) {},
              //open: function (event, ui) {},
              //focus: function (event, ui) {},
              //close: function (event, ui) {},
              change: function (event, ui) {
                // If the value of the textbox does not match a suggestion, 
                // clear its value
                if ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0) {
                  alert('IN');
                  $(this).val('');
                }
              },
              select: function (event, ui) {
                console.log(
                  ui.item ?
                  "Selected: " + ui.item.value :
                  "Nothing selected, input was " + this.value 
                );
              }
            })
            .keypress(function (e) {
              var keyCode = e.keyCode || e.which;
              // If TAB or RETURN is pressed and the text in the textbox does 
              // not match a suggestion, set the value of the textbox to the 
              // text of the first suggestion
              if ((keyCode == 9 || keyCode == 13) 
                  && ($(".ui-autocomplete li:textEquals('" + $(this).val() + "')").size() == 0)
                 ) {
                console.log('Search term did not find matching keywords, text has been reset');
                $(this)
                  .val($(".ui-autocomplete li:visible:first").text());
              }
            });
          }
          */
          $('option[value=""]', this).remove();
        })
        .delegate('button.filterRemover', 'click', function () {
          // Remove filter list item when X button is clicked
          $(this).closest('li.filterItem').remove();
          $('#filtersList').trigger('adjustNames');
        });
     
      /**
       * Form submission processing via XHR
       */

      $('#filtersForm').submit(function () {
        $.post(
          '/search/',
          $(this).formParams(),
          function (data, textStatus, jqXHR) {
            var resultsList = '<ul>';
            $(data).each(function (i, record) {
              resultsList += '<li>';
              var coverFound = false;
              $(record.posters).each(function (i, poster) {
                if (poster.image.size === 'thumb') {
                  resultsList += '<img src="' + poster.image.url + '" height="' + poster.image.height + '" width="' + poster.image.width + '" alt="' + record.name + '" />';
                  coverFound = true;
                  return false;
                }
              });
              if (!coverFound) {
                resultsList += '<img src="#" height="138" width="92" alt="' + record.name + '" />';
              }
              resultsList += record.name;
              resultsList += '</li>';
            });
            $('#resultsPane').html(resultsList);
          }
        );
        return false;
      });
     
      // Trigger an add filter button click event upon document ready
      $('#addFilterButton').click();
      
    }   
	}
};

/**
 * Utility class used to boostrap and trigger application
 */

var UTIL = {
	
  /**
   * Method used to fire the appropriate event (triggered via UTIL#loadEvents)
   */

	fire: function (func, funcname, args) {
		var namespace = app;
		funcname = (funcname === undefined) ? 'init' : funcname;

		if (func !== '' && namespace[func] && 
        typeof namespace[func][funcname] === 'function') {
			namespace[func][funcname](args);
		} 
	}, 
	
  /**
   * Method used to trigger the common events, as well as the current page 
   * events (based on the body ID attribute)
   */

	loadEvents: function () {
		var bodyId = document.body.id;
		UTIL.fire('common');
		UTIL.fire(bodyId);
		$.each(document.body.className.split(/\s+/), function (i, classnm) {
			UTIL.fire(bodyId, classnm);
		});
		UTIL.fire('common', 'finalize');
	}

};
 
// Execute boostrap

$(document).ready(UTIL.loadEvents);

