/**
 * Initialize $.CORE in case it's not present
 */
if(typeof $.CORE == "undefined") {
	$.CORE= Object;
};

/**
 * Section scaling
 */
$.CORE.scaling = {
	construct : function() {
		this.screenDetection();
	},
	
	screenDetection : function() {
		var wHeight = $(window).height();
		var wWidth = $(window).width();
			
		$(window).resize(function(){
			wHeight = $(window).height();
			wWidth = $(window).width();
		});
			
		// Scale screens
		$('section, .bg')
		.css({
			 width: wWidth,
			 height: wHeight
		});

		$.CORE.scaling.positionContent(wHeight);

		$(window).resize(function(){
			$('section, .bg')
			.css({
				 width: wWidth,
				 height: wHeight
			});
			
			$.CORE.scaling.positionContent(wHeight);
		});
			
		window.onorientationchange = function(){
			wHeight = $(window).height();
			wWidth = $(window).width();

			$('section, .bg')
			.css({
				 width: wWidth,
				 height: wHeight
			});
			
			$.CORE.scaling.positionContent(wHeight);
		}
	},
	
	positionContent : function(wHeight) {
		$('section .center, section .bg .center').each(function(){
			$(this).css({
				top: ((wHeight - $(this).height()) / 2) + 'px'
			});
		});
	}
}

/**
 * Parallax 
 */
$.CORE.parallax = {
	sections : '#home, #mission, #focus, #approach, #team, #contact',
	
	construct : function() {
		var _parallax = this;
		setTimeout(function(){
			_parallax.defineActiveSections();
		}, 500);
		
		$(window).bind('scroll', function(){
			_parallax.defineActiveSections();										  
		});

		setTimeout(function() {
			_parallax.isCurrentSection();
		}, 500);

		$(window).bind('scroll', function(){
			_parallax.isCurrentSection();
		});
		
		//if(!$.CORE.ua.mobile) {
			_parallax.handlerBg();
		//}
	},
	
	defineActiveSections : function() {
		$($.CORE.parallax.sections).each(function(i, e){
			if($.CORE.parallax.isScrolledIntoView(e)){
				$(e).addClass('active');
			} else {
				$(e).removeClass('active');
			}
		});
	},
	
	isScrolledIntoView : function(elem) {
		var docViewTop = $(window).scrollTop();
		var docViewBottom = docViewTop + $(window).height();

		var elemTop = $(elem).offset().top;
		var elemBottom = elemTop + $(elem).height();
	
		return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));		
	},
	
	isCurrentSection : function() {
		var viewElm = null;
		var viewArea = 0;
		$('section.active').each(function(index, section) {
			if(viewElm == null) {
				viewElm = section;
			}
			var viewAreaTmp = $(section).height() - Math.abs($(window).scrollTop() - $(section).offset().top);
			var viewAreaPrev = viewAreaTmp;
			if(viewAreaTmp > viewArea) {
				viewArea = viewAreaTmp;
				viewElm = section;
			}
			$(section).removeClass('current');
		});
		$(viewElm).addClass('current');
		$.CORE.nav.setActive(viewElm);
	},
	
	handlerBg : function(){
		$(window).bind('scroll', function() {
			$.CORE.parallax.positionBg();
		});
	},
	
	positionBg : function() {
		$('section.active .bg').each(function(){
			var contentOffsetTop = 0;
			var windowScrollTop = $(window).scrollTop();
			var sectionOffset = $(this).offset().top;
			
			var bgTopOffset = 0;
			bgTopOffset = $.CORE.parallax.calcParallaxUp(windowScrollTop + contentOffsetTop, sectionOffset, 0.8);

			$(this).css({ backgroundPosition : 'center ' + bgTopOffset + 'px' });
		});		
	},
	
	calcParallaxUp : function(windowScrollTop, sectionOffset, speedRatio) {
		return Math.round((windowScrollTop - sectionOffset) * speedRatio) * -1;
	}
};

/**
 * Navigation
 */
$.CORE.nav = {
	construct : function() {
		$('footer').css('visibility', 'visible');
		
		$.CORE.nav.scrollToSection();	

		setTimeout(function(){
			$.CORE.nav.setActive();
		}, 750);
		
		if($.CORE.ua.mobile) {
			$('#content')
			.css({
				height : $('#content').height() - 80
			});
		} else {
			$.CORE.nav.fixedNav();
			$(window).bind('scroll', function(){
				$.CORE.nav.setActive();			
			});
		}
	},
	
	fixedNav : function() {
		$('#header').css({
			position: 'fixed',
			top: 0
		});

		$('footer').css({
			position: 'fixed',
			bottom: 0
		});
	},
	
	setActive : function(viewElm) {
		var activeElm = null;
		if($('body').hasClass('autonav')) {
			$('nav li').removeClass('current');
			var activeId = $('section.current').attr('id');
			if(viewElm != null) {
				activeElm = viewElm;
				activeId = $(viewElm).attr('id');
			}
			$('nav a[rel="#' + activeId + '"]').parent().addClass('current');
		}
	},
	
	scrollToSection : function() {
		$('nav a').bind({
			'click': function(e){
				var _this = this;
				if(!$.CORE.ua.mobile) {
					var sectionTime = 500;
					var currIndex = parseInt($('#header nav li.current').index());
					if(currIndex < 0) {
						currIndex = 0;
					}
					var newIndex = parseInt($('nav a').index(_this));
					var duration = Math.abs(newIndex - currIndex) * sectionTime;
					$.scrollTo($(_this).attr('rel'), { duration: duration });
					e.preventDefault();					
				} else {
					$.CORE.parallax.defineActiveSections();
					$.CORE.parallax.isCurrentSection();
				}
			}
		});
	}
};

/**
 * UA sniffing
 */
$.CORE.ua = {
	mobile : false,
	version : null,
	checker : null,
	
	construct : function() {
		this.sniff();
	},
	
	sniff : function() {
		var ua = navigator.userAgent;

		if(ua.match(/OS 5/)) {
			$.CORE.ua.version = 'OS 5';
		}

		var checker = {
		  iphone: ua.match(/(iPhone|iPod|iPad)/),
		  blackberry: ua.match(/BlackBerry/),
		  android: ua.match(/Android/)
		};

		if (checker.android || checker.iphone || checker.blackberry){
			$.CORE.ua.mobile = true;
		}
		
		$.CORE.ua.checker = checker;
	}
};

/**
 * Scrolling
 */
$.CORE.scrolling = {
	construct : function() {
		this.cycle();
	},
	
	cycle : function() {
		if($('.scroller').length > 0) {
			$('.scroller').each(function(){
				var $parent = $(this).parent();
				
				$.data($parent, 'index', 0);
				$.data($parent, 'total', $('.bg', $parent).length);
				$('.bg:eq(0)', $parent).addClass('activeSlide');
				$('.next, .discover', $parent).bind('click', function(e){
					var left = $('.scroller', $parent).css('left');
					var index = $.data($parent, 'index');
					var total = $.data($parent, 'total');
					if(index < total-1) {
						$('.scroller', $parent).animate({
							left: (index+1) * $(window).width() * -1
						}, 500);
						$.data($parent, 'index', ++index);
					}
					$('.bg:not(:eq('+ index +'))', $parent).removeClass('activeSlide');
					$('.bg:eq('+ index +')', $parent).addClass('activeSlide');
					if(index == total-1) {
						$('.next', $parent).fadeOut('slow');
					}
					if(index > 0 && index < total) {
						$('.prev', $parent).fadeIn('slow');
					}
					e.preventDefault();
				});
				$('.prev', $parent).bind('click', function(e){
					var left = $('.scroller', $parent).css('left');
					var index = $.data($parent, 'index');
					var total = $.data($parent, 'total');
					if(index > 0) {
						$('.scroller', $parent).animate({
							left: (index-1) * $(window).width() * -1
						}, 500);
						$.data($parent, 'index', --index);
					}
					$('.bg:not(:eq('+ index +'))', $parent).removeClass('activeSlide');
					$('.bg:eq('+ index +')', $parent).addClass('activeSlide');
					if(index == 0) {
						$('.prev', $parent).fadeOut('slow');
					}
					if(index < total) {
						$('.next', $parent).fadeIn('slow');
					}
					e.preventDefault();
				});
			});
			
			$(window).resize(function(){
				$('.scroller').each(function(){
					var $parent = $(this).parent();
					$('.scroller', $parent).css({
						left: $('.activeSlide', $parent).index() * $(window).width() * -1
					});
				});
			});
		}
	}
};

/**
 * Video
 */
$.CORE.video = {
	videoPanels : '#vid1',
	
	construct : function() {
		if($('#home').length > 0) {		
			$.CORE.video.linkVideo();
			$.CORE.video.closeVideo();
		}
	},
	
	linkVideo : function() {
		$('.panel-video').bind('click', function(e){
			$('<div>')
			.attr('id', 'video-mask')
			.attr('class', $(this).attr('href').replace('#', ''))
			.css({
				height: '100%',
				width: '100%',
				opacity: 0
			})
			.appendTo('body')
			.animate({
				opacity: 0.7
			});
			
			var width = $($(this).attr('href')).width();
			var height = $($(this).attr('href')).height();
			$($(this).attr('href'))
			.hide()
			.css({
				left: '50%',
				marginLeft: width / 2 * -1,
				marginTop: height / 2 * -1
			})
			.fadeIn('slow');
			e.preventDefault();
		});
	},
	
	closeVideo : function() {
		$('#video-mask').live('click', function(){
			$.CORE.video.fadeOut($(this).attr('class'));
		});
		
		$('a.close').live('click', function(e){
			$.CORE.video.fadeOut($('#video-mask').attr('class'));
			e.preventDefault();
		});
	},
	
	fadeOut : function(vidClass) {
		$('#' + vidClass)
		.fadeOut(function(){
			$(this)
			.css({
				left: -9999
			});
		});

		$('#video-mask')
		.animate({
			opacity: 0
		}, 500, function(){
			$(this).remove();
		});		
	}
};

/**
 * Forms
 */
$.CORE.forms = {
	construct : function() {
		this.execFormCheckerPlugin();
		this.eraseBreask();
		this.sheduleMeeting();
		this.radioButtons();
	},
	
	execFormCheckerPlugin : function() {
		var $formRef = $('form.formGenerated');
		if($formRef.length) {
        	$formRef.formChecker();
		}
	},
	
	eraseBreask : function() {
		$('.block br').remove();
	},
	
	sheduleMeeting : function() {
		var sheduleForm = '#shedule-meeting form';
		$(sheduleForm).bind('submit', function(){
			if($(sheduleForm +' .error').length == 0) {
				$.ajax({
					type: "POST",
					url: "",
					data: $(sheduleForm).serialize(),
					beforeSend : function() {
						$(sheduleForm).fadeOut('fast');
					},
					success: function(msg){
						var $response = $('<div>')
						.attr('id', 'responseSheduleMeeting')
						.append($('#message', msg).html())
						.hide();

						$(sheduleForm).parent().append($response).find('#responseSheduleMeeting').fadeIn();
					},
					error: function(jqXHR, textStatus, errorThrown){
						//alert(textStatus);
					}
				});
			}
			return false;
		});
	},

	radioButtons : function() {
		$('form .block label').bind({
			mouseenter: function() {
				if(!$.CORE.ua.mobile) {
					$(this).addClass('hover');
				} else {
					$('label').removeClass('selected');
					$('label', $(this).parent()).removeClass('selected');
					$(this).addClass('selected');
				}
			},
			mouseleave: function() {
				if(!$.CORE.ua.mobile) {
					$(this).removeClass('hover');
				}
			},
			click: function() {
				$('label').removeClass('selected');
				$('input', $(this).parent()).attr('selected', null);
				$(this).prev().attr('selected', 'selected');
				$('label', $(this).parent()).removeClass('selected');
				$(this).addClass('selected');
			}
		});
	}
};

/**
 * Circle
 */
$.CORE.promo = {
	construct : function() {
		if($('#home').length > 0) {		
			setTimeout(this.slideIn, 1000);
			this.circle();
		}
	},
	
	slideIn : function() {
		$('#circle').animate({
			top: 0
		}, 1500);
	},
	
	circle : function() {
		$('#circle #cClose').bind('click', function(e){
			$(this).parent().fadeOut();
			e.preventDefault();
		});
	}
};

/**
 * Executes when the DOM has been fully loaded
 */
$(document).ready(function() {
	$.CORE.ua.construct();
	$.CORE.scaling.construct();
	$.CORE.parallax.construct();
	setTimeout(function(){
		$.CORE.nav.construct();
		$.CORE.promo.construct();
		$.CORE.video.construct();
		$.CORE.scrolling.construct();
		$.CORE.forms.construct();
	}, 750);
	setTimeout(function(){
		$('#mask').fadeOut(1000, function(){
			$(this).remove();
		});
	}, 1000);
});
