Event.observe(window, "load", function() {
	Menu.assignObservers();
	Menu.assignSelected("/" + window.location.pathname.split('/')[1]);
});

document.observe("dom:loaded", function() {
	Menu.assignFirstAndLast();
	Comment.attachHints();
});

Survey = {
  failedMessage: "There was a problem delivering your survey. Please review your entries and try again."
                  + "If this problem persists, please contact us using the form at the bottom of the page.",
  successMessage: "Thank you for completing our client survey! Your feedback is especially important to us."
                  + "<br /><a href=\"#\" onclick=\"Survey.reset(); return false;\">Please click"
                  + " here if you'd like to take the survey again.</a>",
  form: function() { return $('sf'); },
  feedback: function() { return $('survey_feedback'); },
  inputs: function() { return Survey.form().getElements().reject(function(i) { return i.type == "submit" })},
  respond: function(response) {
    if (response) {
      Survey.success();
    } else {
      Survey.failure();
    }
  },
  
  success: function() {
    var feedback = Survey.feedback();
    feedback.update(Survey.successMessage).addClassName('visible');
    new Effect.Appear(feedback, { duration: 0.5 });
  },
  
  failure: function() {
    Survey.feedback().update(Survey.failedMessage).addClassName('visible');
    new Effect.Appear(Survey.feedback(), { duration: 0.5 });
    Survey.enable();
  },
  
  reset: function() {
    var feedback = Survey.feedback();
    Survey.form().reset();
    Survey.enable();
    if (feedback.hasClassName('visible')) {
      feedback.removeClassName('visible');
      new Effect.Fade(feedback, { duration: 0.5 });   
    }
  },
  
  disable: function() {
    var effects = [];
    var form = Survey.form();
    var feedback = Survey.feedback();
    if (feedback.hasClassName('visible')) {
      feedback.removeClassName('visible');
      effects.push(new Effect.Fade(feedback, { sync: true }));   
    }
    form.disable();
    effects.push(new Effect.Opacity(form, { sync: true, from: 1.0, to: 0.25 }));
    new Effect.Parallel(effects, { duration: 0.5 });
  },
  
  enable: function() {
    var form = Survey.form();
    new Effect.Opacity(form, { from: 0.25, to: 1.0, duration: 0.5, afterFinish: function() {
      form.enable();
    }});
  }
};

Comment = {
  failedMessage: "There was a problem delivering your message. Please review your entries and try again.",
  successMessage: "Thanks for the comments!",
	submitButton: function(){ return $('comment_submit') },
	formID: function(){ return $('contactForm') },
	inputs: function() { return Comment.formID().getElements().reject(function(i) { return i.type == "submit" })},
	
	attachHints: function() {
		$('contactForm').getElements().each(function(e) {
			if (e.type != 'submit') { e.defaultValueActsAsHint() };
		});
	},
	
	respond: function(response) {
		if (response) {
			Comment.success();
		} else {
			Comment.failure();
		}
		Comment.toggleSubmit();
	},
	
	success: function() {
		var inputs = Comment.inputs();
		var effects = $A();
		inputs.each(function(e) {
			effects.push(new Effect.Morph(e, {
				style: 'background: #94FF70;',
				sync: true
			}));
		});
		$('comment_feedback').update(Comment.successMessage);
		new Effect.Parallel(effects,{ duration: 0.5 });
		Comment.listenRetry(true);
	},
	
	failure: function() {
		var inputs = Comment.inputs();
		var effects = $A();
		inputs.each(function(e) {
			effects.push(new Effect.Morph(e, {
				style: 'background: #fec5c5;',
				sync: true
			}));
		});
		$('comment_feedback').update(Comment.failedMessage);
		new Effect.Parallel(effects,{ duration: 0.5 });
		Comment.listenRetry(false);
	},
	
	listenRetry: function(sent) {
	  new Event.observe('contactForm','click', function (event) {
		  if (Comment.inputs().include(event.element())) {
		    $('contactForm').stopObserving('click');
		    $('comment_feedback').update();
		    var effects = $A();
    		Comment.inputs().each(function(e) {
    			effects.push(new Effect.Morph(e, {
    				style: 'background: #ffffff;',
    				sync: true
    			}));
    			new Effect.Parallel(effects,{ duration: 0.5 });
    			if (sent) $('contactForm').reset();
    		});
		  }
		});
	},
	
	toggleSubmit: function() {
		var button = Comment.submitButton();
		if (button.disabled) {
			button.disabled = false;
			button.value = "Send Comment";
		} else {
			button.disabled = true;
			button.value = "Sending. . .";
		}
	}
};

Faq = {
	data: null,
	updateAnswer: function(id) {
		$$('div#questions ol li a.selected').invoke('removeClassName','selected');
		var h3 = id == 0 ? "Pet Links" : "Answers:";
		$('answer').update("<h3>" + h3 + "</h3>" + Faq.data[id].answer);
		new Effect.Highlight('q' + id, { startcolor: '#aaaaaa', endcolor: '#3e3e3e' });
		new Effect.Highlight('answer', { startcolor: '#aaaaaa', endcolor: '#3e3e3e' });
		$('q' + id).addClassName('selected');
	},
	
	resetBG: function(id) {
		$(id).setStyle({ background: "none" });
	}
};

Menu = {
	assignObservers: function(){
  	Event.observe('topMenu', "mouseover", function(event) { Menu.over(event.element()); });
		Event.observe('topMenu', "mouseout", function(event) { Menu.out(event.element()); });
		Event.observe('topMenu', "click", function(event) { Panel.fetch(event); });
  },
	
	over: function(newTarget) {
		var adjacent = newTarget.hasClassName('last') ? false : newTarget.next('a');
		if (adjacent) {
			newTarget.addClassName('hover');
			adjacent.addClassName(adjacent.hasClassName('last') ? 'lastAdjacentHover' : 'adjacentHover');
		} else {
			newTarget.addClassName('lastHover');
		}
		
	},
	
	out: function(target) {
		var adjacent = target.hasClassName('last') ? false : target.next('a');
		if (adjacent) {
			target.removeClassName('hover');
			adjacent.removeClassName(adjacent.hasClassName('last') ? 'lastAdjacentHover' : 'adjacentHover');
		} else {
			target.removeClassName('lastHover');
		}
	},
	
	assignSelected: function(locationMatch) {
		$$('div#topMenu a.selected').each(function(e) {
			e.removeClassName('selected');
			e.removeClassName('lastSelected');
			if (!e.hasClassName('last')) e.next('a').removeClassName('selectedAdjacent');
		});
		
		locationMatch = locationMatch == "/home" ? "/" : locationMatch;
		var selected = $$('div#topMenu a[href=' + locationMatch + ']')[0];
		
		if (selected.hasClassName('last')) {
		  selected.addClassName('selected');
			selected.addClassName('lastSelected');
		} else {
			selected.addClassName('selected');
			selected.next('a').addClassName('selectedAdjacent');
		}
	},
	
	assignFirstAndLast: function() {
		var items = $$('div#topMenu a');
		items.first().addClassName('first');
		items.last().addClassName('last');
	}
};

Panel = {
	staged: null,
	box: {
		home: 		{ copy: null, size: 481 },
		staff: 		{ copy: null, size: 377 },
		services: { copy: null, size: 590 },
		facility: { copy: null, size: 423 },
		shopping: { copy: null, size: 345 },
		faqs: 		{ copy: null, size: 346 },
		survey: 	{ copy: null, size: 1050 }
	},
	
	fetch: function(event) {
		Event.stop(event);
		var element = event.element();
		var panel = element.href.split('/').last() || "home";
		if (panel == Panel.staged) {
			return false;
		} else {
			var request = (Panel.box[panel].copy == null) ? true : false;
			var c = $('copy');
			
			Panel.store(c);
			
			new Effect.Opacity(c, { 
				from: 1.0, 
				to: 0.0, 
				duration: 0.5,
				afterFinish: function() {
					if ($('errorMessage')) $('errorMessage').remove();
					if (request) {
						Panel.request(c, panel);
					} else {
						Panel.success(Panel.box[panel].copy, c, panel);
					}
					return true;
				}
			});
		}

	},
	
	request: function(c, panel) {
		new Ajax.Request('/ajax/' + panel, {
			method: 'get',
			onSuccess: function(transport) { Panel.success(transport.responseText, c, panel) },
			onFailure: function(transport) { Panel.failure(c) }
		});
	},
	
	success: function(data, c, panel) {
		Menu.assignSelected("/" + panel);
		Panel.staged = panel;
		
		new Effect.Morph(c, {
			style: { height: Panel.box[panel].size + 'px' },
			duration: 0.5,
			afterFinish: function() {
				c.update(data);
				new Effect.Opacity(c, {
					from: 0,
					to: 1,
					duration: 0.5,
					afterFinish: Panel.reRegister
				});
			}
		});
	},
	
	failure: function(c) {
		var errorMessage = "<p>Unfortuantely, your request could not be completed. Please try again after a moment. "
											+"If this error persists, please let us know so we can get it fixed. "
											+"Thank you for your patience.</p>"
		var errorDiv = new Element('div', { id: "errorMessage" }).update(errorMessage);
		c.insert({ before: errorDiv });
		new Effect.Opacity(c, {from: 0, to: 1, duration: 0.5})
	},
	
	store: function(c,panel) {
		if (Panel.box[Panel.staged].copy == null) {
			Panel.box[Panel.staged].copy = c.innerHTML;
		}
	},
	
	reRegister: function() {
		switch (Panel.staged) {
			case "facility":
				if (window.Facility) {
					Facility = new imageSet('imageContainer', window.Facility.data, 'facility');
				}
			break;
			default:
				return true;
		}
	}
};

(function(){
  var methods = {
    defaultValueActsAsHint: function(element){
      element = $(element);
      element._default = element.value;
      
      return element.observe('focus', function(){
        if(element._default != element.value) return;
        element.removeClassName('hint').value = '';
      }).observe('blur', function(){
        if(element.value.strip() != '') return;
        element.addClassName('hint').value = element._default;
      }).addClassName('hint');
    }
  };
   
  $w('input textarea').each(function(tag){ Element.addMethods(tag, methods) });
})();

var imageSet = Class.create({
	initialize: function(element, data, locale) {
		element = $(element);
		
		this.locale = locale;
		this.data = data;
		this.photoBox = element.down('div.photoBox');
		this.photoDetail = element.down('div.photoDetail');
		this.dataBox = element.down('div.dataBox');
		
		this.cacheImages();
	},
	
	initObservers: function() {
		this.photoBoxHandler = this.galleryClicks.bind(this);
		this.photoBox.observe('click', this.photoBoxHandler);
		
		this.photoDetailHandler = this.detailClicks.bind(this);
		this.photoDetail.observe('click', this.photoDetailHandler);
	},
	
	cacheImages: function() {
		var locale = this.locale;
		this.data.each(function(e) {
			e.image = new Element('img', { src: '/images/' + locale + '/' + e.id + '.jpg' });
		});
		this.initObservers();
	},
	
	galleryClicks: function(event) {
		Event.stop(event);
		var anchor = event.findElement('a');
		if (!anchor) { return false };
		this.showDetail(anchor.href.split('/').last());
	},
	
	detailClicks: function(event) {
		Event.stop(event);
		
		var effects = [];
		effects.push(new Effect.Opacity(this.photoBox, { sync: true, from: 0.25, to: 1.0 }));
		effects.push(new Effect.Fade(this.photoDetail, { sync:true }));
		this.handleEffects(effects);
	},
	
	showDetail: function(id) {
		id -= 1;
		var data = this.data[id];
		var caption = data.caption || "";
		var details = "<h2>" + data.title + "</h2><p>" + caption + "</p>"
		
		this.photoDetail.down('div.bigImage').update(data.image);
		this.photoDetail.down('div.dataBox').update(details);
		
		var effects = [];
		effects.push(new Effect.Opacity(this.photoBox, { sync: true, from: 1.0, to: 0.25 }));
		effects.push(new Effect.Appear(this.photoDetail, { sync: true }));
		this.handleEffects(effects);
	},
	
	handleEffects: function(effects) {
		new Effect.Parallel(effects, {
			duration: 0.5
		})
	}
});
