
// Initialization commands

$.fn.pause = function(length){
	$(this).animate({left:$(this).css('left')},length);
	return this;
}


var Site = {

	init:function(page, subIndex){		

		try{$.localScroll();}catch(e){}		
		
		// Add last-child class to <li> elements for IE6
		$('ul li:last-child').addClass('last-child');
		
		// Set all http:// urls to open in new window
		$('a').each(function(){
			var a= $(this);
			if(a.attr('href').match(/^http/i) || a.is('.new-window')){
				a.click(function(){
					window.open(this.href,'popWin');
					return false;
				});
			}
		});
						
		// Render side navigation
		Site.sideNavInit(page, subIndex,function(){
			$('.content-callout').slideDown(1100);			
		});	
		
		// Setup galleries if necessary
		if(page.match(/gallery/)){
			Site.galleryInit();
		}
		
		// Setup contact form validation if necessary
		if(page == '/contact/form'){
			jQuery.validator.addMethod("phone", function(phone_number, element) {
				phone_number = phone_number.replace(/\s+/g, "");
				return this.optional(element) || phone_number.length > 9 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
				}, 
				"Please provide a valid phone number"
			);

			$().ready(function() {
				// validate the comment form when it is submitted	
				$("#contact").validate();
			});
		}
		
		// Run home page animation and load flash
		if(page == 'home'){ 
			
			var n = $('#nav');
			var nw = n.width()-2;
			var ww = $(window).width();
			var o = n.offset();		
			var c = $(n.get(0).cloneNode(false));
			var images = $('#nav img');
		
			images.each(function(){
				var me= $(this);
				var src = me.attr('src');
				var _img = $('<img>').attr('src',src.replace(/\.gif$/,'-over.gif')); // Preload hover state
			
				me.get(0).storedBgImage = me.parent().parent().css('backgroundImage');
				me.parent().parent().css({overflow:'hidden',position:'relative',zIndex:10,backgroundImage:'none'}); // Set position for animation
				me.css({position:'relative',left:0,top:me.height(),zIndex:9});	// Set position for animation		
			});
		
			n.get(0).storedBorderColor = n.css('borderColor');
			n.css({borderColor:'#FFF'}); // Clear border from current #nav
		
			$('body').append(c); // Add cloned #nav
		
			// Start animating horizontal line
	
			c.css({width:2,position:'absolute',top:o.top,left:ww/2-1}).animate({left:'-='+(nw/2),width:nw},750,function(){
				n.css({borderColor:n.get(0).storedBorderColor});
				c.remove();
			
				var cnt = 0;
				var done = 0;
			
				images.each(function(){
					var me= $(this);
					if(cnt > 0) me.pause(cnt * 100); // Pause after each
					me.animate({top:0},500,function(){
						me.parent().parent().css({backgroundImage:me.get(0).storedBgImage,position:'static',overflow:'visible'});
					
						if(done == images.length-1){	
							Site.navInit(page);
							Site.mainNavInit(page);		
							Site.flashInit(page);			
						}
						done++;
					});

					cnt++;
				});				
			});
		}else{
			
			// Initialize all otther navigations and flash
			Site.navInit(page);
			Site.mainNavInit(page);		
			Site.flashInit(page);
		}
		
	},
	flashInit:function(page){	

		switch(page){			
			case 'home':
			 swfobject.embedSWF('/flash/VORHomeApplication.swf', 'flash', '934', '365', '9.0.28', '/flash/expressInstall.swf', {}, {base :'/flash',bgcolor: '#ffffff',wmode:'opaque'}, {id: 'VORHomeApplicationSWF'});
			break;		
		
			default:
			 swfobject.embedSWF('/flash/VORTemplateApplication.swf', 'flash', '934', '216', '9.0.28', '/flash/expressInstall.swf', {dataSource: '/flash/VORTemplateApplication.inky.xml.php?page='+escape(page)}, {base :'/flash',bgcolor: '#ffffff',wmode:'transparent'}, {id: 'VORTemplateApplication', scale: 'noscale'});
			break;				
		}
		
	},
	navInit:function(page){

		$('#nav>ul>li>a').each(function(){
			var me = $(this);
			
			// Find menus
			//var hasMenu = me.next('ul').length > 0 ? true : false;
			var hasMenu  = false; // Disabled dropdown menus
			if(hasMenu){
				var menu  = me.next('ul');
				menu.css({zIndex:5000});
				me.get(0).menuTimer = null;
				me.get(0).menuActive = false;
			
				// Set mouseover for menu item
				menu.bind('mouseover',function(e){
					me.get(0).menuActive = true;
					if(!me.is('.active') && !me.is('.current')){
						var src = me.find('img').attr('src');
						me.find('img').attr('src',src.replace(/\.gif$/gi,'-over.gif'));
						me.addClass('active');
					}
					clearTimeout(me.get(0).menuTimer);
				}).bind('mouseout',function(e){
					me.get(0).menuActive = false;
					me.get(0).menuTimer = setTimeout(function(){
						if(me.get(0).menuActive == false){
							menu.slideUp('fast',function(){
								me.removeClass('active');	
								if(!me.is('.current')){						
									var src = me.find('img').attr('src');
									me.find('img').attr('src', src.replace(/-over/gi,''));
								}
							});							
						}
					},250);
				});
			}
			
			// Set mouseover for nav item
			me.bind('mouseover',function(e){
				var me = $(e.target);
				while(!me.is('A')) me = me.parent();
				var offset = me.offset();

				me.get(0).menuActive = true;
				if(!me.is('.active') && !me.is('.current')){
					var src = me.find('img').attr('src');
					me.find('img').attr('src',src.replace(/\.gif$/gi,'-over.gif'));
					me.addClass('active');
				}
				
				if(hasMenu){					
					menu.removeClass('flipped');					
					clearTimeout(me.get(0).menuTimer);					
					if(offset.left + menu.width() > $(window).width()){
						offset.left = offset.left + me.get(0).offsetWidth - menu.width();
						menu.addClass('flipped');
					}					
					menu.css({left:offset.left,top:offset.top+me.height()-10});				
					menu.slideDown('fast');
				}
			})
			.bind('mouseout',function(e){
				var me = $(e.target);
				while(!me.is('A')) me = me.parent();
			
				if(hasMenu){
					me.get(0).menuActive = false;
					me.get(0).menuTimer = setTimeout(function(){
						if(me.get(0).menuActive == false){
							menu.slideUp('fast',function(){
								me.removeClass('active');		
								if(!me.is('.current')){						
									var src = me.find('img').attr('src');
									me.find('img').attr('src', src.replace(/-over/gi,''));
								}	
							});							
						}
					},100);	
				}else{
					me.removeClass('active');					
					if(!me.is('.current')){						
						var src = me.find('img').attr('src');
						me.find('img').attr('src', src.replace(/-over/gi,''));
					}	
				}
			});			
					
		});			
	},
	mainNavInit:function(page){
		var page = page.replace(/^\//,'').split(/\//).slice(0,1);
		page = page == '' ? 'home' : page;
		var re = new RegExp(page, 'gi');
		$('#nav>ul>li>a').each(function(){	
			var atag = $(this);		
			if(atag.attr('href').match(re)){
				var img = atag.find('img');
				var src = img.attr('src');
				img.attr('src',src.replace(/\.gif$/gi,'-over.gif'));
				atag.addClass('active').addClass('current');
			}
		});
		
	},
	sideNavInit:function(page, menuIndex, callBack){
		var origpage = page;
		var path = page.replace(/^\//,'').split(/\//);
		var page = path.slice(0,1);
		var subpage = path.slice(1,1);
		var menuIndex = typeof menuIndex == 'undefined' ? 1 : isNaN(menuIndex) ? 1 : menuIndex;	

		$('#side-nav li.'+page).slideDown('fast',function(){;
			var atag = $(this).find('ul>li:nth-child('+menuIndex+')>a');
			var atag = $(atag.get(0));			
			atag.addClass('active');
			if(atag.next('ul').length > 0){
				atag.next('ul').slideDown(500,function(){
					var subtag  = $(this);
					subtag.find('a').each(function(){
						if($(this).attr('href') == origpage){
							$(this).addClass('subactive');
						}
					});
					if(typeof callBack == 'function'){
						callBack.apply(this,[this]);
					}
				});			
			}else{
				if(typeof callBack == 'function'){
					callBack.apply(this,[this]);
				}				
			}
		});		
	},
	galleryInView:false,
	galleryImageLoaded:false,
	galleryInit:function(callBack){
		
		//if (!$.browser.msie) $('body').css('opacity', 0.999999); // Firefox opacity flicker fix
		
		var gallen = $('.gallery-module .photo').length;
		var cnt = 0;
		
		$('.gallery-module .photo').each(function(){
			var np = this; // Native
			var p = $(this); // jQuery
							
			// Use native <div class="photo"> for storing data
			np.hoverActive = null;
			np.hoverTimer = null;			
			
			// Stop <a> link from executing nad re-route to overlay
			p.find('a').bind('click',function(e){
				Site.loadGalleryImage(p);
				e.stopPropagation();
				return false;				
			});
			p
			.css({position:'relative',cursor:'pointer'})
			.mouseover(function(){			
				var o = p.offset();
				
				// Firefox 3 adds a pixel on absolute elements when the window is an odd number				
				var pixelFix = navigator.userAgent.match(/Firefox\/3\.\d/i) ? ($(window).width()%2 > 0 ? 1 : 0) : 0;
				
				clearTimeout(np.hoverTimer);
							
				if(np.hoverActive == null){
					var d = $('<div>')
					.addClass('gallery-hover').css({
						width:'155px',
						height:'105px',
						position:'absolute',
						top:o.top,
						opacity:.75,
						left:o.left + pixelFix,
						border:'10px solid #FFF',
						backgroundColor:'transparent',
						zIndex:1000
					}).mouseover(function(){
						$(this).css({cursor:'pointer'});
						clearTimeout(p.get(0).hoverTimer);
						np.hoverActive = true;
					}).bind('click',function(e){
						if(!Site.galleryInView){
							$.blockUI.defaults.baseZ = 32000;
							$.blockUI.defaults.fadeOut = 100; 
							$.blockUI.defaults.css.backgroundColor = 'transparent'; 
						    $.blockUI.defaults.overlayCSS = {  
						        backgroundColor:'#FFF',  
						        opacity: .35
						    };
							$('#content-flow-right').block({message:'<img src="/images/loadingAnimation.gif" />',css:{border:0}});
							$.scrollTo('#content-flow-right',1000,{onAfter:function(){$('#content-flow-right').unblock();Site.loadGalleryImage(p);}});
							Site.galleryInView = true;
						}else{
							Site.loadGalleryImage(p);
						}
						e.stopPropagation();
					}).mouseout(function(){
						np.hoverActive = false;
						np.hoverTimer = setTimeout(function(){
							if(np.hoverActive === false){
								$(np.hoverDiv).remove();
								np.hoverActive = null;
							}
						},10);
					});
					$('body').append(d);
					np.hoverDiv = d.get(0);					
				}
				np.hoverActive = true;
				
			})
			.mouseout(function(){
				var p = $(this);
				np.hoverActive = false;
				np.hoverTimer = setTimeout(function(){
					if(np.hoverActive === false){
						$(np.hoverDiv).remove();
						np.hoverActive = null;
					}
				},10);
			});
			
			if(cnt == gallen-1){		
				if(typeof callBack == 'function'){
					callBack.apply(this);
				}				
			}			
			cnt++;
		});	
		
		$('.gallery-paginate a').bind('click',function(e){
			e.stopPropagation();
			e.preventDefault();
			if(Site.galleryImageLoaded){
				$('#gallery-full').remove();
			}
			Site.loadGallery($(this).attr('href'));
		});	

		
	},
	loadGalleryImage:function(p){
		var imgPath = p.find('a').attr('href');
		
		// Create Overlay Div for Large Image
		
		var pos = $('.gallery-module').offset();
		
		$('body').append(
			$('<div>').attr({id:'gallery-full'}).css({
				position:'absolute',
				top:pos.top+30,
				left:pos.left,
				width:'535px',
				padding:'10px',
				background:'#FFF',
				border:'1px solid #999',
				height:'415px',
				zIndex:10000,
				display:'none'					
			}).append(
				// Add image
				$('<img>').attr({id:'gallery-full-image',src:imgPath}), 
				
				// Add Close Button
				$('<img>').attr('src','/images/gallery-close.gif').css({position:'absolute',bottom:10,right:10,cursor:'pointer'}).click(function(){
					$(this).parent().stop().fadeOut('slow',function(){
						$(this).remove();
						Site.galleryImageLoaded = false;
					});
				})								
			)							
		);
		
		var pics = $('.gallery-module .photo');
		var cnt = 0;
		var curpic = 0;
		pics.each(function(){
			if(this == p.get(0)){
				curpic = cnt;
			}
			cnt++;
		});				
						
		// Add Prev/Next Button

		var prevbtn = $('<img>').attr('src','/images/gallery-prev.gif').css({opacity:.25,position:'absolute',left:10,top:175,cursor:'pointer'});
		var nextbtn = $('<img>').attr('src','/images/gallery-next.gif').css({opacity:.25,position:'absolute',right:10,top:175,cursor:'pointer'});
		
		if(curpic < cnt-1){
			$('#gallery-full').append(
				nextbtn
					.hover(
						function(){$(this).css('opacity',.5)},function(){$(this).css('opacity',.25)}
					)
					.click(
						function(){
							var next= $(this);
							$('#gallery-full-image').fadeOut(function(){
								var grp = $('.gallery-module .photo:eq('+(curpic+1)+') a');
								if(grp.length ==0){
									$('#gallery-full').fadeOut('slow',function(){
										$(this).remove();
										return;
									});
								}else{
									$(this).attr('src', grp.attr('href')).fadeIn(function(){
										curpic++;
									});
								}
							});					
						}
					)
			);
		}
		
		if(curpic > 0){
			$('#gallery-full').append(
				prevbtn
					.hover(
						function(){$(this).css('opacity',.5)},function(){$(this).css('opacity',.25)}
					)				
					.click(function(){
						var prev= $(this);
						$('#gallery-full-image').fadeOut(function(){
							var grp = $('.gallery-module .photo:eq('+(curpic-1)+') a');
							if(grp.length ==0){
								$('#gallery-full').fadeOut('slow',function(){
									$(this).remove();
									return;
								});
							}else{
								$(this).attr('src', grp.attr('href')).fadeIn(function(){
									curpic--;
								});
							}
						});					
					}
				)
			);
		}		
		
		var loading = $('<img src="/images/loadingAnimation.gif" />').css({
			position:'absolute',
			top:170,
			left:200,
			zIndex:3000
		});
		
		$('.gallery-module').append(loading);		
		
		// Preload Image
		//$.ajax({url: imgPath, async:true, cache:true, complete:function(){
			loading.remove();
			$('#gallery-full').fadeIn();
			Site.galleryImageLoaded = true;
		//}});

		
	},
	loadGallery:function(path){
		// Must immeidately unbind all photo events or browser may not
		// clear from memory if the user activates one
		$('.gallery-module .photo').each(function(){
			$(this).unbind('mouseover').unbind('mouseout');											
		});

		var galleryParams = path.substr(path.indexOf('?')+1);
		var params = 'ajax=loadGallery&'+galleryParams;
		var loading = $('<img src="/images/loadingAnimation.gif" />').css({
			position:'absolute',
			top:170,
			left:200
		});

		var hgt = $('.gallery-module').height();
		
		$('.gallery-module').css({height:hgt});
		
		$.blockUI.defaults.baseZ = 32000;
		$.blockUI.defaults.fadeOut = 100; 
		$.blockUI.defaults.css.backgroundColor = 'transparent'; 
	   $.blockUI.defaults.overlayCSS = {  
	        backgroundColor:'#FFF',  
	        opacity: .35
	    };	

		$('.gallery-module').block({message:'<img src="/images/loadingAnimation.gif" />',css:{border:0}});			
		
		$.ajax({
			type	: "POST",
			url		: "/index.php",
			dataType: 'text',
			async	: true,
			data	: params,
			success: function(content){
				$('.gallery-module').fadeTo('slow',.25,function(){					
					$(this).html(content).fadeTo('slow',1,function(){
						$('.gallery-module').css({height:'auto'});
						Site.galleryInit(function(){
							$('.gallery-module').unblock();
						});									
					});
				});
			}
		});				
	}
}

