function tu(name) {
	var textunits = global.get('tu');
	var text = textunits[name];

	if (text === undefined) {
		return name + " not defined in textUnit literal";
	} else {
		return text.unescapeHTML();
	}
}

var ArtistSearchPages = Class.create({
	initialize: function () {
		this.current = 1;
		this.prev = 0;
		this.next = 2;
		this.stack = $A();
		this.types = $A();
		this.total_docs = search_data.get('total');
		this.total_real_docs = search_data.get('total_docs');
		this.page_max = global.get('page_max');
		this.total_pages = Math.ceil(this.total_docs / this.page_max);

		if (this.total_pages > 1) {
			$w('national international').each(function (d) {
				if (search_data.get(d).docs.length) {
					this.types.push(d);
				}
				for (i = 0; i < search_data.get(d).numFound; i++) {
					this.stack.push(d + ':' + i);
				}
			}.bind(this));
			this.stack = this.stack.eachSlice(this.page_max);
			this.stack.splice(0, 0, undefined);
			this.drawPageNav();
		}
		else {
			$w('national international').each(function (d) {
				if (search_data.get(d).docs.length) {
					this.types.push(d);
				}
			}.bind(this));
			$('pages_count').update(' <strong>Results ' + '1-' + this.total_docs + ' ' + tu("OF_PAGINATION") + ' ' + this.total_docs + '</strong>');
		}
	},

	drawPageNav: function () {
		var output = '';
		var prevB = ' &nbsp;&nbsp; <a href="" onclick="browselib.prevPage(); return false;"><img src="/theme/common/image/prev.gif" /></a> &nbsp;&nbsp;';
		var nextB = '&nbsp;&nbsp;<a href="" onclick="browselib.nextPage(); return false;"><img src="/theme/common/image/next.gif" /></a>';

		output += '<strong>' + tu("RESULTS_PAGINATION") + ': ';
		if (this.prev > 0) {
			output += prevB;
		}
		output += ((this.current - 1) * this.page_max + 1) + ' - ';
		if (this.current != this.total_pages) {
			output += (this.page_max * this.current);
		}
		else {
			output += this.total_docs;
		}
		output += ' ' + tu("OF_PAGINATION") + ' ' + this.total_docs + '</strong>';
		if (this.next <= this.total_pages) {
			output += nextB;
		}
		$('pages_count').update(output);
	},

	nextPage: function () {
		if (this.next <= this.total_pages) {
			this.prev = this.current;
			this.current = this.next;
			this.next++;
			return true;
		}
		else {
			return false;
		}
	},
	prevPage: function () {
		if (this.prev > 0) {
			this.prev--;
			this.current--;
			this.next--;
			return true;
		}
		else {
			return false;
		}
	},
	xPage: function (pos) {
		this.current = pos;
		this.prev = pos - 1;
		this.next = pos + 1;
		return true;
	}
});


var BrowseEventList = Class.create({
	initialize: function () {
		this.pages = arguments[0];
	},
	drawEvents: function () {
		$('browse_results_tbl').hide();
		$('no_browse_msg').hide();
		$('browse_results').childElements().reject(function (e) {
			return e.id == 'browse_hdr';
		}).invoke('remove');

		if (browse_data.get('total') > 0) {
			if (this.pages.stack.length) {
				// we have multiple pages, build the current one
				var current = this.pages.stack[global.get('pages').current];
				current.each(function (p, idx) {
					var tmp = p.split(':');
					this.buildEvents(browse_data.get(tmp[0]).docs[tmp[1]], tmp[0], idx);
				}.bind(this));
			}
			else {
				//no pages, just build 'em all
				$w('browse').each(function (s) {
					browse_data.get(s).docs.each(function (d, idx) {
						this.buildEvents(d, s, idx);
					}.bind(this));
				}.bind(this));
			}
		}
		else {
			$('loading').hide();
			$('no_browse_msg').show();
			$('category_name').setStyle({
				color: '#424242'
			});
			browselib.showBrowseDivs();
		}
	},

	buildEvents: function (d, type, idx) {
		var r = new Element('tr');
		$w('event location date more').each(function (c) {
			var td = new Element('td', {
				'class': c
			});
			var div = new Element('div', {
				'class': 'pad510'
			});

			var popup;

			switch (c) {
			case 'event':
				var act = '';
				var event_link = '';
				if (d.AttractionSEOLink && !(d.AttractionSEOLink.first().empty())) {
					event_link = d.AttractionSEOLink.first();
				}
				else {
					event_link = d.CheckoutURL;
				}
				if (d.ExternalRedirect && (global.get('crossSiteNewWindow'))) {
					popup = 'target="_blank"';
				}

				act = '<a href="' + event_link + '"' + popup + '>' + d.EventName + '</a>';
				div.innerHTML = act;
				break;

			case 'location':
				div.innerHTML =  browselib.getLocation(d);
				break;

			case 'date':
				var date = '';
				var is_cancelled = '';
				if (d.Canceled) {
					is_cancelled = '<span class="errorMessage">' + tu("EVENT_IS_CANCELLED") + '</span><br/>';
				}
				if (d.LocalEventDateDisplay && !d.LocalEventDateDisplay.empty()) {
					date += is_cancelled + d.LocalEventDateDisplay;
				}
				else {
					date += is_cancelled + '<br/>' + tu("NO_DATES_AVAILABLE");
				}
				
				if(date == "undefined")
					date= tu("NO_DATES");
				
				div.innerHTML = date;
				break;

			default:
				popup = false;
				if (d.ExternalRedirect && (global.get('crossSiteNewWindow'))) {
					popup = true;
				}
				var link = browselib.purchaseLink(d.CheckoutURL, d.VisibilityStatus, popup);
				div.innerHTML = link;
				div.addClassName('checkoutSearch');
			}
			if (c != 'pic') {
				td.appendChild(div);
			}
			r.appendChild(td);
		});
		$('loading').hide();
		$('browse_results').appendChild(r);
		$('browse_results').show();
		$('browse_results_tbl').show();
		$('category_name').setStyle({
			color: '#424242'
		});

		browselib.showBrowseDivs();
	}
});


var BrowsePages = Class.create({
	initialize: function () {
		this.current = 1;
		this.prev = 0;
		this.next = 2;
		this.stack = $A();
		this.total_docs = browse_data.get('total');
		this.total_real_docs = browse_data.get('total_docs');
		this.page_max = global.get('page_max');
		this.total_pages = Math.ceil(this.total_real_docs / this.page_max);
		if (this.total_docs > 0) {
			if (this.total_pages > 1) {
				var i;
				for (i = 0; i < this.total_real_docs; i++) {
					this.stack.push('browse' + ':' + i);
				}
				this.stack = this.stack.eachSlice(this.page_max);
				this.stack.splice(0, 0, undefined);
				this.drawPageNav();
				$('top_nav', 'btm_nav').invoke('show');
			}
			else {
				var tmp = '1-' + this.total_docs + ' ' + tu("OF_PAGINATION") + ' ' + this.total_docs;
				$('top_nav', 'btm_nav').invoke('update', tmp);
				$('top_nav', 'btm_nav').invoke('show');

			}
		}
		else {
			$('top_nav').hide();
			$('btm_nav').hide();
		}

		$('browse_total').update('(' + this.total_docs + ')');

	},

	drawPageNav: function () {
		var output = '';
		var prevB = '<a href="" onclick="browselib.prevPage(); return false;" class="prev">' + tu("PREV") + '</a>&nbsp;&nbsp;|&nbsp;&nbsp;';
		var nextB = '&nbsp;&nbsp;|&nbsp;&nbsp;<a href="" onclick = "browselib.nextPage(); return false;" class="more">' + tu("NEXT") + '</a>';

		if (this.prev > 0) {
			output += prevB;
		}
		output += ((this.current - 1) * this.page_max + 1) + ' - ';
		if (this.current != this.total_pages) {
			output += (this.page_max * this.current);
		}
		else {
			output += this.total_real_docs;
		}
		output += ' ' + tu("OF_PAGINATION") + ' ' + this.total_real_docs;
		if (this.next <= this.total_pages) {
			output += nextB;
		}
		$('top_nav', 'btm_nav').invoke('update', output);

	},

	nextPage: function () {
		if (this.next <= this.total_pages) {
			this.prev = this.current;
			this.current = this.next;
			this.next++;
			return true;
		}
		else {
			return false;
		}
	},
	prevPage: function () {
		if (this.prev > 0) {
			this.prev--;
			this.current--;
			this.next--;
			return true;
		}
		else {
			return false;
		}
	},
	xPage: function (pos) {
		this.current = pos;
		this.prev = pos - 1;
		this.next = pos + 1;
		return true;
	}
});

var BrowseHisto = Class.create({

	initialize: function () {
		var cat_id = browse_data.get('cat_id');
		if (cat_id == 10001) {
			this.genre_list = arguments[0].MusicBrowseGenre;
		}
		if (cat_id == 10002) {
			this.genre_list = arguments[0].ArtsBrowseGenre;
		}
		if (cat_id == 10003) {
			this.genre_list = arguments[0].FamilyBrowseGenre;
		}
		if (cat_id == 10004) {
			this.genre_list = arguments[0].SportsBrowseGenre;
		}
		if (cat_id == 10101) {
			this.genre_list = arguments[0].FestivalsBrowseGenre;
		}
		if (cat_id == 10102) {
			this.genre_list = arguments[0].ComedyBrowseGenre;
		}
		
		if (cat_id == 0) {
			this.genre_list = arguments[0].MusicBrowseGenre;
			
			var that = this;
			
			if (arguments[0].SportsBrowseGenre) {
				arguments[0].SportsBrowseGenre.each(function(i){
					that.genre_list.push(i);			
				});
			}
			
			if (arguments[0].ArtsBrowseGenre) {
				arguments[0].ArtsBrowseGenre.each(function(i){
					that.genre_list.push(i);			
				});
			}
			
			if (arguments[0].FamilyBrowseGenre) {
				arguments[0].FamilyBrowseGenre.each(function(i){
					that.genre_list.push(i);			
				});
			}
			
			if (arguments[0].FestivalsBrowseGenre) {
				arguments[0].FestivalsBrowseGenre.each(function(i){
					that.genre_list.push(i);			
				});
			}

			if (arguments[0].ComedyBrowseGenre) {
				arguments[0].ComedyBrowseGenre.each(function(i){
					that.genre_list.push(i);			
				});
			}
		}

		this.active_cat_name = browselib.getMinorCat();

	},

	drawHisto: function () {
		var tmp;
		
		if (this.genre_list.length) {
			if ($('histo_list')) {
				$('histo_list').innerHTML = '';
			}
			tmp = this._make_list(this.genre_list);
			if ($('histo_list')) {
				$('histo_list').insert({
					'bottom': tmp
				});
			}
		}
		else {
			if ($('histo_list')) {
				$('histo_list').innerHTML = '';
			}
			tmp = this._make_list(this.genre_list);
			if ($('histo_list')) {
				$('histo_list').insert({
					'bottom': tmp
				});
			}
		}
	},

	_make_list: function (myList) {
		var t = new Template("<a href=\"\" onclick='browselib.browseHistoClick(\"#{value}\",\"#{value}\" ); return false;'>#{value} <span class=\"count\">(#{count})</span></a>");
		var t_active = new Template("<a href=\"\" onclick='browselib.browseHistoClick(\"#{value}\",\"#{value}\"); return false;'><strong>#{value} </strong><span class=\"count\">(#{count})</span></a>");
		var t_all = new Template("<a href=\"\" class=\"allCat\" onclick='browselib.browseHistoClick(\"#{value}\",\"#{value}\"); return false;'><strong>#{value} </strong><span class=\"count\">(#{count})</span></a>");
		var t_nc = new Template("#{value} <span class=\"count\">(#{count})</span></a><br/>");
		var t_broad = new Template("<a href=\"#{link}\">#{value}</a>");
		var output = '';
		var template;
		var i;
		
		if(window.browselib.getAllBrowse()) {
			var allCount =browse_data.get("numFound");	
			var allCategoryName = browse_data.get("allCategory");
			output += "<a href=\"\" onclick='browselib.browseHistoClick(\"\",\"\"); return false;'><strong>"+allCategoryName+" </strong><span class=\"count\">("+allCount+")</span></a>";
		}else {
			var allCategoryName = browse_data.get("allCategory");
			var allCount = browse_data.get("allCat");
			output += "<a class=\"allCatTop\" href=\"\" onclick='browselib.allBrowseHistoClick(); return false;'>"+allCategoryName+"<span class=\"count\">("+allCount+")</span></a>";
			
		}
		
		for (i = 0; i < myList.length; i++) {

			if (myList[i + 1] > 0) {
				if (this.active_cat_name == myList[i]) {
					template = t_active;
					active = true;
				}
				else {
					template = t;
				}
			}
			else {
				template = t_nc;
			}
			
			if(window.browselib.getAllBrowse()) {
				
				for (var j=0;j<allCategories.length;j++) {
				     if (allCategories[j] == myList[i]) {
				    	 template = t_all;
				        break;
				     };
				  };	
			}
			
			output += template.evaluate({
				value: myList[i],
				count: myList[i + 1]
			});
			i++;
		}

		return output;
	}
});

//for search
var Histo = Class.create({
	initialize: function () {
		this.city_list = arguments[0].VenueCityCountry;
		this.category_list = arguments[0].MajorGenre;
		this.act_list = arguments[0].AttractionName;
		this.venue_list = arguments[0].VenueName;
		this.date_ranges = arguments[0].LocalEventMonthYear;

		if ($('DCSext.results_city')) {
			$('DCSext.results_city').content = this.city_list.length / 2;
		}

		if ($('DCSext.results_act')) {
			$('DCSext.results_act').content = this.act_list.length / 2;
		}

		if ($('DCSext.results_venue')) {
			$('DCSext.results_venue').content = this.venue_list.length / 2;
		}

		if ($('DCSext.results_date')) {
			$('DCSext.results_date').content = this.date_ranges.length / 2;
		}

		if ($('DCSext.results_category')) {
			$('DCSext.results_category').content = this.category_list.length / 2;
		}

	},
	drawHisto: function () {
		var facet_list = search_data.get('facets').join('');
		var hdr;
		var bdy;
		$('left-nav').hide();
		$('left-nav').childElements().reject(function (e) {
			return e.id == 'custom_date' || e.id == 'cl-lid' || e.id == 'cl-nav';
		}).invoke('remove');

		//Draw Filters
		if (this.city_list.length) {
			hdr = new Element('div', {
				'class': 'lid-nav'
			}).update(tu("CITY_FILTER_HEADER"));
			$('left-nav').insert({
				'bottom': hdr
			});
			bdy = new Element('div', {
				'class': 'container-nav',
				'id': 'nav-city'
			});
			this._make_list(this.city_list, 'c', bdy);
			$('left-nav').insert({
				'bottom': bdy
			});
		}

		if (this.category_list.length && (this.category_list.length > 3 || facet_list.include('g'))) {
			hdr = new Element('div', {
				'class': 'lid-nav'
			}).update(tu("CATEGORY_FILTER_HEADER"));
			$('left-nav').insert({
				'bottom': hdr
			});
			bdy = new Element('div', {
				'class': 'container-nav',
				'id': 'nav-category'
			});
			this._make_list(this.category_list, 'g', bdy);
			$('left-nav').insert({
				'bottom': bdy
			});
		}

		if (this.act_list.length) {
			hdr = new Element('div', {
				'class': 'lid-nav'
			}).update(tu("EVENT_FILTER_HEADER"));
			$('left-nav').insert({
				'bottom': hdr
			});
			bdy = new Element('div', {
				'class': 'container-nav',
				'id': 'nav-event'
			});
			this._make_list(this.act_list, 'a', bdy);
			$('left-nav').insert({
				'bottom': bdy
			});
		}

		if (this.venue_list.length) {
			hdr = new Element('div', {
				'class': 'lid-nav'
			}).update(tu("VENUE_FILTER_HEADER"));
			$('left-nav').insert({
				'bottom': hdr
			});
			bdy = new Element('div', {
				'class': 'container-nav',
				'id': 'nav-venue'
			});
			this._make_list(this.venue_list, 'v', bdy);
			$('left-nav').insert({
				'bottom': bdy
			});
		}

		if (this.date_ranges) {
			hdr = new Element('div', {
				'class': 'lid-nav'
			}).update(tu("DATE_RANGE_FILTER_HEADER"));
			if (this.date_ranges.length) {
				$('left-nav').insert({
					'bottom': hdr
				});
				bdy = new Element('div', {
					'class': 'container-nav mgBot1',
					'id': 'nav-date'
				});
				this._make_list(this.date_ranges, 'm', bdy, true);
				$('left-nav').insert({
					'bottom': bdy
				});
			}
			$('left-nav').insert({
				'bottom': $('custom_date').show()
			});
		}

		$('left-nav').show();

	},
	//Used to create the filterdisplay
	_make_list: function (myList, myParam, myElement, noCount) {
		var p_list = myList.partition(function (a) {
			return Object.isString(a);
		});
		var f_name = p_list[0];
		var f_count = p_list[1];
		var break_out;
		var f_output;
		var max_disp;
		var total_html = [];

		var facet = search_data.get('facets').find(function (n) {
			return n.split('=').first() == myParam;
		});
		if (facet) {
			f_output = '<a href="" class="hiLite" onclick="browselib.crumbPop(\'' + myParam + '\', true); return false;">[' + tu("ALL_FILTER") + ']</a>';
			break_out = true;
		}

		var div = [];
		var i;
		for (i = 0; i < f_name.length; i++) {
			var link_value = f_name[i].split("'").join("\'");
			
			if (i >= 8 && !max_disp) {
				max_disp = true;
				div.push('<div id="extra_' + myParam + '" style="display:none;">');
			}
			var a_link;
			if (facet) {
				a_link = noCount ? '<strong>' + f_name[i] + '</strong>' : '<strong>' + f_name[i] + ' <span class="count">(' + f_count[i] + ')</span></strong>';
			}
			else {
				if (f_name[i].include('&#39;')) {
					link_value = f_name[i].replace(/&#39;/g, '\\&#39;');
				}
				if (noCount) {
					a_link = '<a href="" onclick="browselib.updateSearch(\'' + myParam + '\',\'' + link_value + '\'); return false;">' + f_name[i] + '</a>';
				}
				else {
					if (f_name[i] == 'SEARCH_DIVIDER') {
						a_link = '<hr style="margin:3px 0;" />';
					}
					else {
						a_link = '<a href="" onclick="browselib.updateSearch(\'' + myParam + '\',\'' + link_value + '\'); return false;">' + f_name[i] + ' <span class="count"> (' + f_count[i] + ')</span></a>';
					}
				}
			}
			if (break_out) {
				var compare_txt = f_name[i];
				if (compare_txt.include('&#39;')) {
					compare_txt = compare_txt.replace(/&#39;/g, "'");
				}
				if (compare_txt.include('&#34;')) {
					compare_txt = compare_txt.replace(/&#34;/g, '"');
				}
				if (facet.split('=').last() == encodeURIComponent(compare_txt)) {
					total_html.push(f_output);
					total_html.push(a_link);

					break;
				}
				else {
					continue;
				}
			}
			else {
				if (max_disp) {
					div.push(a_link);
				}
				else {
					total_html.push(a_link);
				}
			}
		}
		if (max_disp) {
			div.push('</div>');
			var new_div = div.join('');
			total_html.push(new_div);
			total_html.push('<a href="" onclick="browselib.toggleFilter(\'extra_' + myParam + '\', this); return false;" class="more"><span class="more">' + tu("SEE_MORE_SEARCH") + '</span><span class="less">' + tu("SEE_LESS_SEARCH") + '</span></a>');
		}
		var to_html = total_html.join('');
		$(myElement).innerHTML = to_html;
	}
});


var ArtistEventList = Class.create({
	initialize: function () {
		this.pages = arguments[0];
	},
	drawEvents: function () {
		// add international
		$w('national international').each(function (d) {
			if ($('hdr_' + d)) {
				$('hdr_' + d).hide();
			}
			if ($('tbl_' + d)) {
				$('tbl_' + d).hide();
			}
			if ($('spc_' + d)) {
				$('spc_' + d).hide();
			}
			if ($('no_local_msg')) {
				$('no_local_msg').hide();
			}

			$('tbl_' + d).childElements().reject(function (e) {
				return e.id === 'row_' + d;
			}).invoke('remove');
		});
		if (this.pages.stack.length) {
			// we have multiple pages, build the current one
			var current = this.pages.stack[global.get('pages').current];
			current.each(function (p, idx) {
				var tmp = p.split(':');
				var data = search_data.get(tmp[0]).docs[tmp[1]];
				if (data) {
					this.buildEvents(data, tmp[0], idx);
				}
				else {
					new LightBox('modal', 'loading_lb').showContent();
					var set = global.get('set') + 1;
					getData({
						aid: global.get('aid'),
						set: set
					});
					global.set('set', set);
					throw $break;
				}
			}.bind(this));
			this.buildCounts(current);
			$('artist_list').show();
		}
		else if (search_data.get('total') === 0) {
			$('artist_list').hide();
			$('no_tickets').show();
			$('loading').hide();
		}
		else {
			//no pages, just build 'em all
			//add international
			$w('national international').each(function (s) {
				search_data.get(s).docs.each(function (d, idx) {
					this.buildEvents(d, s, idx);
				}.bind(this));
				if (global.get('pages').types.include(s)) {
					$('count_' + s).update('(' + search_data.get(s).docs.length + ')');
				}
			}.bind(this));
			$('artist_list').show();
		}
		browselib.noNational();
	},
	buildCounts: function (current) {
		var min = current.first().split(':');
		var max = current.last().split(':');
		min[1] = parseInt(min[1], 10) + 1;
		max[1] = parseInt(max[1], 10) + 1;
		if (min[0] === max[0]) {
			$('count_' + min[0]).update('(' + min[1] + ' - ' + max[1] + ' ' + tu("OF_PAGINATION") + ' ' + search_data.get(min[0]).numFound + ')');
		}
		else {
			var tmp_h = $H();
			current.each(function (c) {
				var key = c.split(':').first();
				tmp_h.set(key, []);

			});
			current.each(function (c) {
				var key = c.split(':').first();
				var val = c.split(':').last();
				var tmp_val = tmp_h.get(key);
				tmp_val.push(val.toString());
				tmp_h.set(key, tmp_val);
			});
			tmp_h.keys().each(function (k) {
				var tmp = tmp_h.get(k);
				var d_length = search_data.get(k).numFound;
				if (tmp.length == d_length) {
					$('count_' + k).update('(' + d_length + ')');
				}
				else {
					var min = parseInt(tmp_h.get(k).first(), 10) + 1;
					var max = parseInt(tmp_h.get(k).last(), 10) + 1;
					$('count_' + k).update('(' + min + ' - ' + max + ' ' + tu("OF_PAGINATION") + ' ' + d_length + ')');
				}
			});
		}
	},
	buildEvents: function (d, type, idx) {
		var r = new Element('tr');
		$w('date venue act info').each(function (c) {
			var td = new Element('td');
			var span = new Element('span');
			var popup;
			switch (c) {
			case 'date':
				td.setAttribute('id', 'divdateBlock');
				td.addClassName('dateBlock');
				var date = '';

				if (d.LocalEventShortMonth && !d.LocalEventShortMonth.empty()) {
					date += '<div class="month"><span class="dots">&#149;</span> ' + d.LocalEventShortMonth + ' <span class="dots">&#149;</span></div><div class="date">' + d.LocalEventDay + '</div><div class="day">' + d.LocalEventShortWeekday + '</div>';
				}
				else {
					date += '<img src="/theme/common/image/tba_date.gif">';
				}

				span.innerHTML = date;
				td.writeAttribute({
					'nowrap': 'nowrap'
				});
				break;

			case 'venue':
				var is_cancelled = '';

				if (d.Canceled) {
					is_cancelled = '<span class="errorMessage">' + tu('EVENT_IS_CANCELLED') + '</span><br/>';
				}
				if (d.VenueCity && !d.VenueCity.empty()) {
					var time_loc = '';
					if (d.LocalEventTimeDisplay && !d.LocalEventTimeDisplay.empty()) {
						time_loc += (d.LocalEventTimeDisplay && !d.LocalEventTimeDisplay.empty()) ? '' + d.LocalEventTimeDisplay : '';
					}

					popup = '';

					if (d.ExternalRedirect && (global.get('crossSiteNewWindow'))) {
						popup = 'target="_blank"';
					}

					var venue_loc = d.VenueCity + ', ' + d.VenueCountry;
					span.innerHTML = '<div class="padH10">' + is_cancelled + '<a href="' + d.VenueSEOLink + '"' + popup + '>' + d.VenueName + '</a><br/>' + venue_loc + '<br/>' + time_loc;
				}
				else {
					span.innerHTML = '<div class="padH10">' + is_cancelled + tu("NO_LOCATIONS") + '</div>';
				}

				td.addClassName('venue');
				break;
			case 'act':
				var my_link_text = d.EventName;
				span.innerHTML = my_link_text;
				td.addClassName('eventName');
				span.addClassName('eventName');
				break;
			default:
				popup = false;
				if (d.ExternalRedirect && (global.get('crossSiteNewWindow'))) {
					popup = true;
				}

				var link = browselib.purchaseLink(d.CheckoutURL, d.VisibilityStatus, popup);
				td.innerHTML = link;
				td.addClassName('findTix');

			}
			if (c != 'info') {
				td.appendChild(span);
			}
			r.appendChild(td);
		});
		$('tbl_' + type).appendChild(r);
		$('loading').hide();
		if ($('hdr_' + type)) {
			$('hdr_' + type).show();
		}
		if ($('tbl_' + type)) {
			$('tbl_' + type).show();
		}
		if ($('spc_' + type)) {
			$('spc_' + type).show();
		}
	}
});


//For search
var EventList = Class.create({
	initialize: function () {
		this.pages = arguments[0];
	},
	drawEvents: function () {
		$w('national international noevents').each(function (d) {
			if ($('hdr_' + d)) {
				$('hdr_' + d).hide();
			}
			if ($('result_' + d)) {
				$('result_' + d).hide();
			}
			if ($('spc_' + d)) {
				$('spc_' + d).hide();
			}
			if ($('no_national_msg')) {
				$('no_national_msg').hide();
			}
			$('row_' + d).siblings().invoke('remove');
		});

		if (this.pages.stack.length) {
			// we have multiple pages, build the current one
			var current = this.pages.stack[global.get('pages').current];
			current.each(function (p, idx) {
				var tmp = p.split(':');
				this.buildEvents(search_data.get(tmp[0]).docs[tmp[1]], tmp[0], idx);
			}.bind(this));

			// Display number of events
			this.buildCounts(current);
		}

		// Loop through all buckets we want to display
		else {
			//No pages just build them all
			$w('national international noevents').each(function (s) {
				//For current bucket loop through all docs
				search_data.get(s).docs.each(function (d, idx) {
					this.buildEvents(d, s, idx);
				}.bind(this));

				$('count_' + s).update('(' + search_data.get(s).docs.length + ')');

			}.bind(this));
		}
		browselib.searchHandleNoResults();
	},
	//Count and displays the total number and which events are showing above all buckets
	buildCounts: function (current) {
		var min = current.first().split(':');
		var max = current.last().split(':');
		min[1] = parseInt(min[1], 10) + 1;
		max[1] = parseInt(max[1], 10) + 1;
		if (min[0] == max[0]) {
			$('count_' + min[0]).update('(' + min[1] + ' - ' + max[1] + ' ' + tu("OF_PAGINATION") + ' ' + search_data.get(min[0]).docs.length + ')');
		}
		else {
			var tmp_h = $H();
			current.each(function (c) {
				var key = c.split(':').first();
				tmp_h.set(key, []); // removed new Array()
			});

			current.each(function (c) {
				var key = c.split(':').first();
				var val = c.split(':').last();
				var tmp_val = tmp_h.get(key);
				tmp_val.push(val.toString());
				tmp_h.set(key, tmp_val);
			});

			tmp_h.keys().each(function (k) {
				var tmp = tmp_h.get(k);
				var d_length = search_data.get(k).docs.length;
				if (tmp.length == d_length) {
					$('count_' + k).update('(' + d_length + ')');
				}
				else {
					var min = parseInt(tmp_h.get(k).first(), 10) + 1;
					var max = parseInt(tmp_h.get(k).last(), 10) + 1;
					$('count_' + k).update('(' + min + ' - ' + max + ' ' + tu("OF_PAGINATION") + ' ' + d_length + ')');
				}
			});
		}
	},
	buildEvents: function (d, type, idx) {
		//create table-row for each event
		var r = new Element('tr');

		$w('event location date more').each(function (c) {
			var td;
			var div;
			var popup;
			var venue_loc;

			if (type === 'noevents') {

				var d_type = d.Type.first();

				td = new Element('td', {
					'class': c
				});
				div = new Element('div', {
					'class': 'pad10'
				});
				switch (c) {
				case 'event':
					if (d_type == 'Venue') {
						div.innerHTML = tu("NO_EVENTS_SCHEDULED");
					}
					else {
						div.innerHTML = '<a href="' + d.AttractionSEOLink.first() + '">' + d.AttractionName.first() + '</a>';
					}
					break;
				case 'location':
					div.innerHTML =  browselib.getLocation(d);
					break;
				case 'date':
					div.innerHTML = tu("NO_DATES");
					break;
				default:
					var my_link = d_type == 'Venue' ? d.VenueSEOLink : d.AttractionSEOLink;
					div.innerHTML = '<a href="' + my_link + '" class="more">' + tu("MORE_INFO") + '</a>';
					div.addClassName('checkoutSearch');
				}
			} else {
				td = new Element('td', {
					'class': c
				});
				div = new Element('div', {
					'class': 'pad10'
				});

				switch (c) {
				case 'event':
					var act = '';
					var event_link = '';
					if (d.AttractionSEOLink && !d.AttractionSEOLink.first().empty()) {
						event_link = d.AttractionSEOLink.first();
					}
					else {
						event_link = d.CheckoutURL;
					}

					popup = '';

					if (d.ExternalRedirect && (global.get('crossSiteNewWindow'))) {
						popup = 'target="_blank"';
					}
					act = '<a href="' + event_link + '"' + popup + '>' + d.EventName + '</a>';

					// Look for secondary acts that match the search term
					if (d.AttractionSEOLink && d.AttractionSEOLink.length > 1) {
						var term = search_data.get('searchTerms') ? search_data.get('searchTerms').query : search_data.get('term');
						var i;
						for (i = 1; i < d.AttractionSEOLink.length; i++) {
							if (d.AttractionName[i].toLowerCase().indexOf(term.toLowerCase()) >= 0) {
								act = act + '<br/><a class="secondary_act" href="' + d.AttractionSEOLink[i] + '"' + popup + '> - ' + d.AttractionName[i] + '</a>';
							}
						}
					}

					div.innerHTML = act;
					break;

				case 'location':
					div.innerHTML =  browselib.getLocation(d);
					break;

				case 'date':
					var date = '';
					var is_cancelled = '';
					if (d.Canceled) {
						is_cancelled = '<span class="errorMessage">' + tu("EVENT_IS_CANCELLED") + '</span><br/>';
					}

					date += is_cancelled + d.LocalEventDateDisplay;
					
					if(date == "undefined")
						date= tu("NO_DATES");
					
					div.innerHTML = date;

					break;

				default:

					popup = false;
					if (d.ExternalRedirect && (global.get('crossSiteNewWindow'))) {
						popup = true;
					}

					var link = browselib.purchaseLink(d.CheckoutURL, d.VisibilityStatus, popup);
					div.innerHTML = link;
					div.addClassName('checkoutSearch');
				}
			}

			td.appendChild(div);
			r.appendChild(td);

		});

		// add the row to bucket table on the page
		$('tbl_' + type).appendChild(r);

		// show the header result and the spacer of bucket table
		if ($('hdr_' + type)) {
			$('hdr_' + type).show();
		}
		if ($('result_' + type)) {
			$('result_' + type).show();
		}
		if ($('spc_' + type)) {
			$('spc_' + type).show();
		}
	}
});


// For Search
var SearchPages = Class.create({
	initialize: function () {
		//handles variables need for pagination
		this.current = 1;
		this.prev = 0;
		this.next = 2;
		this.stack = $A();
		this.types = $A();
		this.page_max = global.get('page_max');
		this.results_max = 500;
		this.max_pages = Math.ceil(this.results_max / this.page_max);
		this.total_docs = search_data.get('total');
		this.total_real_docs = search_data.get('total_docs') <= this.results_max ? search_data.get('total_docs') : this.results_max;
		this.total_pages = Math.ceil(this.total_real_docs / this.page_max);

		if (this.total_pages > 1) {
			$w('national international noevents').each(function (d) {
				if (search_data.get(d).docs.length) {
					this.types.push(d);
				}
				var i;
				for (i = 0; i < search_data.get(d).docs.length; i++) {
					this.stack.push(d + ':' + i);
				}
			}.bind(this));

			this.stack = this.stack.eachSlice(this.page_max);
			//  why does it add undefined first???
			this.stack.splice(0, 0, undefined);

			//Draws the pagination to the page
			this.drawPageNav();
		}
		else {
			$w('national international noevents').each(function (d) {
				if (search_data.get(d).docs.length) {
					this.types.push(d);
				}
			}.bind(this));

			//Build the pagination text and add it to the html
			var count_html = "1 - " + this.total_docs + " " + tu("OF_PAGINATION") + " " + this.total_docs;

			if (this.total_docs === 0) {
				count_html = "0 - " + this.total_docs + " " + tu("OF_PAGINATION") + " " + this.total_docs;
			}

			$('pages_count').innerHTML = count_html;

			if ($('filter_txt')) {
				$('filter_txt').hide();
			}
		}
		//Updates and shows the number of results at the top of the page
		$('search_total').update('(' + this.total_docs + ')');
		$('pages').show();
		if ($('DCSext.results_total')) {
			$('DCSext.results_total').content = this.total_docs;
		}
		if ($('DCSext.term')) {
			$('DCSext.term').content = global.get('keyword');
		}
	},
	//Draws the pagination. No strange this...
	drawPageNav: function () {

		var output = ((this.current - 1) * this.page_max + 1) + ' - ';

		if (this.current != this.total_pages) {
			output += (this.page_max * this.current);
		}
		else {
			if (this.total_docs < this.total_real_docs) {
				output += this.total_docs;
			}
			else {
				output += this.total_real_docs;
			}
		}

		output += " " + tu("OF_PAGINATION") + " " + this.total_docs;

		if (this.total_pages > 1) {
			var prevB = ' &nbsp;&nbsp; <a href="" onclick="browselib.prevPage(); return false;"><img src="/theme/common/image/search/blank.gif" class="prev" /></a> &nbsp;&nbsp;';
			var nextB = '<a href="" onclick="browselib.nextPage(); return false;"><img src="/theme/common/image/search/blank.gif" class="next" /></a>';

			if (this.prev > 0) {
				output += prevB;
			}
			else {
				output += '&nbsp;&nbsp;';
			}
			var p;
			for (p = 1; p <= this.total_pages; p++) {
				if (p == this.current) {
					output += p + ' &nbsp;&nbsp; ';
				}
				else {
					output += '<a href="" onclick="browselib.xPage(' + p + '); return false;">' + p + '</a> &nbsp;&nbsp; ';
				}
			}
			if (this.next <= this.total_pages) {
				output += nextB;
			}
		}
		$('pages_count').update(output);

		if (this.current == this.total_pages && this.total_pages > 1 && this.current == this.max_pages) {
			if (!$('filter_txt')) {
				$('pages').insert({
					'before': '<div class="pad15 border_all txtCnt mgBot10" id="filter_txt"><strong>' + tu("FOR_MORE_RESULTS_START") + '<a href="" onclick="$(\'colLeft\').scrollTo(); return false;">' + tu("FOR_MORE_RESULTS_END") + '</a>.</strong></div>'
				});
			}
			else {
				$('filter_txt').show();
			}
		}
		else {
			if ($('filter_txt')) {
				$('filter_txt').hide();
			}
		}
	},
	nextPage: function () {
		if (this.next <= this.total_pages) {
			this.prev = this.current;
			this.current = this.next;
			this.next++;
			
			if(typeof omniSearchPagination == 'function')
				omniSearchPagination();
			
			return true;
		}
		else {
			return false;
		}
	},
	prevPage: function () {
		if (this.prev > 0) {
			this.prev--;
			this.current--;
			this.next--;

			if(typeof omniSearchPagination == 'function')
				omniSearchPagination();
			
			return true;
		}
		else {
			return false;
		}
	},
	xPage: function (pos) {
		this.current = pos;
		this.prev = pos - 1;
		this.next = pos + 1;

		if(typeof omniSearchPagination == 'function')
			omniSearchPagination();
		
		return true;
	}
});


// Not in use
var SeeAlso = Class.create({
	initialize: function () {
		this.also_list = arguments[0];
	},

	drawSeeAlso: function () {
		if (this.also_list.length) {
			var tempA = [];
			this.also_list.each(function (c) {
				if (c != search_data.get('term')) {
					var link = c.Link.include('http') ? '' : 'http://www.ticketmaster.com';
					link += c.Link;
					link += link.include('?') ? '&' : '?';
					tempA.push('<a href="' + link + 'tm_link=Search_other_matches">' + c.LinkText + '</a>');
				}
			});
			$('suggest_list').insert({
				'top': tempA.join(', ')
			});
			$('search_suggest').show();
		}
	}
});


var Suggest = Class.create({
	initialize: function () {
		this.suggest_list = arguments[0];
	},

	drawSuggest: function () {
		if (this.suggest_list.length) {
			var tempA = [];
			if ($('suggest_list').childElements().length) {
				$('suggest_list').insert({
					'bottom': ', '
				});
			}
			this.suggest_list.each(function (c) {
				if (c != search_data.get('term')) {
					tempA.push('<a href="?keyword=' + encodeURIComponent(c) + '&tm_link=Search_other_matches">' + c + '</a>');
				}
			});
			$('suggest_list').insert({
				'bottom': tempA.join(', ')
			});
			$('search_suggest').show();
		}
	}
});


var Crumbs = Class.create({
	initialize: function () {
		this.facet_list = arguments[0];
		this.term = arguments[1];
	},
	drawCrumbs: function () {
		if (this.facet_list.length) {

			$('term_crumbs').update(tu("SEARCH_RESULTS_FOR") + '<a href=\"\" onclick=\"browselib.updateSearch(); return false;\">' + this.term + '</a>');
			var span = new Element('span', {
				'class': 'normal'
			});
			var last = this.facet_list.last();
			this.facet_list.each(function (f, c) {
				var s = new Element('span', {
					'class': 'count'
				}).update('&nbsp;&raquo; ');
				$('term_crumbs').insert({
					'bottom': s
				});
				var tmp;
				var a;
				var b;
				if (f.include('&') && f.include('start') && f.include('end')) {
					// Date range
					if (global.get("date_string_format") === '%d-%m-%Y') {
						a = f.split('&');
						b = a[0].split('=');
						tmp = browselib.getConvertedDate(b[1]) + ' - ';
						b = a[1].split('=');
						tmp += browselib.getConvertedDate(b[1]);
					}
					else {
						a = f.split('&');
						b = a[0].split('=');
						tmp = b[1] + ' - ';
						b = a[1].split('=');
						tmp += b[1];
					}
				}
				else {
					// standard facet
					tmp = decodeURIComponent(f.split('=')[1]);
				}
				if (f !== last) {
					var aa = '<a href="" onclick="browselib.crumbPop(' + c + '); return false;">' + tmp + '</a>';
					tmp = aa;
				}
				$('term_crumbs').insert({
					'bottom': tmp
				});
			});
		}

		else {
			$('term_crumbs').update(tu("SEARCH_RESULTS_FOR") + ' ' + this.term);
		}
	}
});



var Browselib = Class.create({

	initialize: function() {
		this.dateTimeFormat = '%Y-%m-%d\\<br/>%H:%i';
	},
	
	setType: function (page) {
	this.type = page;
	},
	
	setDateTimeFormat: function (formatStr) {
		if (formatStr) {
			this.dateTimeFormat = formatStr;
		}
	},

	getType: function () {
		return this.type;
	},
	
	setAllBrowse: function (b) {
		this.allBrowse = b;
	},
	
	getAllBrowse: function () {
		if (this.allBrowse)
			return true;
		else
			return false;
	},
	

	// search, browse, artist
	purchaseLink: function (link, VisibilityStatus, popup) {
		var availabilityText = "";
		var extraAvailabilityText = "";

		switch (VisibilityStatus) {
		case 'seats_available':
			availabilityText = tu("FIND_TICKETS_SEARCH");
			if (popup === true) {
				return '<a class="more" target="_blank" href="' + link + '">' + availabilityText + '</a>';
			} else {
				return '<a class="more" href="' + link + '">' + availabilityText + '</a>';
			}
			break;

		case 'no_seats_available':
			availabilityText = tu("MORE_INFO");
			extraAvailabilityText = tu("NO_TICKETS_AVAILABLE");

			if (popup === true) {
				return '<a class="more" target="_blank" href="' + link + '">' + availabilityText + '</a><br/>' + extraAvailabilityText;
			} else {
				return '<a class="more" href="' + link + '">' + availabilityText + '</a><br/>' + extraAvailabilityText;
			}
			break;

		case 'sold_out':
			if (popup === true) {
				return '<a class="more" target="_blank" href="' + link + '">' + tu("SOLD_OUT") + '</a>';
			} else {
				return '<a class="more" href="' + link + '">' + tu("SOLD_OUT") + '</a>';
			}
			break;
			//return '<span><strong class="sold-out-search">' + tu("SOLD_OUT") + '</strong></span>';

		case 'currently_not_on_sale':
			availabilityText = tu("MORE_INFO");
			extraAvailabilityText = tu("CURRENTLY_NOT_ON_SALE");

			if (popup === true) {
				return '<a class="more" target="_blank" href="' + link + '">' + availabilityText + '</a><br/>' + extraAvailabilityText;
			} else {
				return '<a class="more" href="' + link + '">' + availabilityText + '</a><br/>' + extraAvailabilityText;
			}
			break;

		case 'cancelled':
			availabilityText = tu("MORE_INFO");

			if (popup === true) {
				return '<a class="more" target="_blank" href="' + link + '">' + availabilityText + '</a>';
			} else {
				return '<a class="more" href="' + link + '">' + availabilityText + '</a>';
			}
			break;
		}
	},

	// Search and browse
	sortAlpha: function (a, b) {
		var sort_key = global.get('skey');
		if (global.get(sort_key) == 'desc') {
			if (b[sort_key] < a[sort_key]) {
				return -1;
			}
			if (b[sort_key] > a[sort_key]) {
				return 1;
			}
		}
		else {
			if (a[sort_key] < b[sort_key]) {
				return -1;
			}
			if (a[sort_key] > b[sort_key]) {
				return 1;
			}
		}
		if(sort_key == "VenueCity") {
			// sort on venue name if equal
			sort_key ="VenueName";
			if (a[sort_key] < b[sort_key]) {
				return -1;
			}
			if (a[sort_key] > b[sort_key]) {
				return 1;
			}
		}
		
		return 0;
	},

	// Search and browse
	getConvertedDate: function (date) {
		var a = date.split('-');
		var tmp = a[2] + '-' + a[1] + '-' + a[0];

		return tmp;
	},

	nextPage: function () {
		if (global.get('pages').nextPage()) {

			if (this.getType() === "browse") {
				new BrowseEventList(global.get('pages')).drawEvents();
			}

			if (this.getType() === "search") {
				new EventList(global.get('pages')).drawEvents();
			}

			if (this.getType() === "artist") {
				new ArtistEventList(global.get('pages')).drawEvents();
			}

			global.get('pages').drawPageNav();
		}
		$$('body').first().scrollTo();
	},

	prevPage: function () {
		if (global.get('pages').prevPage()) {

			if (this.getType() === "browse") {
				new BrowseEventList(global.get('pages')).drawEvents();
			}

			if (this.getType() === "search") {
				new EventList(global.get('pages')).drawEvents();
			}

			if (this.getType() === "artist") {
				new ArtistEventList(global.get('pages')).drawEvents();
			}

			global.get('pages').drawPageNav();
		}
		$$('body').first().scrollTo();
	},

	xPage: function (p) {
		if (global.get('pages').xPage(p)) {

			if (this.getType() === "browse") {
				new BrowseEventList(global.get('pages')).drawEvents();
			}

			if (this.getType() === "search") {
				new EventList(global.get('pages')).drawEvents();
			}

			if (this.getType() === "artist") {
				new ArtistEventList(global.get('pages')).drawEvents();
			}

			global.get('pages').drawPageNav();
		}
		$$('body').first().scrollTo();
	},

	showLoaderDivs: function (updating) {
		if (updating) {
			//show small updating results
			//Calculates center of the page
			var scroll_x = isNaN(parseInt(window.scrollX, 10)) ? parseInt(document.documentElement.scrollLeft, 10) : parseInt(window.scrollX, 10);
			var scroll_y = isNaN(parseInt(window.scrollY, 10)) ? parseInt(document.documentElement.scrollTop, 10) : parseInt(window.scrollY, 10);
			var viewport = document.viewport.getDimensions();
			var load_box = $('loading_lb').getDimensions();
			var top = (((viewport.height - load_box.height) / 2) - 50) + scroll_y;
			var left = ((viewport.width - load_box.width) / 2) + scroll_x;
			var actual_page = $$('body').first().getDimensions();
			
			$('modal').setStyle({
				height: actual_page.height+ 'px',
				width: actual_page.width+ 'px'
			});
			$('loading_lb').setStyle({
				top: top + 'px',
				left: left + 'px'
			});
			$('modal', 'loading_lb').invoke('show');
		}
		else {
			//Show large Loading results	
			$('modal', 'loading').invoke('show');
		}
	},

	webTrends: function (tag) {
		dcsMultiTrack('DCS.dcsuri', tag, 'WT.ti', tag);
	},

	sortResults: function (sType) {

		var sorder;
		var img_src;
		switch (sType) {
		case "event":
			global.set('skey', 'EventName');
			sorder = 'EventName';
			break;
		case "location":
			global.set('skey', 'VenueCity');
			sorder = 'VenueCity';
			break;
		case "date":
			global.set('skey', 'EventDate');
			sorder = 'EventDate';
			break;
		case "onsale":
			global.set('skey', 'VisibilityStatus');
			sorder = 'VisibilityStatus';
			break;
		}
		if (global.get(sorder) == 'desc') {
			global.set(global.get('skey'), 'asc');
			img_src = '/theme/common/image/search/sort.gif';
		}
		else {
			global.set(global.get('skey'), 'desc');
			img_src = '/theme/common/image/search/sort_up.gif';
		}

		// since the each loop steals this...
		var ethis = this;

		if (this.getType() === "search") {
			$w('national international noevents').each(

			function (k) {

				if (search_data.get(k).docs.length) {
					$('sa_' + k).src = img_src;
					$(sType + '_' + k).insert({
						'bottom': $('sa_' + k)
					});
					search_data.get(k).docs.sort(ethis.sortAlpha);
				}
			});
		}

		if (this.getType() === "browse") {
			$w('browse').each(

			function (k) {
				if (browse_data.get(k).docs.length) {
					$('sa_' + k).src = img_src;
					$(sType + '_' + k).insert({
						'bottom': $('sa_' + k)
					});
					browse_data.get(k).docs.sort(ethis.sortAlpha);
				}
			});
		}

		this.xPage(1);
	},

	toggleFilter: function (toToggle, togLink) {

		if ($(toToggle)) {
			$(toToggle).toggle();
			if ($(toToggle).hasClassName('more')) {
				$(toToggle).addClassName('less');
				$(toToggle).removeClassName('more');
			}
			else {
				$(toToggle).addClassName('more');
				$(toToggle).removeClassName('less');
			}
			if ($(togLink).hasClassName('more')) {
				$(togLink).addClassName('less');
				$(togLink).removeClassName('more');
			}
			else {
				$(togLink).addClassName('more');
				$(togLink).removeClassName('less');
			}
		}
	},

	crumbPop: function (facetIndex, isAll) {
		if (Object.isNumber(facetIndex)) {
			var c = search_data.get('facets').length - 1;
			while (c > facetIndex) {
				search_data.get('facets').pop();
				c--;
			}
			this.webTrends('search_bread_crumb');
		}
		else {
			var temp;
			temp = search_data.get('facets').reject(function (i) {
				return i.split('=').first() == facetIndex;
			});
			search_data.set('facets', temp);
			temp = null;
			if (isAll) {
				var tag;
				switch (facetIndex) {
				case "a":
					tag = "act_show_all";
					break;
				case "v":
					tag = "venue_show_all";
					break;
				case "g":
					tag = "category_show_all";
					break;
				case "c":
					tag = "city_show_all";
					break;
				case "m":
					tag = "date_show_all";
					break;
				}
				this.webTrends(tag);
			}
		}
		this.initSearch(search_data.get('facets').join('&'));
	},

	setArtistTracking: function () {

		var attraction = global.get('attraction');

		if ($('DCSext.artid')) {
			$('DCSext.artid').content = attraction.ARTIST_ID;
		}

		if ($('DCSext.artist_name')) {
			$('DCSext.artist_name').content = attraction.ARTIST_NAME;
		}

		if ($('DCSext.artist_majcat')) {
			$('DCSext.artist_majcat').content = attraction.ARTIST_MAJCAT;
		}
		if ($('DCSext.artist_minorcat')) {
			$('DCSext.artist_minorcat').content = attraction.ARTIST_MINORCAT;
		}
		var tot = search_data.get('total');

		if (search_data.get('total') === 0) {
			if ($('WT.ti')) {
				$('WT.ti').content = 'Artist_NotOnSale';
			}
			if ($('DCS.dcsuri')) {
				$('DCS.dcsuri').content = 'Artist_NotOnSale';
			}
		}
		else {
			if ($('WT.ti')) {
				$('WT.ti').content = 'Artist_List';
			}
			if ($('DCS.dcsuri')) {
				$('DCS.dcsuri').content = 'Artist_List';
			}
		}
	},


	handleSearchTracking: function () {

		var misspells = false;
		var suggestion = false;
		var results = false;

		if (search_data.get('searchTerms') && search_data.get('searchTerms').misspell) {
			misspells = true;
		}

		if ((search_data.get('seeAlso') && search_data.get('seeAlso').length > 0) | (search_data.get('didYouMean') && search_data.get('didYouMean').length > 0)) {
			suggestion = true;
		}

		if (search_data.get('total_docs') && search_data.get('total_docs') > 0) {
			results = true;
		}

		if (results && !suggestion) {
			if ($('DCSext.results')) {
				$('DCSext.results').content = "Match with No Suggestions";
			}

			if ($('DCS.dcsuri')) {
				$('DCS.dcsuri').content = "Match with No Suggestions";
			}
			if ($('WT.ti')) {
				$('WT.ti').content = "Match with No Suggestions";
			}
		}
		if (results && suggestion) {
			if ($('DCSext.results')) {
				$('DCSext.results').content = "Match with Suggestions";
			}
			if ($('DCS.dcsuri')) {
				$('DCS.dcsuri').content = "Match with Suggestions";
			}
			if ($('WT.ti')) {
				$('WT.ti').content = "Match with Suggestions";
			}
		}

		if (misspells && suggestion) {
			if ($('DCSext.results')) {
				$('DCSext.results').content = "Correction with Suggestions";
			}
			if ($('DCS.dcsuri')) {
				$('DCS.dcsuri').content = "Correction with Suggestions";
			}
			if ($('WT.ti')) {
				$('WT.ti').content = "Correction with Suggestions";
			}
		}

		if (misspells && !suggestion) {
			if ($('DCSext.results')) {
				$('DCSext.results').content = "Correction with No Suggestions";
			}
			if ($('DCS.dcsuri')) {
				$('DCS.dcsuri').content = "Correction with No Suggestions";
			}
			if ($('WT.ti')) {
				$('WT.ti').content = "Correction with No Suggestions";
			}
		}

		if (!results) {
			if ($('DCSext.results')) {
				$('DCSext.results').content = "No Match";
			}
			if ($('DCS.dcsuri')) {
				$('DCS.dcsuri').content = "No Match";
			}
			if ($('WT.ti')) {
				$('WT.ti').content = "No Match";
			}
		}

		if (results && misspells && !suggestion) {
			if ($('DCSext.results')) {
				$('DCSext.results').content = "Correction with Suggestions";
			}
			if ($('DCS.dcsuri')) {
				$('DCS.dcsuri').content = "Correction with Suggestions";
			}
			if ($('WT.ti')) {
				$('WT.ti').content = "Correction with Suggestions";
			}
		}
	},

	updateSearch: function (param, value) {

		if (param && value) {
			value = encodeURIComponent(value);
			var to_pass = param + '=' + value;

			// adds info to search_data_facets thru temp
			var tmp = search_data.get('facets');
			tmp.push(to_pass);
			var tag;
			switch (param) {
			case "a":
				tag = "search_act_filter";
				break;
			case "v":
				tag = "search_venue_filter";
				break;
			case "g":
				tag = "search_category_filter";
				break;
			case "c":
				tag = "search_city_filter";
				break;
			case "m":
				tag = "search_month_filter";
				break;
			}
			this.webTrends(tag);
		}
		else {
			search_data.set('facets', $A());
			this.webTrends('search_bread_crumb');
		}
		this.initSearch(search_data.get('facets').join('&'));
	},

	searchHandleNoResults: function () {
		if (global.get('pages').current === 1) {
			if (!global.get('pages').types.include('national')) {
				if (!global.get('pages').types.include('international')) {
					if (search_data.get('total_docs') < 1) {
						if (search_data.get('facets').length === 0) {
							$('noSearchResults').show();
							$('search_results').hide();

							//Tracking
							if ($('DCS.dcsuri')) {
								$('DCS.dcsuri').content = 'No Match';
							}
						}
						else {
							//No national
							$('count_national').update("(0)");
							$('hdr_national').show();
							$('no_national_msg').show();
						}
					}
					else {
						$('count_national').update("(0)");
						$('hdr_national').show();
						$('no_national_msg').show();
					}
				}
				else {
					//No national
					$('count_national').update("(0)");
					$('hdr_national').show();
					$('no_national_msg').show();
				}
			}
		}
	},

	convertDate: function (date_from, date_to) {

		if (Object.isElement($(date_from)) && Object.isElement($(date_to))) {
			var calendar_from_input_str = $(date_from).value;
			var calendar_to_input_str = $(date_to).value;

			if (global.get('date_string_format') == '%d-%m-%Y') {
				var date_separater = global.get('date_string_format').substr(2, 1);
				calendar_from_input_str = calendar_from_input_str.split(date_separater);
				calendar_from_input_str = calendar_from_input_str[1] + date_separater + calendar_from_input_str[0] + date_separater + calendar_from_input_str[2];
				calendar_to_input_str = calendar_to_input_str.split(date_separater);
				calendar_to_input_str = calendar_to_input_str[1] + date_separater + calendar_to_input_str[0] + date_separater + calendar_to_input_str[2];
			}
			return true;
		}
		else {
			return false;
		}
	},

	formatDate: function (dateVal) {
		if (global.get('date_string_format') == '%d-%m-%Y') {
			var tmp = dateVal.split('-');
			return tmp[2] + '-' + tmp[1] + '-' + tmp[0];
		}
		else {
			return dateVal;
		}
	},

	addRange: function (from, to) {

		if (this.convertDate(from, to)) {
			var from_value = this.formatDate($F(from));
			var to_value = this.formatDate($F(to));
			var new_facet = search_data.get('facets').reject(function (n) {
				return n.split('=').first() == 'start';
			});
			search_data.set('facets', new_facet);
			var tmp = search_data.get('facets');
			tmp.push('start=' + from_value + '&end=' + to_value);
			this.webTrends('search_custom_date');
			this.initSearch(search_data.get('facets').join('&'), true);
		}
		else {
			alert('e=1x337: Date Range Error');
		}
	},

	addParam: function (param, value) {
		if (param && value) {
			value = encodeURIComponent(value);
			var to_pass = param + '=' + value;
			var tmp = browse_data.get('facets');
			tmp.push(to_pass);
		}
	},

	getMinorCat: function () {
		if ($('minor_cat').value) {
			return $('minor_cat').value;
		}
		else {
			if ($('minor_cat_title').down()) {
				
				if(window.browselib.getAllBrowse()) {
					var mct = $('minor_cat_title').down().innerHTML;
					
					
					if(mct == "") 
						mct = browse_data.get("allCategory");
					return mct;
				}
				
				return $('minor_cat_title').down().innerHTML;
			}
			else {
				if ($('minor_cat_title').firstDescendant()) {
					return $('minor_cat_title').firstDescendant().innerHTML;
				}
				else {
					if ($('minor_cat_title').innerHTML) {
						return $('minor_cat_title').innerHTML;
					}
					else {
						return "";
					}
				}
			}
		}
	},

	updateBrowse: function () {
		this.initBrowse(this.getBrowseParameters(true), true);
	},

	showBrowseDivs: function () {
		// Hide loader divs
		$('modal', 'loading_lb', 'loading').invoke('hide');

		if (this.total_docs > 0) {
			$('btm_nav', 'top_nav').invoke('show');
		}

		$('browseList').show();
	},

	hideBrowseDivs: function (update) {
		$('browseList').hide();
		$('btm_nav', 'top_nav').invoke('hide');
		this.showLoaderDivs(update);
	},

	browseHistoClick: function (code, text) {
		document.title = tu("PAGE_TITLE").replace('%CATEGORY_NAME%',text);
		
		browse_data.set('cat_name', text);

		//set category field
		if ($('minor_cat_title').firstDescendant()) {
			$('minor_cat_title').firstDescendant().update(text);
		}
		else {
			$('minor_cat_title').update(text);
		}

		//Set hidden category field	
		$('minor_cat').value = code;
		var tag = 'tm_' + browse_data.get('cat_name').toLowerCase() + '_b_' + code;

		this.webTrends(tag);
		this.updateBrowse();
	},
	
	allBrowseHistoClick: function() {
		var rdc = $('rdc_select');
		var location = $('major_loc');
		var fromDate = $('calendar_from_input');
		var toDate = $('calendar_to_input');
		
		$('location_form').setValue(location.getValue());
		
		$('rdc_select_form').setValue(rdc.getValue());
		
		if($('rdc_select_form').getValue() == "range") {
			$('type_form').setValue("RANGE");
			$('calendar_from_input_form').setValue(fromDate.getValue());
			$('calendar_to_input_form').setValue(toDate.getValue());
			//remove rdc_select_form
			$('rdc_select_form').remove();
		}else {
			$('type_form').setValue("selected");
			$('calendar_from_input_form').remove();
			$('calendar_to_input_form').remove();
			//remove calender inputs
		}
		$('browseAllForm').submit();
		
	},

	browseGetSearch: function (uri, h, k, args) {
			
		new Ajax.Request(uri, {
			method: 'get',
			parameters: args,
			onSuccess: function (t) {
				var data = t.responseText.evalJSON();
				browselib.postProcess(data);
				
				if(k == 'allCat') {
					h.set("allCat", data.response.numFound);
					return false;
				}
				
				if (k == 'histogram') {
					h.set(k, data.facet_counts.facet_fields);
					h.set("numFound", data.response.numFound);
				}
				else {
					if (data.error !== undefined) {
						h.set('error', data.error);
					}
					else {
						h.set(k, data.response);
						h.set('total', h.get('total') + h.get(k).numFound);
						h.set('total_docs', h.get('total_docs') + h.get(k).docs.length);
					}
				}
			},
			onFailure: function (t) {
				h.set('response_errors', 1);
			}
		});
	},
	
	
	/**
	 * Post processes search results
	 */
	postProcess: function(data) {
		for (i = 0; i < data.response.docs.length; i++) {
			var d = data.response.docs[i];
			
			// Format the display datetime
//			if (d.LocalEventYear && d.LocalEventMonth && d.LocalEventDay && d.LocalEventTimeDisplay) {
//				var year = d.LocalEventYear;
//				var month = d.LocalEventMonth;
//				var day = d.LocalEventDay;
//				var hour = d.LocalEventTimeDisplay.substr(0,2);
//				var minute = d.LocalEventTimeDisplay.substr(3,2);
//				if (d.LocalEventTimeDisplay.substr(6, 2) == 'PM') {
//					hour += 12;
//				}
//				
//				var tmp = new Date(year, month, day, hour, minute, 0);
//				d.LocalEventDateDisplay = tmp.format(this.dateTimeFormat);
//			}
			
		}
	},

	/**
	 * Makes the ajax.request
	 * uri: url to the json-repsonse
	 * h: where to store the resonse
	 * k: what kind of request.
	 * args: filter parameters
	 */
	//for search
	getSearch: function (uri, h, k, args) {

		new Ajax.Request(uri, {
			method: 'get',
			parameters: args,
			onSuccess: function (t) {
				var data = t.responseText.evalJSON();
				
				browselib.postProcess(data);
				
				if (k == 'histogram') {
					h.set(k, data.facet_counts.facet_fields);
				}
				else if (k == 'seeAlso') {
					h.set('seeAlso', data.response.docs); //getting the manual set seeAlsos
					var searchTerms = [];
					searchTerms.query = global.get('keyword');

					if (data.spellcheck.suggestions.length) {
						var suggestions = data.spellcheck.suggestions.last().suggestion;
						h.set('didYouMean', suggestions);

						if (data.spellcheck.misspelledTerm) {
							//set the misspell info							
							searchTerms.query = suggestions[0];
							searchTerms.misspell = data.spellcheck.misspelledTerm;
							suggestions.splice(0, 1);
						}
					}
					h.set('searchTerms', searchTerms);
				}
				else {
					//stores the response in search_data
					h.set(k, data.response);
					//counts the events
					h.set('total', h.get('total') + h.get(k).numFound);
					//counts all events to displayed
					h.set('total_docs', h.get('total_docs') + h.get(k).docs.length);
				}
			},
			onFailure: function (t) {
				h.set('response_errors', 1);
			}
		});
	},


	artistGetSearch: function (uri, h, k, args) {
		var ethis = this;
		new Ajax.Request(uri, {
			method: 'get',
			parameters: args,
			onSuccess: function (t) {
				var data = t.responseText.evalJSON();
				browselib.postProcess(data);

				//stores the response in search_data
				h.set(k, data.response);
				//counts the events
				h.set('total', h.get('total') + h.get(k).numFound);
				//counts all events to displayed
				h.set('total_docs', h.get('total_docs') + h.get(k).docs.length);
				ethis.setArtistTracking();
			},
			onFailure: function (t) {
				h.set('response_errors', 1);
			}
		});
	},

	initBrowse: function (args, update) {

		this.hideBrowseDivs(update);
		browse_data.set('total', 0);
		browse_data.set('total_docs', 0);
		browse_data.set('response_errors', 0);

		fireBrowse(args);
		var start_time = new Date().getTime();
		var ethis = this;

		var requestCheck = new PeriodicalExecuter(

		function (pe) {
			var end_time = new Date().getTime();
			if (((end_time - start_time) / 1000) >= 30 || (browse_data.get('response_errors') && browse_data.get('response_errors') == 1)) {
				pe.stop();
				$('loading').hide();
				$('browse_content').hide();
				$('page_error').show();
				return;
			}
			if (Ajax.activeRequestCount === 0) {
				pe.stop();

				if (browse_data.get('error')) {
					//change the error in the  no browse message div
					$('no_browse_msg').innerHTML = "<div class=\"error\" style=\"padding-bottom:5px\">" + browse_data.get('error') + "</span>";
				}

				if (browse_data.get('histogram')) {				
					new BrowseHisto(browse_data.get('histogram')).drawHisto();
				}
				
				$('category_name').innerHTML = ethis.getMinorCat();
				global.set('pages', new BrowsePages());
				
				new BrowseEventList(global.get('pages')).drawEvents();
				
				if(typeof omniBrowse == 'function')
					omniBrowse();
				
				// Send webtrends
				if (global.get('webtrends_sent') == 'false') {
					dcsVar();
					dcsMeta();
					dcsFunc("dcsAdv");
					dcsTag();
					global.set('webtrends_sent', 'true');
				}
			}
		}, 0.25);
	},

	getBrowseParameters: function (useMinorCat) {
		
		if(useMinorCat == undefined)
			useMinorCat = false;
		
		var genre;

		if ($('minor_cat').value) {
			genre = $('minor_cat').value;
		}
		else {
			if ($('minor_cat_title').down()) {
				genre = $('minor_cat_title').down().innerHTML;
			}
			else {
				genre = $('minor_cat_title').innerHTML;
			}
		}

		genre = genre.replace("&amp;", "%26");
		genre = genre.replace("&", "%26");
		var location = $('major_loc').value;
		var majorCategory = browse_data.get('cat_id');
		var rdc_select = $('rdc_select').value;
		var from = $('calendar_from_input').value;
		var to = $('calendar_to_input').value;

		var parameterString = '';
		
		if(!this.getAllBrowse())
			parameterString +='cat=' + majorCategory;

		if (genre && !this.getAllBrowse()) {
			parameterString = parameterString + '&g=' + genre;
		} else {
			if(useMinorCat)
				parameterString = parameterString + '&g=' + genre;
		}
		
		
		
		if (location) {
			parameterString = parameterString + '&location=' + location;
		}
		if (rdc_select) {
			if (rdc_select != 'range') {
				parameterString = parameterString + '&rdc_select=' + rdc_select;
			}
			else {
				if (from) {
					if (global.get('date_string_format') === '%d-%m-%Y') {
						from = this.getConvertedDate(from);
					}
					parameterString = parameterString + '&from=' + from;
				}
				if (to) {
					if (global.get('date_string_format') === '%d-%m-%Y') {
						to = this.getConvertedDate(to);
					}
					parameterString = parameterString + '&to=' + to;
				}
			}
		}
		return parameterString;
	},

	//for artist
	noNational: function () {
		if (true && global.get('pages').current === 1) {
			if (!global.get('pages').types.include('national')) {
				$('hdr_national').show();
				$('no_national_msg').show();
				$('count_national').update('(0)');
			}
		}
	},


	artistInitSearch: function (args) {

		search_data.set('total', 0);
		search_data.set('total_docs', 0);
		search_data.set('response_errors', 0);
		$('loading').show();
		fireSearch(args);
		var start_time = new Date().getTime();
		var requestCheck = new PeriodicalExecuter(

		function (pe) {
			var end_time = new Date().getTime();
			if (((end_time - start_time) / 1000) >= 30 || (search_data.get('response_errors') && search_data.get('response_errors') == 1)) {
				pe.stop();
				var tmp = $('page_error').innerHTML;
				$('mainContent').innerHTML = tmp;
				return;
			}
			if (search_data.get('national') && search_data.get('international')) {
				pe.stop();
				global.set('pages', new ArtistSearchPages());

				new ArtistEventList(global.get('pages')).drawEvents();
				browselib.noNational();
				
				if(typeof omniArtist == 'function')
					omniArtist();
				
				// Send webtrends
				if (global.get('webtrends_sent') == 'false') {
					dcsVar();
					dcsMeta();
					dcsFunc("dcsAdv");
					dcsTag();
					global.set('webtrends_sent', 'true');
				}
			}
		}, 0.25);
	},

	getLocation: function(d) {
		if (d.VenueName && !d.VenueName.empty() || d.VenueCity && !d.VenueCity.empty()) {
			popup = '';

			if (d.ExternalRedirect && (global.get('crossSiteNewWindow'))) {
				popup = ' target="_blank"';
			}

			var venue_loc = '';
			if (d.VenueCity && !d.VenueCity.empty()) {
				venue_loc += d.VenueCity;
			}
			if (d.VenueCountry && !d.VenueCountry.empty()) {
				if (d.VenueCity && !d.VenueCity.empty()) {
					venue_loc += ', ';
				}
				venue_loc += d.VenueCountry;
			}
			return '<a href="' + d.VenueSEOLink + '"'+popup+'>' + d.VenueName + '</a>' + venue_loc;
		}

		return tu("NO_LOCATIONS");
	},
	
	// This is for searchmodule
	initSearch: function (args, sne) {

		// see if its updating or loading 
		var updating = $('colLeft').visible();
		//display spinner
		browselib.showLoaderDivs(updating);

		buildCalendarPicker();

		//Reset variables in search_data
		search_data.set('total', 0);
		search_data.set('total_docs', 0);
		search_data.set('response_errors', 0);

		//Makes ajax requests
		fireSearch(args, sne);

		var start_time = new Date().getTime();

		var ethis = this;

		//Periodal Executer handles the responses from the ajax requests in fireSearch
		//pe is polling every 0.25 seconds until the data has arrived or an error occurs
		var requestCheck = new PeriodicalExecuter(

		function (pe) {
			var end_time = new Date().getTime();

			// Stops the pe if there is errors or search takes more than 30s
			if (((end_time - start_time) / 1000) >= 30 || (search_data.get('response_errors') && search_data.get('response_errors') == 1)) {
				pe.stop();
				$('loading').hide();
				$('modal', 'loading_lb').invoke('hide');
				$('search_results').hide();
				//$('search_noresults').hide();
				$('search_error').show();
				
				if(typeof omniSearchBrowseError == 'function')
					omniSearchBrowseError();

				return;
			}
			//Stops the pe if there is no more ajax calls running
			if (Ajax.activeRequestCount === 0) {
				pe.stop();

				var error = false;

				$w('national international noevents').each(function (d) {
					if (!search_data.get(d)) {
						error = true;
					}
				});

				if ((search_data.get('response_errors') && search_data.get('response_errors') == 1) || error) {
					$('loading').hide();
					$('modal', 'loading_lb').invoke('hide');
					$('search_results').hide();
					//$('search_noresults').hide();
					$('search_error').show();

					if(typeof omniSearchBrowseError == 'function')
						omniSearchBrowseError();

					return;
				}
				else {
					if (search_data.get('histogram')) {
						new Histo(search_data.get('histogram')).drawHisto();
						$('browse_calendar_picker').show();
					}
					else {
						// Where the histogram is empty we want to hide the container
						$$('#colLeft .wrap-default')[0].setStyle('background-image : none');
						$$('#colLeft .roundBot')[0].hide();
						$('left-nav').hide();
					}

					$('suggest_list').innerHTML = '';
					if (search_data.get('seeAlso') && search_data.get('seeAlso').length) {
						//show the manual seeAlsos
						new SeeAlso(search_data.get('seeAlso')).drawSeeAlso();
						//something for tmlinks??
					}
					if (search_data.get('didYouMean') && search_data.get('didYouMean').length) //possbile misspells
					{
						new Suggest(search_data.get('didYouMean')).drawSuggest();
					}

					//Store the events in global variable
					//Handles pagination
					global.set('pages', new SearchPages());

					if (search_data.get('searchTerms')) {
						new Crumbs(search_data.get('facets'), search_data.get('searchTerms').query).drawCrumbs();
					}

					var str;
					//if we have a misspelled term show that to
					if (search_data.get('searchTerms')) {
						str = search_data.get('searchTerms').misspell;
						if (str !== undefined) {
							$('srch_subhdr').update('<em>' + tu("NO_RESULTS_FOR_WITH_SUGGESTION") + ' "' + str + '"</em>').show();
						}
					}
					else {
						str = search_data.get('term');
						$('term_crumbs').update(tu("SEARCH_RESULTS_FOR") + str);
					}

					//Build the html for all events			
					new EventList(global.get('pages')).drawEvents();

					// Hide loading and displays search-result divs
					$('loading').hide();
					$('modal', 'loading_lb').invoke('hide');
					$('srch_top', 'colLeft', 'srch_results').invoke('show');

					ethis.handleSearchTracking();
					
					if(typeof omniSearch == 'function')
						omniSearch();
					
					// Send webtrends
					if (global.get('webtrends_sent') == 'false') {
						dcsVar();
						dcsMeta();
						dcsFunc("dcsAdv");
						dcsTag();
						global.set('webtrends_sent', 'true');
					}
				}
			}
		}, 0.25); //How often the pe should run
	}
});
