function safe_button(theButtonId){
	$(theButtonId).disable();
	$(theButtonId).value = 'Please wait...';
}
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(){
	//lazy-load all images
/*
	if($('slide_sorter')){
		var images = $$('#slide_sorter img.file_preview');
		images.invoke('lazyload');
		document.observe('scroll',function(evt){
			images.each(function(element){
				var element = element;
				if(in_viewport(element)){
					element.remove_placeholder();
				}
			});
		})
	}
*/
	//links from cart area open in new window
	//$$('.shopping a').each(function(elm){elm.target = '_blank'});
	//
	$$('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.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'});
							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'});
	$$('div.flash').each(function(elm){
		if(!elm.hasClassName('error')) new Effect.Fade(elm,{delay:2});
	});
	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;
					}
				});
			}
		})
	});
}

