new Pluit.Carousel.init({
  circular: true
});

Event.observe(window, 'load', init, false);
var baseURL;

function init() {
	baseURL = $$("link[rel=index]")[0].readAttribute('href');

	if ($$('a.blind')) setupBlindDivs();
	
	if ($$('.products-grid')) setupProductsGrid();
	
	if ($('homeslide-images')) setupHomeSlideshow();
	
	var noteForm = $$('.footer .mmf-form')[0];
	if (noteForm) noteForm.observe('submit', submitNoteForm);
			
	var subForm = $('subForm');
	if (subForm) subForm.observe('submit', submitNewsletterForm);
	
	Shadowbox.init({ });
}

function setupBlindDivs() {
	var blindDivs = new Array();
	var greyOut = true;
	$$('a.blind').each(function(el) {
		var name = el.href.split(/#/).last();
		var div = $$('div.blind_content[name="'+name+'"]')[0];
		blindDivs.push(div);
		var visible = div.visible();
		var height = div.show().getHeight();
		if (!visible) {
			div.hide();
			if (greyOut) Effect.multiple(div.previousSiblings(), Effect.Opacity, { from: 1, to: .5, duration: 0 });
		}
		div.setStyle( { height: height+'px' } );
		el.observe('click', function(event) {
			var element = event.element();
			var blindDiv;
			for (var i = 0; i < blindDivs.length; i++) {
				blindDiv = blindDivs[i];
				if (element.href.split(/#/).last() == blindDiv.readAttribute('name')) {
					if (blindDiv.visible()) {
						blindFadeDiv(blindDiv, false);
						if (greyOut) Effect.multiple(blindDiv.previousSiblings(), Effect.Opacity, { to: .5 });
					} else {
						blindFadeDiv(blindDiv, true);
						if (greyOut) Effect.multiple(blindDiv.previousSiblings(), Effect.Opacity, { from: .5, to: 1 });
					}
				} else {
					if (blindDiv.visible()) blindFadeDiv(blindDiv, false);
					if (greyOut) Effect.multiple(blindDiv.previousSiblings(), Effect.Opacity, { to: .5 });
				}
			}
			var img = $$('img.blind_content_img[name="'+name+'"]')[0];
			var height = '0px';
			if (img) {
				Effect.multiple($$('img.blind_content_img:not([name="'+name+'"])'), Effect.Fade, {duration: .2});
				new Effect.Appear(img, { queue: { position: 'end', scope: 'imgappear' } });
				height = img.getHeight() + 'px';
			}
			if (img && $('blind_content_img_container')) new Effect.Morph($('blind_content_img_container'), { duration: .8, style: 'height:' + height, queue: { position: 'front', scope: 'imgappear' }  });
			Event.stop(event);
		});
	});
	
	$$('img.blind_content_img').each(function(img) {
		var visible = img.visible();
		var height = img.show().getHeight();
		if (!visible) img.hide();
		else $('blind_content_img_container').setStyle( { height: height + 'px' } );
		img.setStyle( { height: height+'px' } );
	});
}

function blindFadeDiv(div, show) {
	if (show) {
		new Effect.Parallel([
			new Effect.BlindDown(div, { sync: true }), 
			new Effect.Opacity(div, { sync: true, from: 0, to: 1 }) 
		], { 
			duration: .5,
			queue: { position: 'end', scope: 'divappear' }
		});
	} else {
		new Effect.Parallel([
			new Effect.BlindUp(div, { sync: true }), 
			new Effect.Opacity(div, { sync: true, from: 1, to: 0 })
		], { 
			duration: .5,
			queue: { position: 'front', scope: 'divappear' }
		});
	}
}

function setupProductsGrid() {
	$$('.products-grid .hproduct').each(function(el) {
		el.observe('mouseover', function(event) {
			el.select('img.small-label').invoke('setStyle', { display: 'block' });
			el.select('img.fn').invoke('setStyle', { display: 'none' });
		});
	});
	
	$$('.products-grid .hproduct').each(function(el) {
		el.observe('mouseout', function(event) {
			el.select('img.small-label').invoke('setStyle', { display: 'none' });
			el.select('img.fn').invoke('setStyle', { display: 'block' });
		});
	});
}

function setupHomeSlideshow() {
	var lis = $('homeslide-images').select('li');
	end_frame = lis.length - 1;
	//new Effect.Appear(lis[0]);
	if (lis.length > 1) setTimeout(fadeInOut(0, 0, end_frame, 5000, lis), 5000 + 500);
}

function fadeInOut(frame, start_frame, end_frame, delay, lis) {
	return (function() {
		lis = $('homeslide-images').select('li');
		new Effect.Fade(lis[frame]);
		if (frame == end_frame) { frame = start_frame; } else { frame++; }
		var lisAppear = lis[frame];
		new Effect.Appear(lisAppear);
		setTimeout(fadeInOut(frame, start_frame, end_frame, delay), delay);
	})
}

function submitNoteForm (event) {
	Event.stop(event);
	var noteForm = $$('.footer .mmf-form')[0];
	
	var formAction = noteForm.readAttribute("action");
	// Serialize form values to be submitted with POST
	var hash = $H(noteForm.serialize(true));
	
	// Add form action to end of serialized data
	hash.set("_mmf_is_ajax_call", 1);
	
	// Validate email address with regex
	if (hash.get('your-message') == '') {
		alert("Please enter a message");
		return;
	}
	
	var popForm = new Element('div').update('<h2>Thanks for your note!</h2><br/><h3>Please verify you\'re not a spammer and (optionally) give us your email address so we can write you back</h3><br/>');
	popForm.addClassName('note-form');
	var newNoteForm = noteForm.cloneNode(true);
	newNoteForm.select('.hidden')[0].removeClassName('hidden');
	newNoteForm.select('textarea')[0].innerHTML = noteForm.select('textarea')[0].getValue();
	newNoteForm.select('textarea')[0].hide();
	/** var noButton = newNoteForm.select('input[type=submit]')[0].cloneNode(true);
	noButton.setValue('No Thanks');
	noButton.addClassName('btn-nothanks');
	noButton.insert({before:'&nbsp;'});
	**/
	newNoteForm.select('input[type=submit]')[0].insert({before: '<br/><br/>'});
	newNoteForm.insert('<br/><br/><input type="checkbox" name="newsletter-signup" value="newsletter-signup" />&nbsp;<h5>Add my email address to the mailing list so I can hear about new products and sales!</h5>');
	popForm.insert(newNoteForm);
	popForm = new Element('div').insert(popForm);
	
	Shadowbox.open({
		content:    popForm.innerHTML,
		player:     "html",
		title:      "",
		height:     300,
		width:      780,
		options:	{
			onFinish: function() {
				var finalForm =  $$('#sb-player .mmf-form')[0];
				finalForm.observe('submit', function(event) {
					Event.stop(event);
				
					var formAction = finalForm.readAttribute("action");
					// Serialize form values to be submitted with POST
					var hash = $H(finalForm.serialize(true));
					
					// Validate email address with regex
					var emailField = finalForm.select('input[type=text]')[1];
					if (emailField.getValue() != '' && !checkEmail(emailField)) {
						alert("Please enter a valid email address");
						return;
					}
					
					var newsletterSignup = finalForm.select('input[type=checkbox]')[0].getValue() != null;
					if (newsletterSignup && emailField.getValue() != '') {
						subForm.select('input[type=text]')[0].setValue(emailField.getValue());
						submitNewsletterForm();
					}
	
					// Add form action to end of serialized data
					hash.set("_mmf_is_ajax_call", 1);
	
					finalForm.disable();
					finalForm.setOpacity(.5);
					finalForm.select('.ajax-loader')[0].setStyle({visibility:'visible'});
					
					// Submit the form via ajax
					new Ajax.Request(formAction, {
						method: 'post',
						parameters: hash,
						onFailure: function() {
							finalForm.setOpacity(1);
							finalForm.enable();
						},
						onSuccess: function(response) {
							var json = response.responseText.evalJSON();
							// Server-side validation
							if (response.responseText.search(/error/i) != -1) {
								alert('An error has occured. Incorrect CAPTCHA?');
								
								if (json.captcha) {
									jQuery.each(json.captcha, function(i, n) {
										var match = /([0-9]+)\.(png|gif|jpeg)$/.exec(n);
										$$('#_mmf_captcha_challenge_' + i)[0].setValue(match[1]);
										$$('#_mmf_captcha_challenge_' + i)[1].setValue(match[1]);
										$$('img.mmf-captcha-' + i)[0].src = n;
										$$('img.mmf-captcha-' + i)[1].src = n;
									});
								}
		
								finalForm.setOpacity(1);
								finalForm.enable();
								finalForm.select('.ajax-loader')[0].setStyle({visibility:'hidden'});
							} else {
								finalForm.reset();
								finalForm.setOpacity(1);
								finalForm.enable();
								finalForm.select('.ajax-loader')[0].setStyle({visibility:'hidden'});
								Shadowbox.close();
							}
						}
					});
				});	
			},
			enableKeys: false,
			modal: true,
			displayNav: false
		}
	});
	
	noteForm.reset();
}

function submitNewsletterForm (event) {
	if (event) Event.stop(event);
	var silent = event == null;
	var subForm = $('subForm');
	
	var formAction = subForm.readAttribute("action");
	var id = "ykykir";
	var emailId = id + "-" + id;

	// Validate email address with regex
	if (!checkEmail($(emailId))) {
		alert("Please enter a valid email address");
		return;
	}
	
	// Serialize form values to be submitted with POST
	var hash = $H(subForm.serialize(true));
	
	// Add form action to end of serialized data
	hash.set("action", formAction);
	
	if (!silent) {
		subForm.disable();
		subForm.setOpacity(.5);
		$$('#subForm .ajax-loader')[0].show();
	} else subForm.reset();
	
	// Submit the form via ajax
	new Ajax.Request(baseURL + '/proxy.php', {
		method: 'post',
		parameters: hash,
		onFailure: function() {
			subForm.setOpacity(1);
			subForm.enable();
		},
		onSuccess: function(response) {
			// Server-side validation
			if (response.responseText.search(/invalid/i) != -1) {
				alert('The email address you supplied is invalid and needs to be fixed before you can subscribe to this list.');
			} else {
				if (!silent) {
					Shadowbox.open({
						content:    '<div><h2>Thanks for subscribing!</h2></div>',
						player:     "html",
						title:      "",
						height:     200,
						width:      370
					});
					setTimeout(Shadowbox.close, 3000);
					subForm.reset();
					subForm.setOpacity(1);
					subForm.enable();
					$$('#subForm .ajax-loader')[0].hide();
				}
				
				if (_gaq) {
					// Fire off Google Analytics fake pageview
					_gaq.push(['_trackPageview', 'newsletter_signup']);
				}
			}
		}
	});
}

function checkEmail(emailElement) { 
	var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var emailVal = emailElement.getValue();
	return pattern.test(emailVal);
}

