
function popup(href, height) {
	if (! window.focus) return true;
	if (! height) height = "800"
	window.open(href, null, 'width=680,height='+height+',scrollbars=yes');
	return false;
}

function stop(e) {
	if (!e) e = window.event;
	e.cancelBubble=true;
	if (e.stopPropagation) e.stopPropagation();
	return true;
}

function make_hint(elid, hint_value) {
	var el = $(elid)
	if (!el) return;
	el.hint_value = hint_value
	el.hint_type = el.type
	el.reset_hint = function() {
		this.value = this.hint_value;
		this.style.color = "gray";
		this.style.type = "text";
		this.onfocus = function() {
			this.style.color = "black"
			this.style.type = this.hint_type
			this.value = ""
			this.onfocus = null;
		}
	}
	el.onblur = function() {
		if (this.value == '') this.reset_hint()
	}
	if (el.value == "") {
		el.reset_hint()
	}
	var oldsubmit = el.form.onsubmit
	function myonsubmit() {
		if (el.style.color == "gray") el.onfocus();
		if (oldsubmit) oldsubmit();
	}
	el.form.onsubmit = myonsubmit
	var old_unload = window.onunload
	window.onunload = function() {
		myonsubmit()
		if (old_unload) old_unload();
	}
}

function any_form_elements_set(parent) {
	el = parent.getElementsByTagName("input")
	for (i=0; i<el.length; i++) {
		if (el[i].type == 'hidden') continue;
		if (el[i].type == 'submit') continue;
		if (el[i].type == 'checkbox') {
			if (el[i].checked) return true;
			continue;
		}
		if (el[i].value != "") return true;
	}
	el = parent.getElementsByTagName("option")
	for (i=0; i<el.length; i++) {
		if (el[i].selected && el[i].value != "") return true;
	}
	return false
}

function make_expandable(div_id) {
	var div = $(div_id)
	var open_div = $(div_id+"_open")
	var close_div = $(div_id+"_close")
	var open_anchor = document.createElement("A");
	var close_anchor = document.createElement("A");
	open_anchor.innerHTML = "show more options..."
	open_anchor.href = "javascript:"
	close_anchor.innerHTML = "hide options"
	close_anchor.href = "javascript:"
	div.save_display = div.style.display
	// Are there any input fields in "div" that have a non-empty value?
	if (any_form_elements_set(div)) {
		open_anchor.style.display = "none"
	} else {
		div.style.display = "none"
	}
	open_anchor.onclick = function() {
		this.style.display = "none"
		new Effect.BlindDown(div, { duration: 0.5 });		
	}
	close_anchor.onclick = function() {
		new Effect.BlindDown(open_anchor, { duration: 0.5 });		
		new Effect.BlindUp(div, { duration: 0.5 });				
	}
	open_div.insertBefore(open_anchor, null)
	close_div.insertBefore(close_anchor, null)
}

function make_expandable_on_select(expandable_id, select_id) {
	var select = $(select_id)
	var div = $(expandable_id)
	select.old_value = select.value;
	if (select.value != '0') {
		div.style.display = 'none';
	}
	select.onchange = function() {
		if (this.value == '0') {
			new Effect.BlindDown(div, { duration: 0.5 });
		} else {
			if (this.old_value == '0') {
				new Effect.BlindUp(div, { duration: 0.5 });
			}
		}
		this.old_value = this.value;
	}
}

function grow_ta() {
	while (this.scrollHeight > this.clientHeight && this.clientHeight < 400) {
		this.rows += 1;
	}
}


if  (document.getElementById) {  // This tests whether we are using DOM level 2.
		
	// TODO:  Should use domcontentloaded?
	vavoca_old_onload = window.onload
	window.onload = function () {
		if (vavoca_old_onload) vavoca_old_onload();

		if (!window.opera) {  // Opera doesn't report height properly
			tas = $$('textarea')
			for (i=0; i<tas.length; i++) {
				tas[i].onkeyup = grow_ta
			}
		}
		
		DURATION = 0.5;
		var funs = new Object();

		/* Create an "Advanced Search" description text. */
		function asdesc() {
			out = "";
			searchform = $("search")
			if (searchform.c.value) out += ", "+searchform.c.value;
			if (searchform.rating.value) out += ", "+searchform.rating.value+" stars";
			if (searchform.pay.value) out += ", $"+searchform.pay.value;
			if (searchform.dist.value && searchform.dist.value != "0") out += ", "+searchform.dist.value+"mi";
			langs = "";
			langNode = searchform["lang[]"];
			// langNode is either a SELECT element or a NodeList of SELECT elements.
			if (langNode.nodeName == "SELECT") langNode = [ langNode ];
			for (i=0; i<langNode.length; i++) {
				l = langNode[i];
				if (l.selectedIndex != 0) langs += "+"+l.options[l.selectedIndex].text;
			}
			if (langs) {
				out += ", " + langs.slice(1);
			}
			if (searchform.pic.checked) out += ", +photos";
			if (searchform.lic.checked) out += ", +license";
			for (a in searchform) {
				if (a.search(/^a\[.*\]$/) >= 0 && searchform[a].checked) {
					out += ", Availability";
					break;
				}
			}
			if (out) return out.slice(1);
			return " -none-";
		}
		
		/*  One "Feature" of many browsers is that form value fields are not
		reset when a user hits CTRL-R to reload a page.  This means that
		we could end up in a state where the Advanced Search box was redrawn
		in a state other than the value we have for the hidden "as" field.
		We get around this problem by passing the state of the Advanded 
		Search box in the className attribute */
		if ($("as")) {
			$("as").value = $("as").className;
		}

		var asdiv = $("advsearchdiv");
		
		/* set_as simply sets the hidden "as" input value to the argument and makes
		sure that this hidden field is not disabled */
		function set_as(value) {
			$("as").disabled = false;
			$("as").value = value;
		}
		/* Set the text of the advanced search buttons to either Minimize or Maximize
        depending on the current state of the as.value */
		function set_as_buttons() {
			if ($("as").value == "min") {
				$("asmin").name = "asmax"
				$("asmin").value = "+"
				$("asmin").onmousedown = funs.asmax;
				/* TODO:  Set the background images somehow? */
			} else {
				$("asmin").name = "asmin"
				$("asmin").value = "-"
				$("asmin").onmousedown = funs.asmin;
				/* TODO:  Set the background images somehow? */
			}
		}
		function set_as_title() {
			if ($("as").value == "min") {					
				$("asdesc").innerHTML = asdesc();
				$("astitle").innerHTML = "Advanced Search:";
			} else {
				$("asdesc").innerHTML = "";
				$("astitle").innerHTML = "Advanced Search Options";					
			}
		}
		
		/* Internet Explorer hack.... 
		 * "Relatively positioned items do not play well with the Blind effects in IE.  They
		    float on the screen, even as everything else scrolls up.  And if the page started
		    out with them hidden, they remain invisible! */
		function as_make_static() {
			if (navigator.appName != "Microsoft Internet Explorer") return;
			el = $("asbody").getElementsByTagName("label")
			for (i=0; i<el.length; i++) el[i].style.position = "static";
			el = $("asbody").getElementsByClassName("rating_input")
			for (i=0; i<el.length; i++) {
				el[i].style.position = "static"
				imgs = el[i].getElementsByTagName("img")
				for (j=0; j<imgs.length; j++) imgs[j].style.position = "static";
			}
		}		
		function as_make_relative() {
			if (navigator.appName != "Microsoft Internet Explorer") return;
			el = $("asbody").getElementsByTagName("label")
			for (i=0; i<el.length; i++) el[i].style.position = "relative";
			el = $("asbody").getElementsByClassName("rating_input")
			for (i=0; i<el.length; i++) {
				el[i].style.position = "relative";
				imgs = el[i].getElementsByTagName("img")
				for (j=0; j<imgs.length; j++) imgs[j].style.position = "relative";
			}
		}
		
		/* Return the "scale" of the minimized position as used by the effects 
		library in the BlindUp and BlindDown animations.  This returns the percentage
		of height the advanced search box should be in when in the minimized position. */
		function as_min_scale() {
			as_dims = $("advsearch").getDimensions();
			return 100.0 * (6+$("ashead").getDimensions().height) / as_dims.height;
		}
		
		/* as_min_finish does some cleanup work after the effects library has finished the
        blindup animation to minimize the advanced search box. We do not want to simply show
        a clipped advanced search box. This function hides the actual advanced search body
        and undoes the clipping.  It also sets the title of the advanced search box so the
		user sees a summary of the advanced search options. It first preserves any
        additional width the advanced search body may have created for the table to prevent
        the advanced search table from "popping" to a skinnier format. */
		function as_min_finish() {
			$("advsearch").style.width = $("asbody").getDimensions().width+6+"px";
			$("asbody").style.display="none";
			$("advsearch").style.height = "auto";
			asdiv.undoClipping();
			set_as_title();
		}
		
		funs.asmin = function() {
			if (Effect.Queue.size()) return false;
			set_as("min");
			set_as_buttons();
			as_make_static();
			new Effect.BlindUp(asdiv, { duration: DURATION, 
				restoreAfterFinish: false,
				scaleTo: as_min_scale(), 
				afterFinishInternal: as_min_finish } 
			);
			return false;
		}
		funs.asmax = function() {
			if (Effect.Queue.size()) return false;
			set_as("open");
			set_as_buttons();
			set_as_title();
			asdiv.makeClipping().style.height = asdiv.getDimensions().height+"px";
			$("asbody").style.display = $("ashead").style.display;
			$("advsearch").style.width = "auto";
			as_dim = $("advsearch").getDimensions();
			as_make_static();
			new Effect.BlindDown(asdiv, { duration: DURATION, 
				restoreAfterFinish: false,
				scaleFrom: as_min_scale(),
				scaleMode: {originalHeight: as_dim.height, originalWidth: as_dim.width},
				afterFinishInternal: as_make_relative					
			});
			return false;
		}
		funs.asopen = function() {
			if (Effect.Queue.size()) return false;
			set_as("open");
			$("asopen").onmousedown = null;
			set_as_buttons();
			set_as_title();
			asdiv.style.height = "auto";
			$("asbody").style.display = $("ashead").style.display;
			as_make_static();
			new Effect.Fade("asopen", { duration: DURATION, to: 0.00001 }); 
			new Effect.BlindDown(asdiv, { duration: DURATION, 
				                          afterFinishInternal: as_make_relative });
			return false;
		}
		funs.asclose = function() {
			if (Effect.Queue.size()) return false;
			$("as").disabled = true;
			$("asopen").onmousedown = funs.asopen;
			as_make_static();
			new Effect.Appear("asopen", { duration: DURATION }); 
			new Effect.BlindUp(asdiv, { duration: DURATION });
			return false;
		}	
		funs.asclear = function() {
			inputs = asdiv.getElementsByTagName("input");
			for (i=0; i<inputs.length; i++) {
				inputs[i].clear();
				inputs[i].checked=false;
			}
			inputs = asdiv.getElementsByTagName("select");
			for (i=0; i<inputs.length; i++) {
				inputs[i].selectedIndex = 0;
			}
			return false;
		}
		buttons = document.getElementsByClassName("asbutton")
		for (i=0; i<buttons.length; i++) {
			b=buttons[i]
			b.onclick = funs[b.name]
		}
		/* When the page reloads and the Advanced Search box is in the minimized 
		position the title and buttons may be incorrect.  Browsers such as Firefox
		do not throw away the form data a user has entered when the user hits the
		"reload" button.  So if a user opened the AS box, enters some data and then
		minimizes it and hits the "reload" button, the AS title will be based on old
		data because the server sets it from the params that were set in the URL even
		though the fields (now hidden from view) still have the new data in them.
		Also, the minimize/maximize button will have a value of "open" because when
		it is clicked with javascript disabled we want "as" to be set to "open".
		However we want to assign it the "maximize" function - the set_as_buttons
		function will take care of that.
		*/
		if (($("as")) && ($("as").value == "min")) {
			set_as_title();
			set_as_buttons();
		}
		
		// Return the current rating value for a star-rating DIV.
		function getratingvalue(rating) {
			inputs = rating.getElementsByTagName("INPUT");
			return inputs[0].value;
		}
		
		// Set the current rating value for a star-rating DIV
		function setratingvalue(rating, value) {
			inputs = rating.getElementsByTagName("INPUT");
			inputs[0].value = value;
			set_stars(rating, value, "-32px");
		}
		
		/* Set the first 'n' stars with a TOP value of 'top' - this has the effect
		 of changing their color.  The rest are set to top = 0px, to reset their color. */
		function set_stars(rating, n, top) {
			for (j=0; j<rating.stars.length; j++) {
				star = rating.stars[j];
				if (j<n) {
					star.style.top = top;
				} else {
					star.style.top = "0px";
				}
			}
		}
		
		/* walk through all of the rating DIV elements, enhancing their star IMGs */ 
		ratings = document.getElementsByClassName("rating_input");
		for (i=0; i<ratings.length; i++) {
			rating = ratings[i];
			// With javascript, we use the hidden input element to set the value.
			rating.getElementsByTagName("INPUT")[0].disabled = false;
			rating.stars = rating.getElementsByTagName("IMG");
			for (j=0; j<rating.stars.length; j++) {
				star = rating.stars[j];
				star.rating = rating;
				star.rating_value = j+1;
				star.onclick = function() { 
					setratingvalue(this.rating, this.rating_value); 
				}
				star.onmouseover = function() { 
					set_stars(this.rating, this.rating_value, "-16px");
				}
			}
			rating.onmouseout = function() {
				set_stars(this, getratingvalue(this), "-32px");
			}
			rating.onmouseout();
		}
		
		make_hint('topemail', 'email')
		make_hint('toppassword', 'password')
		make_hint('account_form_city', 'Enter Address, City, or Zipcode')		
		make_hint('get_review_form_email_list', 'myfriend@gmail.com, myotherfriend@yahoo.com')

		/* Highlight the first true input element of the last form that is not topemail or toppassword! */
		forms = $$('form')
		if (forms.length > 0) {
			felms = forms.last().getElements();
			if (felms[0].nodeName != "INPUT" || felms[0].type != "submit") {
				for (i=0; i<felms.length; i++) {
					if (felms[i].id.substr(0,3) != 'top' && felms[i].type != 'hidden') {
						felms[i].activate()
						break;
					}
				}
			}
		}
		
		if ($("home") && $("q") && $("l")) {
			$("l").onkeydown = $("q").onkeydown = function(e) {
				if (window.event) {
					keyCode = window.event.keyCode
				} else if (e.which) {
					keyCode = e.which;
				}
				if (keyCode == 13) {
					new Effect.Highlight('searchbuttons', {startcolor: '#ff8000', restorecolor:'#ffffff'});
					return false
				} else {
					return true
				}
			}
		}
		
		// We want to encourage users to pick one of our categories, but if they really want to
		// they can enter one of their own.
		category_selects = document.getElementsByClassName("category_input");
		for (i=0; i<category_selects.length; i++) {
			category_select = category_selects[i];
			new_option = document.createElement("OPTION")
			new_option.text = "Enter New Category:"
			new_option.value = "+"
			if (navigator.appName == "Microsoft Internet Explorer") {				
				category_select.add(new_option, 1);
			} else {
				category_select.add(new_option, category_select.options[1]);
			}			
			category_text = document.createElement("INPUT");
			category_text.name = 'c'
			category_select.onchange = function() {
				if (this.value == new_option.value) {
					this.name = ''
					this.parentNode.insertBefore(category_text, this.nextSibling);
				} else {
					if (this.name == '') {
						this.name = 'c'
						this.parentNode.removeChild(category_text)
					}
				}
			}
		}
 	}
}
