
function get_select_value(sel) {
	return sel.options[sel.selectedIndex].value;
}

function set_select_value(sel, value) {
	for (var i=0; i < sel.options.length; i++) {
		if (sel.options[i].value == value) {
			sel.selectedIndex = i;
			sel.onchange;
		}
	}
}

// Given the id of a page element, and an object containg style keys and values,
// sets those styles on the given object
function styler(id, styles) {
	try {
	var elem = document.getElementById(id);
	if (!id) {return;}
	for (var stylename in styles) {
		var stylevalue = styles[stylename];
		elem.style[stylename] = stylevalue;
	}
	} catch(e) { }
}

function onchage_country(sel) {
	var dest = document.f.PLACE;
	dest.options.length = 1;
	var country = get_select_value(sel);
	if (country == 'USA' || country == 'CANADA') {
		document.location = '/templates/door/usa.tmpl';
		return;
	}
    else if (country == 'PUERTO RICO') {
        document.location = '/templates/door/usa.tmpl?COUNTRY=PUERTO+RICO';
        return;
    }
    else if (country == 'JAPAN') {
        document.location = 'http://www.aveda.co.jp/network/default.asp';
        return;
    }
	var places = country_regions[country];
	if (!places) { return; }

	var all_cities_value = 
		"COUNTRY|" + country + 
		"|ACTUAL_CITY|ALL" + 
		"|STATE|ALL";
	var all_cities_option = new Option(
		"All Cities", all_cities_value, true, true
	);

	// JavaScript reports that arrays indexed by strings
	// have no length, so we have to keep track of the size 
	// of the array ourselves.
	var regions = new Array();
	var region_count = 0;
	for(var i=0; i < places.length; i++) {
		var place = places[i];
		var region = (place.VALUE.split("|"))[5];

		if(! regions[region]) {
			var all_cities_region_value = 
				"COUNTRY|" + country +
				"|ACTUAL_CITY|ALL" +
				"|STATE|" + region;
			var region_name = place.LABEL;
			region_name = (region_name.split(", "))[1];
			var option = new Option(
				"All Cities in " + region_name, 
				all_cities_region_value, 
				false, false
			);
			regions[region] = option;
			region_count++;
		}
	}

	dest.options[dest.options.length] = all_cities_option;
	if( region_count > 1 ) {
		$H(regions).values().each(function(region) {
			dest.options[dest.options.length] = region;
		});
	}


    places.each(function(place) {
		var optionObj = new Option(place.LABEL, place.VALUE, false, false);
        if (optionObj == null) { return; }
		dest.options[dest.options.length] = optionObj;
	});
    
    
}

function ucfirst(str) {
	str = str.toLowerCase();
	var first = str.charAt(0);
	first = first.toUpperCase();
	return first + str.substring( 1, str.length );
}
