Array.prototype.contains = function(obj) {
	var i = this.length;
	while (i--) {
		if (this[i] === obj) {
			return true;
		}
	}
	return false;
}

var Artist = {
	aid: '',
	artists: '',
	selected: [],
	controlUrl: 'ajax-handler/artist_lookup',
	register: function() {
		Event.observe('find-artists-link', 'click', Artist.search, false);
		// Event.observe('clear-artists-link', 'click', Artist.clear, false);
		//Event.observe('div_clearartist', 'click', Artist.clear, false);
		new Ajax.Autocompleter("autocomplete2", "autocomplete_choices2", "ajax-handler/auction_house_lookup?a=2", {paramName: "typing", minChars: 3, afterUpdateElement: Artist.setAuctionHouse});
	},
	clear: function() {
		
		Artist.selected = [];
		$('artist-list-ids').value = '';
		$('artist-list').innerHTML = '';
		$('artist_list_container').hide();

		$('aln').value = '';
		$('afn').value = '';
	},

	search: function() {
		var last = $('a_typing1').value;
		var first = $('a_typing2').value;

		if ( (last) || (first) ) {
			$('artist-loading').show();
			new Ajax.Request(Artist.controlUrl, { method: 'get', parameters: 'a=1&last=' + last + '&first=' + first, onComplete: Artist.drawArtistSelection });
		}
	},

	retrieve: function(aid, callback) {
		if ( aid ) {
			$('artist-loading').show();
			Artist.aid = aid;
			new Ajax.Request(Artist.controlUrl, { method: 'get', parameters: 'a=3&aid=' + aid, onComplete: callback });
		}
	},
	
	drawArtistSelectionStatic: function(r) {
		try {
			var p = eval(r.responseText); 
			for (var i = 0; i < p.length; i++) {
				var a = p[i];

				Artist.selected.push(a.id);
				
				var artistText = a.last + ', ' + a.first;
				
				if ( (a.birth) || (a.death) ) {
					artistText += ' (' + a.birth;
					artistText += '-'
						artistText += a.death + ')';
				} else if (a.desc) {
					artistText += ' (' + a.desc + ')';
				}
	
				if (a.nat)
					artistText += ' - ' + a.nat;

				var artistHtml =	"<div class=\"artist-choice\" id='sa-" + a.id + "'>"
				+ '<div class="col1">&nbsp;</div>'
				+ '<div><a href="#" onclick="Artist.artistListRemove(\'' + a.id + '\');return false;"><img src="images/remove.png" alt="Remove" border="0" /></a>'
				+ '&nbsp;&nbsp;' + artistText + '</div>'
				+ '</div>';
				
				$('artist-list').innerHTML = $('artist-list').innerHTML + artistHtml; 
			}
	
			$('artist_list_container').show();
			Artist.recordArtistList();
		} catch (e) {}
	},

	setAuctionHouse: function(r, p) {
		$('auctionHouseId').value = p.id;
	},

	drawArtistSelectionSelected : function (r) {
		Artist.drawArtistSelection(r);
		try { $('artistId').value = Artist.aid; } catch (e) {}
	},

	drawArtistSelection: function(r) {
		$('artist-loading').hide();
		var p = '';

		try { p = eval(r.responseText); } catch (e) {}
		if (p == undefined) { p = ''; }

		var selectBox = '<select id="artistId" class="choose-artist" name="search.artistId" onchange="Artist.setArtistName();"><option value="0">select artist</option>';
		
		if (p != '') {

			for (var i = 0; i < p.length; i++) {
				var a = p[i];
	
				selectBox += '<option id="artist-' + a.id + '" value="' + a.id + '"' + (p.length == 1 ? ' selected="selected"' : '') + '>' + a.last + ', ' + a.first;
				
				if ( (a.birth) || (a.death) ) {
					selectBox += ' (' + a.birth;
					selectBox += '-'
					selectBox += a.death + ')';
				} else if (a.desc) {
					selectBox += ' (' + a.desc + ')';
				}
	
				if (a.nat)
					selectBox += ' - ' + a.nat;
	
				selectBox += '</option>';
			}
		}
		
		selectBox += '</select>';

		var addArtistLink = '<a href="#" onclick="Artist.artistListAdd();return false;"><img src="images/add.png" alt="Add" border="0" style="vertical-align: middle; padding-left: 10px;" /></a>';
		
		$('choose_container').show();
		$('choose_select').innerHTML = selectBox + addArtistLink; 

		Artist.artists = p;
	},
	
	setArtistName: function() {
		var s = $('artistId').value;

		for (var i = 0; i < Artist.artists.length; i++) {
			var a = Artist.artists[i];
			if (s == a.id) {
				$('aln').value = a.last;
				$('afn').value = a.first;
			}
		}
	},

	artistListAdd: function() {
		var aid = $('artistId').value;
		if (aid <= 0) return;
		if (Artist.selected.contains(aid)) return;
		
		$('artist_list_container').show();

		Artist.selected.push(aid);
		
		var artistHtml = "<div class=\"artist-choice\" id='sa-" + aid + "'>"
		+ '<div class="col1">&nbsp;</div>'
		+ '<div><a href="#" onclick="Artist.artistListRemove(\'' + aid + '\');return false;"><img src="images/remove.png" alt="Remove" border="0" /></a>'
		+ '&nbsp;&nbsp;' + $('artist-' + aid).innerHTML + '</div>'
		+ '</div>';
		
		$('artist-list').innerHTML = $('artist-list').innerHTML + artistHtml;

		Artist.recordArtistList();
	},

	artistListRemove: function(aid) {
		if(aid <= 0) return;
		if (!Artist.selected.contains(aid)) return;

		var temp = [];
		var i = Artist.selected.length;
		while (i--) {
			if (Artist.selected[i] !== aid) {
				temp.push(Artist.selected[i]);
			}
		}

		Artist.selected = temp;
		$('sa-' + aid).remove();

		if (Artist.selected.length == 0) {
			$('artist_list_container').hide();
		}

		Artist.recordArtistList();
	}, 

	recordArtistList: function() {
		$('artist-list-ids').value = '';
		var i = Artist.selected.length;
		while (i--) {
			$('artist-list-ids').value += Artist.selected[i] + ' ';
		}
	}
}

Event.observe(window, 'load', Artist.register, false);

// TODO: move these functions into Artist object
function isValidNumber(id) {
	if (isNaN($(id).value)) {
		alert("Please enter a valid number");
		$(id).value = '';
	}
}

function setAuctionDate(el, val) {
	$(el).value = val;
}

function validateFrom() {
	var valid = false;

	try {
		if ( $('artistId').value != '' ) {
			valid = true;
		}
	} catch (e) {}

	try {
		if ( $('artist-list-ids').value != '' ) {
			valid = true;
		}
	} catch (e) {}
	
	if ( $('a_title').value != '' ) {
		if ( $('a_title').value.length >= 2 )
			valid = true;
	}
	
	if ( ( $('date_of_work_1').value != '' ) && 
		 ( $('date_of_work_2').value != '' ) ) {
		valid = true;
	}
	
	if ( $('price_1').value != '' ) {
		if ($('price_2').value != '' ) {
			valid = true;
		}
	}

	if ( $('a_catcode').value != '' ) {
		valid = true;
	}

	if ( $('auctionHouseId').value != '' ) {
			valid = true;
	}

	if ( $('auctionSaleDateStart').value != '' ) {
		if ($('auctionSaleDateEnd').value != '' ) {
			valid = true;
		}
	}

	return valid;
}

function submitForm() {
	// validation.
	if (!validateFrom()) {
		alert('You are required to enter searchable criteria.\n' +
			  'Please make sure at least one of the following\n' +
			  'is entered:\n'+
			  '---------------------------------------------\n' +
			  '- Artist;\n- Title (at least two characters);\n- Sale price (or range of sale prices);\n'+
			  '- Start and end date of work;\n- Sale date (or range of sale dates);\n- Auction Code;\n- Auction House;');
		return;
	}

	$('controls-1').hide();
	$('controls-2').hide();
	$('loading-indicator').show();

	var titleSearch = false;
	if ( ( $('a_title').value != '' ) && ( $('a_title').value.length >= 2 ) ) {
		titleSearch = true;

		try {
			if ( $('artistId').value > 0 ) {
				titleSearch = false;
			}
		} catch (e) {}

		try {
			if ( $('artist-list-ids').value != '' ) {
				titleSearch = false;
			}
		} catch (e) {}

		try {
			if ( $('auctionHouseId').value != '' ) {
				titleSearch = false;
			}
		} catch (e) {}
	}

	if (titleSearch) {
		var ext = '';

		sm ('dialog-box', 360, 330);
	} else {
		var p = $('search_form').serialize();
		new Ajax.Request('count-results.action', { method: 'post', parameters: p, onComplete: doCount });
	}
}

function titleSelectSubmit(s) {
	if (s == 'exact') {
		$('full-scan').value = 'false';

		var p = $('search_form').serialize();
		new Ajax.Request('count-results.action', { method: 'post', parameters: p, onComplete: doCount });
	} else if (s == 'full') {
		$('full-scan').value = 'true';

		var p = $('search_form').serialize();
		new Ajax.Request('count-results.action', { method: 'post', parameters: p, onComplete: doCount });
	} else {
		$('loading-indicator').hide();
 		$('controls-1').show();
 		$('controls-2').show();

		return;
	}
}

function doCount(r) {
 	var res = r.responseText;
 	var sub = '';

 	if (res == 0) {
		alert('Your query did not return any results,\nplease modify the search criteria.');

 		$('loading-indicator').hide();
 		$('controls-1').show();
 		$('controls-2').show();
 	} else if (res > 0) {
		sub = 'true'
 	}

	if (sub) {
 		$('scount').value = res;
 	 	$('search_form').submit();
 	} else {
 		$('loading-indicator').hide();
 		$('controls-1').show();
 		$('controls-2').show();
 	}
}

function showArtistHelp() {
	var iWin = window.open("", "ArtistHelp", "scrollbars=yes,width=350,height=120");

	iWin.document.open();

	iWin.document.writeln("<html>");
	iWin.document.writeln("<head><title>Artist Help</title>");
//	iWin.document.writeln("<link rel='stylesheet' href='styles/navigation_dark.css' type='text/css' media='screen' />");
//	iWin.document.writeln("<link rel='stylesheet' href='styles/default_dark.css' type='text/css' media='screen' />");
	iWin.document.writeln("<link rel='stylesheet' href='styles/main.css' type='text/css' media='screen' />");
	iWin.document.writeln("</head>");

	iWin.document.writeln("<body>");
	iWin.document.writeln("<p class='artist-help'>To search for lots from more than one artist, first select the artist(s) from the list and click ADD.</p><br/>");
	iWin.document.writeln("<p class='artist-help'>To remove artists that have already been selected, click X to remove one artist. CLEAR ALL will remove all selected artists from the list.</p>");
	iWin.document.writeln("</body>");
	iWin.document.writeln("</html>");

	iWin.document.close();
}

function widgetOff() {
		
}

Event.observe(window, 'load', widgetOff);

