var ProgramSearch = {
	_xhr: new Request({
		url: '/program/search',
		//url: '/frontend_dev.php/program/search',
		link: 'cancel',
		method: 'get',
		onRequest: function () {
			var html = '<div id="content"><p class="loading"><img src="/images/ajax-loader.gif" alt="" />Loading...</p></div>';
			document.id('searchresults').set('html', html);
		},
		onComplete: function (html) {
			document.id('searchresults').set('html', html);
			setSearchResultBehaviours();
		}
	}),

	_timeout: undefined,
	_submitBtn: undefined,
	_timeoutDuration: 1000,

	init: function () {
		if (!document.id('program-search')) return;

		$$('#program-search li').addEvent('click', function (e) {
			var elm = $(this);
			var activeOptions;

			if(elm.hasClass('more') == true) {
				// er is op more geklikt
				return;
			}

			if(elm.hasClass('more') == false && elm.getParent().hasClass('group program')) {
				// andere knop in menu geklikt
				var menuElement = elm;
				var spanElement = menuElement.getElement('span');
				// dit is de knop waarop is geklikt: spanElement.data
				var moreElement = menuElement.getParent().getElementById('more_button');

				if(moreElement){
					// terugzetten naar oude 'More' label
					var moreSpanElement = moreElement.getElement('span');
					moreSpanElement.innerHTML = 'More';
				}
				
			}

			if(elm.getParent().getParent().hasClass('more') == true) {
				e.stopPropagation();

				// dit betekent dat iemand iets uit de dropdown van More selecteert
				var moreElement = elm.getParent().getParent();
				var spanElement = moreElement.getElement('span');
				var test = elm.getFirst();
				
				if(elm.getFirst().get( 'text' ) != spanElement.get( 'text' )){
					// indien nog niet actief => activeer menu item
					spanElement.innerHTML = elm.getFirst().get( 'text' );
					// activeer more button in menu
					
					$$('#dashboard ul.program li.active')[0].removeClass('active');
					moreElement.addClass('active');
					
					//remove active dropdown item
					var dropdowns = $$('#dashboard ul.program li.dropdown');
					for(var i = 0; i < dropdowns.length; i++) {
						if(dropdowns[i].hasClass('active')) dropdowns[i].removeClass('active');
					}
					// toon uitklap menu niet meer
					//$$('#program-search .more ol').setStyle('display', 'none');
				}
			}

			//if this is a click on the foldout <li>
			if (elm.hasClass('keywords') || elm.hasClass('locations')) {
				elm.getPrevious().removeClass('active');
				elm.addClass('active');
			} else {
				ProgramSearch.toggle(this);
			}

			if (elm.getParent().getParent().hasClass('foldout')) {
				activeOptions = elm.getParent().getParent().getElements('li.active span');
				elm.getParent().getParent().getPrevious().getPrevious().set('text', activeOptions.get('text').join(', '));

        // if the field listing the keywords or locations is empty
				if (elm.getParent().getParent().getSiblings()[0].get('text') == '') {
					if (elm.getParent().getParent().getParent().hasClass('locations')) {
						ProgramSearch.deselectAll('locations');
						$$('#program-search li.locations').removeClass('active');
						$$('#program-search li.locations')[0].getPrevious().addClass('active');
					} else {
						ProgramSearch.deselectAll('keywords');
						$$('#program-search li.keywords').removeClass('active');
						$$('#program-search li.keywords')[0].getPrevious().addClass('active');
					}

					e.stop();
				}
			}

			if (elm.getNext()) {
				//if this is a click on a 'no keywords' or 'no locations' <li>
				if (elm.getNext().hasClass('keywords') || elm.getNext().hasClass('locations')) {
					var deselectWhat = elm.getNext().hasClass('keywords') ? 'keywords' : 'locations';
					ProgramSearch.deselectAll(deselectWhat);
				}
			}

			if ($(e.target).get('tag') != 'button' && elm.getParent().getParent().hasClass('more') == false) {
				// en niet de more knop
				ProgramSearch._submitBtn.addClass('active');
			}
		});

		//do a search on <enter> on the textfield and <click> on the button
		ProgramSearch._submitBtn = $$('#program-search button')[0];

		ProgramSearch._submitBtn.addEvent('click', function (e) {
			ProgramSearch.doSearch();
		});

		$$('#program-search input[type=text]').addEvent('keyup', function (e) {
      var inputField = $(this),
          clearBtn = inputField.getSiblings('.clear')[0],
          submitBtn = inputField.getSiblings('button')[0];

			if (e.key == 'enter') {
				ProgramSearch.doSearch();
			} else {
				window.clearTimeout(ProgramSearch._timeout);
				ProgramSearch._timeout = window.setTimeout(ProgramSearch.doSearch, ProgramSearch._timeoutDuration);
			}

      if (inputField.get('value') != '') {
        inputField.addClass('notempty');
        clearBtn.setStyle('display', '');
        submitBtn.setStyle('display', 'none');

      } else {
        inputField.removeClass('notempty');
        clearBtn.setStyle('display', 'none');
        submitBtn.setStyle('display', '');
      }
		});

		$$('#program-search input[type=text]').addEvent('click', function (e) {
			e.stopPropagation();
		});

    $$('#program-search .freesearch .clear')[0].addEvent('click', function (e) {
      var clearBtn = $(this),
          input = clearBtn.getSiblings('input')[0],
          submitBtn = clearBtn.getSiblings('button')[0];

      clearBtn.setStyle('display', 'none');
      submitBtn.setStyle('display', '');
      input.set('value', '');
      input.removeClass('notempty');

      e.stopPropagation();
    });

    var inputField = $$('#program-search .freesearch input')[0];
    if (inputField.get('value') == '') {
      inputField.getSiblings('.clear').setStyle('display', 'none');
    } else {
      inputField.getSiblings('button').setStyle('display', 'none');
      inputField.addClass('notempty');
    }

		$$('li.locations > span', 'li.keywords > span').addEvent('click', function (e) {
      var elm = $(this);

      if (elm.hasClass('clear')) {
        if (elm.getParent().hasClass('keywords')) {
          ProgramSearch.deselectAll('keywords');
        } else {
          ProgramSearch.deselectAll('locations');
        }
        elm.getPrevious().addClass('active');
      } else {
        elm.getParent().getElement('div').toggleClass('show');
      }
			e.stop();
		});

		$$('li.locations > div', 'li.keywords > div').addEvent('mouseleave', function (e) {
			this.toggleClass('show');
		});

		//if the URL contains a hashstring do a search immediatly and set the right <li> elements active
		if (document.location.href.split('#')[1] != undefined) {
			var queryString = document.location.href.split('#')[1];
	  		ProgramSearch.setButtonsActive(queryString);
	  		ProgramSearch.doSearch(queryString);
	  } else {
			ProgramSearch.doSearch();
		}
	},

	//deselect all keywords or locations
	deselectAll: function (section) {
		if (section != 'keywords' && section != 'locations')
			return;
    
    if (section == 'keywords') 
      var label = 'Click to select styles...';
    else   
		  var label = 'Click to add ' + section + '...';

		$$('#program-search li.' + section, '#program-search li.' + section + ' li.active').removeClass('active');
		$$('#program-search li.' + section + '> span:first-child').set('text', label);
	},

	//toggle a selection item active or inactive
	toggle: function (elm, options) {
	  var options = options || {'forceActive': false, 'forceInactive': false, 'doSearch': true};

		if (elm.getParent().getPrevious() && elm.getParent().getPrevious().get('tag') == 'h2') {
		  if (options.forceActive  && options.forceActive === true) {
        elm.getParent().getElements('li.active').addClass('active');
      } else if (options.forceActive  && options.forceInactive === true) {
        elm.getParent().getElements('li.active').removeClass('active');
      } else {
        elm.getParent().getElements('li.active').toggleClass('active');
      }
    }

    if (options.forceActive  && options.forceActive === true) {
      elm.addClass('active');
    } else if (options.forceActive  && options.forceInactive === true) {
      elm.removeClass('active');
    } else {
      elm.toggleClass('active');
    }

    if (options.doSearch && options.doSearch === true) {
      window.clearTimeout(ProgramSearch._timeout);
      ProgramSearch._timeout = window.setTimeout(ProgramSearch.doSearch, ProgramSearch._timeoutDuration);
	 	}
	},

	doSearch: function (queryString) {
		if (!queryString || typeof queryString !== 'string') {
			var locations = new Array();
			$$('#dashboard ul.locations > li.active div li.active').each(function (el) {
				locations.push(el.get('data-slug'));
			});

			var keywords = new Array();
			$$('#dashboard ul.keywords > li.active div li.active').each(function (el) {
				keywords.push(el.get('data-slug'));
			});
			
			var program = $$('#dashboard ul.program li.active')[0].get('data-slug'); 
			//zodra het om het uitklap menutje van more gaat dan ophalen wie welk more event geselecteerd is
			if(program == 'more') {
				var dropdownElement = $$('#more_button li.active')[0].get('data-slug');
				program = dropdownElement; 
			}
			
			var parameters = {
				program: program,
				days: $$('#dashboard ul.days li.active')[0].get('data-slug'),
				sorting: $$('#dashboard ul.sort_on li.active')[0].get('data-slug'),
				locations: locations,
				keywords: keywords,
				query: document.id('program-search-term').get('value')
			}

			queryString = (new Hash(parameters)).toQueryString()
		}

		var prettyString = '';

    if (queryString.indexOf('&') > -1) {
  		var paramValues = queryString.split('&');
  		paramValues.each(function (paramValue) {
  			var keyValue = paramValue.split('=');
  
  			if (keyValue[0] && keyValue[1]) {
  				prettyString += '/' + keyValue[0] + '/' + keyValue[1];
  			}
  		});
    } else {
      prettyString = queryString;
    }

		document.location.href = '#' + prettyString;

		ProgramSearch._xhr.get(ProgramSearch._xhr.options.url + prettyString);
		ProgramSearch._submitBtn.removeClass('active');
	},

	setButtonsActive: function (queryString) {
		//element collections
		var daysLis     = $$('#program-search ul.days li');
		var programLis  = $$('#program-search ul.program li');
		var sortingLis  = $$('#program-search ul.sort_on li');
		var searchInput = $$('#program-search input');
		var keywordLis  = $$('#program-search ul.keywords li');
		var locationLis = $$('#program-search ul.locations li');

    //ff snelle hack, maak van pretty querystring nasty querystring
    if (queryString.indexOf('&') == -1 && queryString.indexOf('/') > -1) {
      var urlParts = queryString.split('/'),
          offset = 0, nastyQueryString = '';

      if (urlParts[0] == '') {
        offset = 1;
      }

      for (var i=offset; i<urlParts.length; i+=2) {
        if (nastyQueryString != '') {
          nastyQueryString += '&';
        }

        nastyQueryString += urlParts[i] + '=' + urlParts[i+1];
      }

      queryString = nastyQueryString;
    }

		//the different parameters
		var keywords  = new Array()
		var locations = new Array();

    var toggleOptions = {'forceActive': true, 'doSearch': false}

		//split the querystring in an array with key/value pairs as string
		var keyValuePairs = decodeURIComponent(queryString).split('&');
		keyValuePairs.each(function (el) {
			if (el == '') return;

			var key   = el.split('=')[0];
			var value = el.split('=')[1];

			if (key.match(/^locations/)) {
				locationLis.each(function (li) {
					if (li.get('data-slug') == value) {
						ProgramSearch.toggle(li, toggleOptions);
					}

					if (!li.getParent().getParent().getParent().hasClass('active'))
						ProgramSearch.toggle(li.getParent().getParent().getParent());
				});

				locations.push(value);

			} else if (key.match(/^keywords/)) {
				keywordLis.each(function (li) {
					if (li.get('data-slug') == value) {
						ProgramSearch.toggle(li, toggleOptions);
					}

					if (!li.getParent().getParent().getParent().hasClass('active'))
						ProgramSearch.toggle(li.getParent().getParent().getParent());
				});

				keywords.push(value);

			} else if (key == 'days') {
				daysLis.each(function (li) {
					if (li.get('data-slug') == value) {
						ProgramSearch.toggle(li, toggleOptions);
					}
				});

			} else if (key == 'program') {
				programLis.each(function (li) {
					if (li.get('data-slug') == value) {
						ProgramSearch.toggle(li, toggleOptions);
					}
				});

      } else if (key == 'sort_on') {
        sortingLis.each(function (li) {
          if (li.get('data-slug') == value) {
            ProgramSearch.toggle(li, toggleOptions);
          }
        });

			} else if (key == 'query') {
				searchInput.set('value', value);
			}
		});

		if (locations.length > 0)
			$$('#program-search ul.locations li.locations > span:first-child').set('text', locations.join(', '));

		if (keywords.length > 0)
			$$('#program-search ul.keywords li.keywords > span:first-child').set('text', keywords.join(', '));
	}
}

window.addEvent('domready', ProgramSearch.init.bind(ProgramSearch));
window.addEvent('domready', function(){
	$$('#more_button').addEvent('mouseover', function () {
		$$('#more_button .dropdown_icon').setStyle('background-position', '-26px 0px');
	});
	$$('#more_button').addEvent('mouseout', function () {
		$$('#more_button .dropdown_icon').setStyle('background-position', '0px 0px');
	});
	
});
