if(!window['om']) {
	window['om'] = {};
	var om = window['om'];
}

om.browserSucks = (jQuery.browser.msie && jQuery.browser.version < 7);

(function(){
	var $ = jQuery;
	
	$(document).ready(function() {
		om.signup();
		om.heroshot();
		om.gallery();
		om.lightbox();
		om.locations();
		$('a').click(function() { $(this).blur(); });
		om.tableFix();
	});
	
	$(window).load(function() {
		om.tableFix();
	});
	
	om.heroshot = function() {
		om.heroshot.container = $('div.heroshot');
		if(!om.heroshot.container.size()) { return; }
		
		om.heroshot.container.addClass('loading');

		om.heroshot.wrapper = $(jQuery('<div class="heroshot-wrapper" />'));
		om.heroshot.container.append(om.heroshot.wrapper);
		
		om.heroshot.slider = $(jQuery('<div class="slider" />'));
		om.heroshot.wrapper.append(om.heroshot.slider);
		
		om.heroshot.heroes = false;
		om.heroshot.duration = 5;
		om.heroshot.transition = 2;
		om.heroshot.loop = null;

		$.getJSON(
			'/images/heroshots/heroshots.json',
			{},
			function(data) {
				om.heroshot.default_image = 0;
				om.heroshot.duration = typeof data.duration != 'undefined' ? data.duration : om.heroshot.duration;
				om.heroshot.link = typeof data.link != 'undefined' ? data.link : '';
				om.heroshot.transition = typeof data.transition != 'undefined' ? data.transition : om.heroshot.transition;
				om.heroshot.heroes = typeof data.heroes != 'undefined' ? data.heroes : om.heroshot.heroes;
				if(om.heroshot.heroes) {
					om.heroshot.heroes.sort(function() { return Math.round(Math.random())-0.5; });
				}
				om.heroshot.init();
			}
		);
		
		om.heroshot.init = function() {
			if(om.heroshot.heroes) {
				$.each(om.heroshot.heroes,function(i) {
					this.count = (i+1);
					if (typeof om.heroshot.heroes[i]['default'] != 'undefined' && om.heroshot.heroes[i]['default'] == true) {
						om.heroshot.default_image = i;
					}
				});
				if (om.heroshot.default_image != 0) {
					var temp = om.heroshot.heroes[0];
					temp.count = om.heroshot.default_image+1;
					om.heroshot.heroes[om.heroshot.default_image].count = 1;
					om.heroshot.heroes[0] = om.heroshot.heroes[om.heroshot.default_image];
					om.heroshot.heroes[om.heroshot.default_image] = temp;
				}
			}
			var firstImage = om.heroshot.heroes ? om.heroshot.heroes[0] : {'image':'/images/heroshots/hero-default.png','count':0,'duration':om.heroshot.duration};
			om.heroshot.loadImage(firstImage,function(image){ $(image).css({'display':'none'}).attr({'current':'current'}).fadeIn('normal',function() { om.heroshot.container.removeClass('loading'); }); });
			if(om.heroshot.heroes.length > 1) {
				om.heroshot.prev = $(jQuery('<a href="#previous" class="prev" title="Previous">&laquo; Previous</a>'));
				om.heroshot.container.append(om.heroshot.prev);
				om.heroshot.prev.click(function(c) {
					c.preventDefault();
					clearTimeout(om.heroshot.timer);
					//clearInterval(om.heroshot.loop);
					om.heroshot.rotate('prev');
					//om.heroshot.queueNext();
					//om.heroshot.autoplay();
				});
				om.heroshot.next = $(jQuery('<a href="#next" class="next" title="Next">Next &raquo;</a>'));
				om.heroshot.container.append(om.heroshot.next);
				om.heroshot.next.click(function(c) {
					c.preventDefault();
					clearTimeout(om.heroshot.timer);
					//clearInterval(om.heroshot.loop);
					om.heroshot.rotate('next');
					//om.heroshot.autoplay();
				});
				om.heroshot.next.fadeIn();
				//om.heroshot.autoplay();
				om.heroshot.queueNext(firstImage.duration);
			}
		}
		
		om.heroshot.queueNext = function(duration) {
			om.heroshot.timer = setTimeout(function() {
				om.heroshot.rotate();
			}, (duration + om.heroshot.transition) * 1000)
		}
		
		om.heroshot.autoplay = function() {
			om.heroshot.loop = setInterval(function(){
				om.heroshot.rotate();
			}, (om.heroshot.duration + om.heroshot.transition) * 1000)
		}
		
		om.heroshot.loadImage = function(image, callback, append) {
			//alert('loadImage(' + image.count + ')');
			if(typeof image == 'undefined') { return; }
			if(typeof append == 'undefined') { var append = true; }
			var thisImage = new Image();
			thisImage.duration = (typeof image.duration == 'undefined') ? om.heroshot.duration : image.duration;
			thisImage.onload = function() {
				om.heroshot.slider.width(om.heroshot.slider.width() + thisImage.width);
				thisImage.count = image.count;
				//alert('onload: ' + image.count);
				if($.browser.msie && $.browser.version < 7) {
					var finalImage = $(jQuery('<img src="/images/clear.gif" style="filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + thisImage.src + '\', sizingMethod=\'crop\');" />')).width(thisImage.width).height(thisImage.height);
				} else {
					var finalImage = $(thisImage);
				}
				finalImage.data("duration", thisImage.duration);
				if(append) {
					om.heroshot.slider.append(finalImage);
				} else {
					om.heroshot.slider.css({
						'left': parseInt(om.heroshot.slider.css('left'),10) - thisImage.width
					}).prepend(finalImage);
				}
				if(typeof image.link != 'undefined') {
					$(thisImage).css({'cursor':'pointer'}).click(function() {
						window.location = image.link;
					});
				}
				//alert(image.count + ' < ' + om.heroshot.heroes.length);
				if(image.count < om.heroshot.heroes.length) {
					//alert('call loadImage(' + image.count + ')');
					om.heroshot.loadImage(om.heroshot.heroes[image.count]);
				}
				if(typeof callback == 'function') { callback(finalImage); }
				return finalImage;
			}
			thisImage.src = image.image;
			//return thisImage;
		}
		
		om.heroshot.rotate = function(direction) {
			if(om.heroshot.slider.is(':animated')) { return; }

			if(typeof direction == 'undefined') { direction = 'next'; }
			var current = om.heroshot.slider.find('img[current]'); 
			var to = null;
			if(direction == 'next' && current.next().size()) {
				to = current.next();
				current.removeAttr('current');
				to.attr({'current':'current'});
				var newLeft = (parseInt(om.heroshot.slider.css('left'),10) - to.width());
				om.heroshot.slider.animate({
					'left': newLeft
				},om.heroshot.transition * 1000);
			} else if(direction == 'next') {
				var currentWidth = om.heroshot.slider.width();
				var duration = ("undefined" == typeof current.siblings(':first-child')[0]) ? om.heroshot.duration : current.siblings(':first-child')[0].duration;
				om.heroshot.loadImage({'image': current.siblings(':first-child').attr('src'), 'count': om.heroshot.heroes.length + 1, duration: duration}, function(to) {
					current.removeAttr('current');
					to.attr({'current':'current'});
					var newLeft = (parseInt(om.heroshot.slider.css('left'),10) - to.width());
					om.heroshot.slider.animate({
						'left': newLeft
					},om.heroshot.transition * 1000, function() {
						current.siblings(':first-child').attr({'current':'current'});
						om.heroshot.slider.css({'left':0,'width':currentWidth});
						to.remove();
					});
				});
				to = current.siblings(':first-child');
			} else if(direction == 'prev' && current.prev().size()) {
				to = current.prev();
				current.removeAttr('current');
				to.attr({'current':'current'});
				var newLeft = (parseInt(om.heroshot.slider.css('left'),10) + to.width());
				om.heroshot.slider.animate({
					'left': newLeft
				},om.heroshot.transition * 1000);
			} else {
				var currentWidth = om.heroshot.slider.width();
				
				var duration = ("undefined" == typeof current.siblings(':last-child')[0]) ? om.heroshot.duration : current.siblings(':first-child')[0].duration;
				om.heroshot.loadImage({'image': current.siblings(':last-child').attr('src'), 'count': om.heroshot.heroes.length + 1, duration: duration }, function(to) {
					current.removeAttr('current');
					to.attr({'current':'current'});
					var newLeft = (parseInt(om.heroshot.slider.css('left'),10) + to.width());
					om.heroshot.slider.animate({
						'left': newLeft
					},om.heroshot.transition * 1000, function() {
						current.siblings(':last-child').attr({'current':'current'});
						om.heroshot.slider.css({'left':(0 - (current.siblings(':last-child').position().left - to.outerWidth(true))),'width':currentWidth});
						to.remove();
					});
				}, false);
				to = current.siblings(':last-child');
			}
			var duration = ("undefined" == typeof om.heroshot.heroes[0].duration) ? om.heroshot.duration : om.heroshot.heroes[0].duration;
			if (to.length > 0) {
				duration = to.data("duration");
			}
			om.heroshot.queueNext(duration);
		}
	}
	
	om.gallery = function() {
		if(!$('body.gallery').size()) { return; }

		$('#main > .gallery-image > img').wrap($(jQuery('<div id="gallery-image" class="loading loading-light"></div>')));
		om.gallery.target = $('#gallery-image');

		var thumbs = $('a[rel=gallery]');
		
		var container = $(jQuery('<div class="thumbs-container"></div>'));
		container.prependTo($('#main'));
		container.html(thumbs.parent('div.thumbs'));
		
		var slider = $(jQuery('<div class="slider" style="left: 0"></div>'))
		slider.width(99 * thumbs.size());
		
		slider.appendTo(thumbs.parent());
		thumbs.each(function() {
			$(this).appendTo(slider);
		});
		
		var prev = $(jQuery('<a href="#prev" class="prev" style="visibility: hidden">Previous</a>'));
		var next = $(jQuery('<a href="#next" class="next">Next</a>'));
		
		container.prepend(prev);
		container.append(next);
		
		prev.add(next).each(function() {
			var link = $(this);
			link.click(function(c) {
				c.preventDefault();
				if(slider.is(':animated')) { return; }
				var newX = parseInt(slider.css('left'),10) - (link.hasClass('prev') ? (0 - 693) : 693);
				prev.add(next).css({'visibility':'visible'});
				if(newX >= 0) {
					newX = 0;
					prev.css({'visibility':'hidden'});
				} else if(newX <= (0 - slider.width()) + 693) {
					newX = (0 - slider.width()) + 693;
					next.css({'visibility':'hidden'});
				}
				slider.animate({
					'left': newX
				},1000);
			});
		});
		
		thumbs.each(function() {
			var thumb = $(this);
			thumb.click(function(c) {
				c.preventDefault();
				if(thumb.hasClass('current')) { return; }
				thumbs.removeClass('current');
				thumb.addClass('current');
				var currentImage = om.gallery.target.find('img');
				currentImage.fadeOut('normal',
					function() {
						var temp = new Image();
						temp.onload = function() {
							$(temp).css({'display':'none'});
							if(temp.width < temp.height) {
								om.gallery.target.parents('.gallery-image').removeClass('gallery-image-landscape').addClass('gallery-image-portrait');
							} else {
								om.gallery.target.parents('.gallery-image').removeClass('gallery-image-portrait').addClass('gallery-image-landscape');
							}
							
							om.gallery.target.append($(temp))
							$(temp).fadeIn('normal',
								function() {
									currentImage.remove();
								}
							);
						}
						temp.src = thumb.attr('href');
					}
				)
			});
		});

		thumbs.eq(0).click();
	}
	
	om.lightbox = function() {
		if(typeof ajax == 'undefined') { ajax = false; }
		if(typeof html == 'undefined') { html = ''; }
		if(!ajax) { om.lightbox.links = $('a[rel*=lightbox]') } else if(typeof html == 'object') { om.lightbox.links = html.find('a[rel*=lightbox]'); } else { return; }
		if(!om.lightbox.links.size()) { return; }
		if(!$('#overlay').size()) { $('body').append($(jQuery('<div id="overlay" style="display: none"></div>'))); }
		om.lightbox.overlay = $('#overlay');
		om.lightbox.overlay.click(function() { om.lightbox.closeLightbox(); });
		if(!$('#popup').size()) { $('body').append($(jQuery('<div id="popup" class="lightbox" style="display: none"></div>'))); }
		om.lightbox.popup = $('#popup');
		om.lightbox.closeLightbox = function() {
			om.lightbox.popup.fadeOut('normal', function(){ om.browserSucks ? om.lightbox.overlay.hide() : om.lightbox.overlay.fadeOut('normal') });
			om.lightbox.popup.fadeOut('normal', function() {
				om.lightbox.target.find('img').remove();
			});
		}

		if(!om.lightbox.popup.find('a.close').size()) {
			om.lightbox.close = $(jQuery('<a class="close" href="#close">Close</a>'));
			om.lightbox.close.click(function(c){ c.preventDefault(); om.lightbox.closeLightbox(); });
			om.lightbox.close.appendTo(om.lightbox.popup);
		}

		if(typeof om.lightbox.target == 'undefined') {
			om.lightbox.target = $(jQuery('<div class="content-wrapper"></div>'));
			om.lightbox.popup.append(om.lightbox.target);
		}

		om.lightbox.links.each(function(i){
			var link = $(this);
			link.click(function(c){
				c.preventDefault();
				link.blur();
				om.lightbox.links.removeAttr('current');
				link.attr({'current': 'current'});
				var img = new Image();
				img.onload = function() {
					$(img).appendTo(om.lightbox.target);
					om.browserSucks ? om.lightbox.overlay.show() : om.lightbox.overlay.fadeIn('normal');
					var new_css = {'width': img.width,'height': img.height,'margin-left': (0 - Math.round(img.width / 2)) + 'px','margin-top': (0 - Math.round(img.height / 2)) + 'px'};
					om.lightbox.popup.css(new_css);
					om.lightbox.popup.fadeIn('normal');
					if(ajax) { om.lightbox.overlay.find('.loading').remove() };
				}
				img.src = link.attr('href');
			})
		})
		om.lightbox.links.filter('[current]').size() ? null : $(om.lightbox.links[0]).attr({'current':'current'});
	}
	
	om.locations = function() {
		if(!$('html#map').size()) { return; }
		
		var locations = $('#sb.locations > ul > li');
		var map = $('#map-container');
		locations.each(function() {
			var location = $(this);
			var link = location.find('.title a');
			link.click(function(c) { c.preventDefault(); });
			location.click(function() {
				//	If we didn't come from web appointments set studio in background
				if (!om.u.match(/appointments/)) {
					$.ajax({
						type: "GET",
						url: "/locations/svc_set_studio.asp",
						data: "s=" + $(this).attr("id"),
						dataType: "text",
						success: function() {
							if (om.u != '') {
								top.location = om.u;
							}
						}
					});
				}
			

			
				if(map.find('div.location-info').size()) {
					//alert('remove');
					map.find('div.location-info').animate({'bottom':'0px'},500, function() { map.find('div.location-info').remove(); });
					var timeout = 550;
				} else {
					var timeout = 0;
				}
					
				om.map_overlay_visible = $(this).attr("id");
				setTimeout(function(){
					var info = $(jQuery('<div class="location-info"></div>'));
					info.html(location.html());
					info.css({'bottom':'-300px'}).appendTo(map).animate({'bottom': '0'},500);
				},timeout);
					
				if (typeof(om.mapMarkers) != "undefined" && typeof(om.mapMarkers[$(this).attr("id")]) != "undefined") {
					GEvent.trigger(om.mapMarkers[$(this).attr("id")], "click");
				}
				
			});
		});
	}

	
	om.signup = function() {
		$("#signup_email").bind("focus", function() {
			if ($("#signup_email").val() == 'you@yours.com')
				$("#signup_email").val('');
		});
	}
	
	om.tableFix = function() {
		$('table.content-wrapper').each(function() {
			var table = $(this);
			var height = table.height() - 587;
			table.find('td.left-middle,td.right-middle').height(height)
		});
	}
})();
