function safe_button(theButtonId){
	$(theButtonId).disable();
	$(theButtonId).value = 'Please wait...';
}

// boolean, argument matches a leap year
function is_leap(yr) {
	if ((parseInt(yr)%4) == 0) {
		if (parseInt(yr)%100 == 0) {
			if (parseInt(yr)%400 != 0) {
				return false;
			}
			if (parseInt(yr)%400 == 0) {
				return true;
			}
		}
		if (parseInt(yr)%100 != 0) {
			return true;
		}
	}
	if ((parseInt(yr)%4) != 0) {
		return false;
	} 
}

// returns number of days in a given month, accounting for leap years
function days_in_month(month, year) {
	var months = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ];
	var feb = 28;
	if (is_leap(year)) { feb = 29; }
	var days = [ 31, feb, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
	for (var i = 0; i < 12; i++) {
		if (Number(month) == Number(months[i])) {
			return days[i];
		}
	}
	return false;
}

function make_num_array(num) {
	var ret = [];
	for (i = 1; i <= num; i++) {
		ret[i] = i;
	}
	alert(ret[5]);
	return ret;
}

function zero_fill(num, places) {
	while (num.length < places) {
		num = '0' + num;
	}
	return num;
}

function recalculate_datepicker(y, m, d) {
	var seldate = d.value;
	var days = days_in_month(m.value, y.value);
	
	d.options.length = 0;
	for (var i = 1; i <= days; i++) {
		var selthis = (Number(seldate) == i) ? true : false;
		var o = new Option(i, i);
		if (selthis) {
			o.selected = true;
		}
		d.options.add(o);
	}
}

var c = function (event) {
	if (confirm('Are you sure you want to delete? There is no Undo!!')) {
		return true;
	} else {
		Event.stop(event);
	}
};
var in_viewport = function(elm){
	var offsets = elm.viewportOffset();
	var scroll = document.viewport.getScrollOffsets();
	var win = document.viewport.getDimensions();
	var port = {top:scroll[1],bottom:scroll[1] + win.height};
	var box = {top:offsets[1],bottom:offsets[1] + elm.getHeight()};
	if(box.top < port.bottom && box.bottom > port.top) return true;
	return false;
}
Element.addMethods({
	lazyload: function(element, options){
		var element = $(element);
		var options = Object.extend({
			placeholder : 'Resources/_clear.gif',
			frequency : 0.5
			}, options || {}
		);
		var old_source = $(element).readAttribute('src');
		var new_source = options.placeholder;
		if(!in_viewport(element)){
			element.writeAttribute({ src : new_source }).writeAttribute({ '_src' : old_source });
			element.setStyle('background: #242424 url(../Resources/loading-pro.gif) no-repeat center center; width:80px; height:80px;');
		}
	},
	remove_placeholder: function (element){
		var element = $(element);
		// this function restores the original image source; called when within the viewport
		if ( true === element.hasAttribute('_src') ){
			var old_source = $(element).readAttribute('_src');
			element.writeAttribute({ src: old_source });
			element.writeAttribute({ _src: null });
			element.setStyle('width:auto; height:auto');
			//console.log(element.src)
		}
	},
	timecodeToFrames: function(element){
		var input = $F(element) || '00:00:00.00';
		if(input.indexOf(':') < 1) return parseInt(input,10);
		var parts = input.split(/[:\.]/);
		//hours
		var hours = parseInt(parts[0],10);
		if(hours < 0 || hours > 99) hours = 0;
		var frames = hours * (60 * 60 * 30);
		//minutes
		var minutes = parseInt(parts[1],10);
		if(minutes > 59 || minutes < 0) minutes = 0;
		frames += minutes * (60 * 30);
		//seconds
		var seconds = parseInt(parts[2],10);
		if (seconds < 0 || seconds > 59) seconds = 0;
		frames += seconds * 30;
		//frames
		var framez = parseInt(parts[3] * 1,10);
		//if(framez > 29 || framez < 0) framez = 0;
		frames += (framez / 100) * 30;
		return Math.round(frames);
	},
	timecodeToSeconds: function(element){
		var input = $F(element) || '00:00:00.00';
		if(input.indexOf(':') < 1) return parseFloat(input);
		var parts = input.split(/[:\.]/);
		//hours
		var hours = parseInt(parts[0],10);
		if(hours < 0 || hours > 99) hours = 0;
		var seconds = hours * (60 * 60);
		//minutes
		var minutes = parseInt(parts[1],10);
		if(minutes > 59 || minutes < 0) minutes = 0;
		seconds += minutes * 60;
		//seconds
		var secs = parseInt(parts[2],10);
		if (secs < 0 || secs > 59) secs = 0;
		//milliseconds
		var milliseconds = parseInt(parts[3] * 1,10);
		//if(framez > 29 || framez < 0) framez = 0;
		seconds += parseFloat(secs.toString() + '.' + milliseconds.toString());
		return seconds;
	},
	framesToTimecode: function(element){
		var element = $(element);
		var input = (!!element.value) ? parseInt(element.value,10) : 0;
		var hours = Math.floor(input / (60 * 60 * 30));
		hours = (hours.toString().length == 1) ? '0' + hours.toString() : hours;
		var mins = Math.floor((input / (60 * 30)) - (60 * hours));
		mins = (mins.toString().length == 1) ? '0' + mins.toString() : mins;
		var secs = Math.floor((input / 30) - ((hours * (60 * 60)) + (mins * 60)))
		secs = (secs.toString().length == 1) ? '0' + secs.toString() : secs;
		var milliseconds = parseInt((input / 30).toString().split('.').last(),10);
		//frames = (frames.toString().length == 1) ? '0' + frames.toString() : frames;
		var timecode = hours + ':' + mins + ':' + secs + '.' + milliseconds;
		return timecode;
	},
	secondsToTimecode: function(element){
		var element = $(element);
		var input = (!!element.value) ? parseFloat(element.value) : 0;
		var hours = Math.floor(input / (60 * 60));
		hours = (hours.toString().length == 1) ? '0' + hours.toString() : hours;
		var mins = Math.floor((input / 60) - (60 * parseInt(hours,10)));
		mins = (mins.toString().length == 1) ? '0' + mins.toString() : mins;
		var secs = (input - ((parseInt(hours,10) * (60 * 60)) + (parseInt(mins,10) * 60)));
		//frames = (frames.toString().length == 1) ? '0' + frames.toString() : frames;
		var timecode = hours + ':' + mins + ':' + secs.toPrecision(3);
		return timecode;
	},
	getCurrentFrame: function(mov) {
		var adj = (mov.GetTimeScale() / 30) || 1;
		var now = Math.round(mov.GetTime() / adj);
		return now;
	},
	getCurrentTime: function(mov) {
		var adj = (mov.GetTimeScale()) || 1;
		var now = (mov.GetTime() / adj);
		return now;
	}
});
document.observe('dom:loaded',function() {
    // hack for iphone app element (430) to display additional element inputs (428 & 428) when the app product is checked
    if ($('element_430') != undefined) {
            a = $('element_429').ancestors();
            a[1].toggle();
            a = $('element_428').ancestors();
            a[1].toggle();
        $('element_430').observe('click', function() {
            if (this.checked) {
                a = $('element_429').ancestors();
                a[1].toggle();
                a = $('element_428').ancestors();
                a[1].toggle();
            } else {
                a = $('element_429').ancestors();
                a[1].toggle();
                a = $('element_428').ancestors();
                a[1].toggle();
           }
        });
    }
    
    // date-picker management
    if ($('start-order-form') != undefined) {
		y = $('dpyear');
		m = $('dpmonth');
		d = $('dpday');
		
		// form elements are disabled while page loads, but now we can enable it
		y.disabled = false;
		m.disabled = false;
		d.disabled = false;
		$('start-order-button').disabled = false;
		
		// fix day options based on initial month/year
		recalculate_datepicker(y, m, d);
		
		// when month changes, reset day options
		m.observe('change', function() {
			recalculate_datepicker($('dpyear'), $('dpmonth'), $('dpday'));
		});
		
		// when year changes do it again (in case of leap year)
		y.observe('change', function() {
			recalculate_datepicker($('dpyear'), $('dpmonth'), $('dpday'));
		});
		
		// capture click on Start Order button and submit manually
		$('start-order-form').observe('submit', function(evt) {
			evt.stop();
			var wdate = y.value + zero_fill(m.value, 2) + zero_fill(d.value, 2);
			if (wdate < $('dpcutoff').value) {
				// User selected an invalid date
				alert("The date you selected appears to be invalid. Please double check your wedding date and try again. \n\nIf you believe this is an error on our end, please email us for support: storymix@storymixmedia.com.");
			} else {
				this.action = '/projects/date/' + wdate;
				this.submit();
			}
		});
	}
    
    $$('input[type="radio"]').each(function(elm){
	//find out if there is already a group for this radio
	if(!elm.up('div.radio_group')){
		var wrap = new Element('div',{'class':'radio_group'});
		elm.up('p').insert({before:wrap});
		$$('input[name="' + elm.readAttribute('name') + '"]').each(function(em){
			wrap.insert(em.up('p').remove());
		});
	}
    });

    $$('.pro-fusion-style, .pro-slideshows-style, .pro-promo-style, .describe-event-theme, .choose-event-theme').each(function(elm){
	if(elm.hasClassName('describe-event-theme') || elm.hasClassName('choose-event-theme')){
		var themeKey = '-240,-241,-242,-132';
	}
	if(elm.hasClassName('pro-slideshows-style')){
		var themeKey = '240';
	}
	if(elm.hasClassName('pro-fusion-style')){
		var themeKey = '241';
	}
	if(elm.hasClassName('pro-promo-style')){
		var themeKey = '242';
	}
	if(!elm.up('p').previous('div.radio_group')){
		new Ajax.Request('/themes/picker/' + themeKey,{
			parameters: {name:elm.readAttribute('name'),current:elm.readAttribute('value')},
			onCreate:function(){
				elm.up('label.theme').addClassName('ajaxload');
			},
			onSuccess:function(transport){
				elm.up('label.theme').removeClassName('ajaxload');
				elm.replace(transport.responseText);
			}
		});
	}
    });
	$$('div.radio_group').each(function(wrap){
		var elm = wrap.down('input[name$="theme-type"]');
		if(elm){
			if(elm.readAttribute('name').include('consumer')){
				var themeKey = '-240,-241,-242,-132';
			}
			if(elm.readAttribute('name').include('wedding')){
				var themeKey = '132';
			}
			if(elm.readAttribute('name').include('pro-slideshow')){
				var themeKey = '240';
			}
			if(elm.readAttribute('name').include('pro-fusion')){
				var themeKey = '241';
			}
			if(elm.readAttribute('name').include('pro-promo')){
				var themeKey = '242';
			}
			var chosen = wrap.select('input[type="radio"]:checked');
			if(chosen.length > 0){
				var subchoice = wrap.next('p')
				subchoice.show();
				var label = chosen.first().up('label').innerHTML.stripTags().toLowerCase()
				if(label.include('standard')){
					subchoice.up('form').stopObserving();
					if( ! subchoice.revert) subchoice['revert'] = subchoice.down('input').clone(true);
					new Ajax.Request('/themes/picker/' + themeKey,{
						parameters: {name:subchoice.revert.readAttribute('name'),current:subchoice.revert.readAttribute('value')},
						onCreate:function(){
							subchoice.down('label.theme').addClassName('ajaxload');
						},
						onSuccess:function(transport){
							subchoice.down('label.theme').removeClassName('ajaxload');
							subchoice.select('span.multibox,input,select').first().replace(transport.responseText);
						}
					});
				}else if(label.include('mix')){
					if( ! subchoice.revert) subchoice['revert'] = subchoice.down('input').clone(true);
					if(!subchoice.down('.marker') && (!subchoice.mixed)) {
						subchoice.select('input,select').first().replace('<span class="marker"></span>');
						subchoice['mixed'] = true;
					}
					var currentArray = subchoice.revert.readAttribute('value').split(',');
					if(currentArray.length > 0){
						currentArray.each(function(elm,idx){
							currentArray[idx] = elm.split(':');
						});
					}
					var currentJSON = $H({Theme:'', Font:'', Music:''});
					['Theme', 'Font', 'Music'].each(function(part){
						currentArray.each(function(choice){
							if(choice.length == 2 && (choice[0] == part)){
								currentJSON.set(part, choice[1]);
							}
						});
					});
					currentJSON = currentJSON.toJSON();
					new Ajax.Request('/themes/mixed/' + themeKey,{
						parameters: {name:subchoice.revert.readAttribute('name'),current:currentJSON},
						onCreate:function(){
							subchoice.down('label.theme').addClassName('ajaxload');
						},
						onSuccess:function(transport){
							subchoice.down('label.theme').removeClassName('ajaxload');
							if(subchoice.down('.marker')) subchoice.down('.marker').replace(transport.responseText);
							subchoice.highlight({restorecolor:'#e6e6e6'});
							subchoice.up('form').observe('click',function(evt){
								//each time anything is clicked in the form, update the backup to match
								var newValue = [];
								subchoice.select('select').each(function(elm){
									var name = elm.readAttribute('name').split('][').last().slice(0,-1);
									newValue.push( name + ':' + $F(elm));
								});
								subchoice.revert.setValue(newValue.join(','));
							});
							subchoice.up('form').observe('submit',function(evt){
								evt.stop();
								subchoice.select('span.multibox,input,select').first().replace(subchoice.revert);
								this.submit();
							});
						}
					});
				}else{
					if(subchoice.revert) {
						subchoice.up('form').stopObserving();
						subchoice.select('span.multibox,input,select').first().replace(subchoice.revert);
						subchoice.highlight({restorecolor:'#e6e6e6'});
					}
				}
			}else{
				wrap.next('p').hide();
			}
			wrap.observe('click',function(evt){
				var chosen = this.select('input[type="radio"]:checked');
				if(chosen.length > 0){
					var subchoice = this.next('p')
					subchoice.show();
					var label = chosen.first().up('label').innerHTML.stripTags().toLowerCase()
					if(label.include('standard')){
						subchoice['mixed'] = false;
						subchoice.up('form').stopObserving();
						if( ! subchoice.revert) subchoice['revert'] = subchoice.down('input').clone(true);
						new Ajax.Request('/themes/picker/' + themeKey,{
							parameters: {name:subchoice.revert.readAttribute('name'),current:subchoice.revert.readAttribute('value')},
							onCreate:function(){
								subchoice.down('label.theme').addClassName('ajaxload');
							},
							onSuccess:function(transport){
								subchoice.down('label.theme').removeClassName('ajaxload');
								subchoice.select('span.multibox,input,select').first().replace(transport.responseText);
								subchoice.highlight({restorecolor:'#e6e6e6'});
							}
						});
					}else if(label.include('mix')){
						if( !subchoice.revert) subchoice['revert'] = subchoice.down('input').clone(true);
						if(!subchoice.down('.marker') && (!subchoice.mixed)){
							subchoice.select('input,select').first().replace('<span class="marker"></span>');
							subchoice['mixed'] = true;
							var currentArray = subchoice.revert.value.split(',');
							if(currentArray.length > 0){
								currentArray.each(function(elm,idx){
									currentArray[idx] = elm.split(':');
								});
							}
							var currentJSON = $H({Theme:'', Font:'', Music:''});
							['Theme', 'Font', 'Music'].each(function(part){
								currentArray.each(function(choice){
									if(choice.length == 2 && (choice[0] == part)){
										currentJSON.set(part, choice[1]);
									}
								});
							});
							currentJSON = currentJSON.toJSON();
							new Ajax.Request('/themes/mixed/' + themeKey,{
								parameters: {name:subchoice.revert.readAttribute('name'),current:currentJSON},
								onCreate:function(){
									subchoice.down('label.theme').addClassName('ajaxload');
								},
								onSuccess:function(transport){
									subchoice.down('label.theme').removeClassName('ajaxload');
									if(subchoice.down('.marker')) subchoice.down('.marker').replace(transport.responseText);
									subchoice.highlight({restorecolor:'#e6e6e6'});
									subchoice.up('form').observe('click',function(evt){
										//each time anything is clicked in the form, update the backup to match
										var newValue = [];
										subchoice.select('select').each(function(elm){
											var name = elm.readAttribute('name').split('][').last().slice(0,-1);
											newValue.push( name + ':' + $F(elm));
										});
										subchoice.revert.setValue(newValue.join(','));
									});
									subchoice.up('form').observe('submit',function(evt){
										evt.stop();
										subchoice.select('span.multibox,input,select').first().replace(subchoice.revert);
										this.submit();
									});
								}
							});
						}
					}else{
						if(subchoice.revert) {
							subchoice.up('form').stopObserving();
							subchoice.select('span.multibox,input,select').first().replace(subchoice.revert);
							subchoice.highlight({restorecolor:'#e6e6e6'});
							subchoice['mixed'] = false;
						}
					}
				}
			});
		}
	});
	$$(".email_link_to_gallery").invoke('observe','click',function(evt){
		var img = evt.element();
		evt.stop();
		new Ajax.Request("/emails/mailto",{
			//hard-coded to the email #24
			parameters:{id:29,projects_id:img.id.split('_').last()},
			onCreate:function(){img.src = "/Resources/icns/spinner.gif"},
			onSuccess:function(transport){
				img.src = "/Resources/icns/email_go.png";
				window.location.href = transport.responseText;
			},
			onError:function(){
				img.src = "/Resources/icns/error.png";
			}
		});
	});
	$$(".email_link_to_upload").invoke('observe','click',function(evt){
		var img = evt.element();
		evt.stop();
		new Ajax.Request("/emails/mailto",{
			//hard-coded to the email #33
			parameters:{id:33,projects_id:img.id.split('_').last()},
			onCreate:function(){img.src = "/Resources/icns/spinner.gif"},
			onSuccess:function(transport){
				img.src = "/Resources/icns/email_go.png";
				window.location.href = transport.responseText;
			},
			onError:function(){
				img.src = "/Resources/icns/error.png";
			}
		});
	});
	$$('input.quantity').invoke('observe','change',function(evt){
		var quantity = ($F(this) * 1);
		if((quantity > 0) || ! isNaN(quantity)){
			this.setValue(quantity);
		}else{
			this.clear();
		}
	});
	if($('visual_wrap')){
		$('visual_wrap').observe('click',function(evt){
			var elm = evt.element();
			if(elm.hasClassName('cancel')){
				evt.stop();
				top.location.reload();
			}
		});
	}
	$$('span.cancel').invoke('observe','click',function(evt){return top.location.reload();});
	$$('a[rel~="new_window"]').each(function(elm){elm.target = '_blank'});
	$$('input.delete, #delete').invoke('observe','click',c);
	$$('form').invoke('observe','submit',function(evt){if(evt.element().getInputs('submit').find(function(elm){return (elm.id == 'submit' || elm.id == 'delete' || elm.id == 'duplicate') }))return safe_button('submit')});

	$$('a[rel~="new_window"]').each(function(elm){elm.target = '_blank'});
        // This code causes so-called "flash" messages to fade out after 2 seconds, which is very frustrating for customers because they don't always have a chance to read the message before it disappears. So I disabled it.  Silly Walter.
//	$$('div.flash').each(function(elm){
//		if(!elm.hasClassName('error')) new Effect.Fade(elm,{delay:10});
//	});
	if($('contact_form')){
		if($('from_name').present()) {
			$('comment').activate();
		}else{
			$('contact_form').focusFirstElement();
		}
	}
	stripe = 'odd';
	var alternate = function(){
		if(stripe == 'even'){
			stripe = 'odd';
		}else{
			stripe = 'even';
		}
		return stripe;
	}
/*
	if($('delegates') && $('filter')){
		var list = $$("#delegates li");
		var lastValue = $F("filter");
		var timeout = false;
		for (var i = list.length - 1; i >= 0; i--){
			list[i]['d'] = list[i].innerHTML.replace(/\[?<a[^>]+>|contact?|<\/a>]?/gi,'').toLowerCase();
		};
		var total = new Number(list.length);
		$('filter').observe('keyup', function(e) {
			var value = this.value;
			clearTimeout(timeout);
			if (value !== lastValue) {
				value = value.toLowerCase();
				var stripe = 'even';
				timeout = setTimeout(function(){
					var showing = new Number(total);
					list.each(function(el) {
						if (el.d.include(value)) {
							Element.show(el);
							el.className = alternate();
						}else{
							Element.hide(el);
							showing --;
						}
					})
					lastValue = value;
					if(showing < total) {
						$('message').update('Showing ' + showing + ' of ' + total + '.');
					}else{
						$('message').update('');
					}
				}, 200);
			}
		});
	}
	if($('clear') && $('filter')){
		$('clear').observe('click',function(evt){
			var stripe = 'even';
			$$("#delegates li").each(function(elm){
				elm.show().className = alternate();
			});
			$('filter').clear().activate().blur();
			$('message').update('');
		});
	}
	if($('filter') && !$('filter').hasClassName('safari')){
		$('filter').observe('click',function(evt){
			if(!$('filter').present()){
				$$("#delegates li").each(function(elm){
					elm.show().className = alternate();
				});
				$('message').update('');
			}
		})
	}
    var DEF_VAL = 'Search...';
	$$('input.search').each(function(elm){
		if(Prototype.Browser.WebKit){
			elm.setAttribute('type', 'search');
			elm.setAttribute('autosave', 'saved.data');
			elm.setAttribute('results', '5');
			elm.setAttribute('placeholder', DEF_VAL);
		}else{
			var clear = new Element('img',{
				'src':'Resources/images/search_clear.gif',
				'width':18,
				'height':25,
				'alt':'(x)'
			});
			elm.insert({after:clear});
			clear.addClassName('clear');
			if(elm.getValue() == '') {
				elm.setValue(DEF_VAL);
				clear.src = clear.src.replace(/search_clear\.gif/,'search_empty_clear.gif');
			}
			elm.addClassName('search_blur');
			elm.observe('focus',function(){
				clear.src = clear.src.replace(/search_clear\.gif/,'search_focus_clear.gif');
				clear.src = clear.src.replace(/search_empty_clear\.gif/,'search_empty_focus_clear.gif');
				if(elm.getValue() == DEF_VAL) elm.clear();
				elm.removeClassName('search_blur').addClassName('search_focus');
			});
			elm.observe('blur',function(){
				if(elm.getValue() == '') elm.setValue(DEF_VAL).removeClassName('search_focus').addClassName('search_blur');
				clear.src = clear.src.replace(/search_focus_clear\.gif/,'search_clear.gif');
				clear.src = clear.src.replace(/search_empty_focus_clear\.gif/,'search_empty_clear.gif');
			});
			elm.observe('keyup',function(){
				if(elm.getValue() != '') 
				clear.src = clear.src.replace(/search_empty_focus_clear\.gif/,'search_focus_clear.gif');
			});
			
			clear.observe('click',function(evt){
				elm.clear().activate().blur();
				clear.src = clear.src.replace(/search_clear\.gif/,'search_empty_clear.gif');
			});
		}
	});
	$$('input.filter').each(function(elm){
		var txt = 'Start typing...';
		var clear = elm.next('img');
		if(Prototype.Browser.WebKit){
			elm.setAttribute('type', 'search');
			elm.setAttribute('placeholder', txt);
			clear.hide();
		}else{
			if(elm.getValue() == '') elm.setValue(txt).addClassName('search_blur');
			elm.observe('focus',function(){
				clear.src = clear.src.replace(/search_clear\.gif/,'search_focus_clear.gif');
				if(elm.getValue() == txt) elm.clear().removeClassName('search_blur').addClassName('search_focus');
			});
			elm.observe('blur',function(){
				if(elm.getValue() == '') elm.setValue(txt).removeClassName('search_focus').addClassName('search_blur');
				clear.src = clear.src.replace(/search_focus_clear\.gif/,'search_clear.gif');
			});
		}
	});
	if($('delegates')){
		var d;
		$('delegates').observe('click',function(evt){
			var elm = Event.element(evt);
			if(elm.hasClassName('contact_link')){
				Event.stop(evt);
				d = new Dialog({
					width:600,
					ajax:{
						url:elm.href,
						options:{
							evalScripts:true,
							method:'get'
						}
					},
					close:{
						link:         false,
						esc:          false,
						overlay:      false
					}
				});
				d.open();
			}
		});
	}
*/
});

var combinator = function(){
	$$('select.combo').each(function(elm){
		var elm = $(elm);
		var texts = ['Choose...'];
		var opts = [''];
		var sel = (elm.options[elm.options.selectedIndex].defaultSelected) ? elm.options.selectedIndex : -1;
		for (var i=0; i < elm.options.length; i++) {
			opts.push(elm.options[i].value);
			texts.push(elm.options[i].text);
		};
		texts.push('Add new...');
		opts.push('Add new...');
		elm.options.length = 0;
		texts.each(function(el,idx){
			elm.options[idx] = new Option(el, opts[idx], (idx == 0), false);
		});
		elm.options.selectedIndex = (sel + 1);
		elm.observe('change',function(evt){
			if(this.value == 'Add new...'){
				if(!window.bak) window['bak'] = {};
				window.bak[this.id] = this;
				var ti = new Element('input',{type:'text',name:this.name,id:this.id});
				this.replace(ti);
				ti.focus();
				ti.observe('blur',function(evt){
					if(this.getValue() == '') {
						this.replace(window.bak[this.id]);
						$(this.id).options.selectedIndex = 0;
					}
				});
			}
		})
	});
}

