// init page
jQuery(function() {
	initCufon();
	initGallery();
	initFixedHeader();
})
jQuery(window).load(function() {
	initStreahImage();
	initBackgroundResize();
})

function initStreahImage() {
	var bg = jQuery('#no-fixed-bg .bg'),
		main = jQuery('#main'),
		win = jQuery(window);
	
	function streahImage() {
		if(bg.length) {
			main.css({
				minHeight: bg.height()
			})
		}
		else {
			main.css({
				minHeight: win.height() - 197
			})
		}
	}
	streahImage();
	win.resize(streahImage);
}

// initCufon
function initCufon() {
	Cufon.set('fontFamily', 'HelveticaNeueLTStd-Th');
	Cufon.replace('.info-box h2');
	Cufon.replace('.carousel li h3');
	Cufon.replace('.post h2');
	Cufon.replace('.contact-form h2');
	Cufon.replace('.contact-form .info-block h3');
	Cufon.replace('.contact-form label');
	Cufon.replace('#sidebar h2');
	Cufon.replace('.post-box h2');
	Cufon.replace('.post .visual .title');
};

// initGallery
function initGallery() {
	jQuery('.carousel-block').scrollGallery({
		sliderHolder: '.holder-frame',
		btnPrev:'a.link-prev',
		btnNext:'a.link-next',
		circleSlide:true,
		pauseOnHover:true,
		autoRotation:false,
		switchTime:5000,
		duration:650
	})
};

// fixed header
function initFixedHeader(){
	if (!jQuery.browser.msie && !jQuery.browser.version < 8) {
		var wrapper = jQuery('#wrapper');
		var hold = wrapper.find('div.fix-box');
		function positioning(){
			hold.css({left:wrapper.offset().left-jQuery(window).scrollLeft()})
		};
		positioning();
		jQuery(window).resize(positioning);
		jQuery(window).scroll(positioning);
	}
};

// scrolling gallery plugin
jQuery.fn.scrollGallery = function(_options){
	var _options = jQuery.extend({
		sliderHolder: '>div',
		slider:'>ul',
		slides: '>li',
		pagerLinks:'div.pager a',
		btnPrev:'a.link-prev',
		btnNext:'a.link-next',
		activeClass:'active',
		disabledPrevClass:'prev-disabled',
		disabledNextClass:'next-disabled',
		generatePagination:'div.pg-holder',
		curNum:'em.scur-num',
		allNum:'em.sall-num',
		circleSlide:true,
		pauseClass:'gallery-paused',
		pauseButton:'none',
		pauseOnHover:true,
		autoRotation:false,
		stopAfterClick:false,
		switchTime:5000,
		duration:650,
		easing:'swing',
		event:'click',
		splitCount:false,
		afterInit:false,
		vertical:false,
		step:false
	},_options);

	return this.each(function(){
		// gallery options
		var _this = jQuery(this);
		var _sliderHolder = _options.sliderHolder ? jQuery(_options.sliderHolder, _this) : _this;
		var _slider = jQuery(_options.slider, _sliderHolder);
		var _slides = jQuery(_options.slides, _slider);
		var _btnPrev = jQuery(_options.btnPrev, _this);
		var _btnNext = jQuery(_options.btnNext, _this);
		var _pagerLinks = jQuery(_options.pagerLinks, _this);
		var _generatePagination = jQuery(_options.generatePagination, _this);
		var _curNum = jQuery(_options.curNum, _this);
		var _allNum = jQuery(_options.allNum, _this);
		var _pauseButton = jQuery(_options.pauseButton, _this);
		var _pauseOnHover = _options.pauseOnHover;
		var _pauseClass = _options.pauseClass;
		var _autoRotation = _options.autoRotation;
		var _activeClass = _options.activeClass;
		var _disabledPrevClass = _options.disabledPrevClass;
		var _disabledNextClass = _options.disabledNextClass;
		var _easing = _options.easing;
		var _duration = _options.duration;
		var _switchTime = _options.switchTime;
		var _controlEvent = _options.event;
		var _step = _options.step;
		var _vertical = _options.vertical;
		var _circleSlide = _options.circleSlide;
		var _stopAfterClick = _options.stopAfterClick;
		var _afterInit = _options.afterInit;
		var _splitCount = _options.splitCount;

		// gallery init
		if(!_slides.length) return;

		if(_splitCount) {
			var curStep = 0;
			var newSlide = $('<slide>').addClass('split-slide');
			_slides.each(function(){
				newSlide.append(this);
				curStep++;
				if(curStep > _splitCount-1) {
					curStep = 0;
					_slider.append(newSlide);
					newSlide = $('<slide>').addClass('split-slide');
				}
			});
			if(curStep) _slider.append(newSlide);
			_slides = _slider.children();
		}

		var _currentStep = 0;
		var _sumWidth = 0;
		var _sumHeight = 0;
		var _hover = false;
		var _pause = false;
		var _stepWidth;
		var _stepHeight;
		var _stepCount;
		var _offset;
		var _timer;

		_slides.each(function(){
			_sumWidth+=$(this).outerWidth(true);
			_sumHeight+=$(this).outerHeight(true);
		});

		// calculate gallery offset
		function recalcOffsets() {
			if(_vertical) {
				if(_step) {
					_stepHeight = _slides.eq(_currentStep).outerHeight(true);
					_stepCount = Math.ceil((_sumHeight-_sliderHolder.height())/_stepHeight)+1;
					_offset = -_stepHeight*_currentStep;
				} else {
					_stepHeight = _sliderHolder.height();
					_stepCount = Math.ceil(_sumHeight/_stepHeight);
					_offset = -_stepHeight*_currentStep;
					if(_offset < _stepHeight-_sumHeight) _offset = _stepHeight-_sumHeight;
				}
			} else {
				if(_step) {
					_stepWidth = _slides.eq(_currentStep).outerWidth(true)*_step;
					_stepCount = Math.ceil((_sumWidth-_sliderHolder.width())/_stepWidth)+1;
					_offset = -_stepWidth*_currentStep;
					if(_offset < _sliderHolder.width()-_sumWidth) _offset = _sliderHolder.width()-_sumWidth;
				} else {
					_stepWidth = _sliderHolder.width();
					_stepCount = Math.ceil(_sumWidth/_stepWidth);
					_offset = -_stepWidth*_currentStep;
					if(_offset < _stepWidth-_sumWidth) _offset = _stepWidth-_sumWidth;
				}
			}
		}

		// gallery control
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				if ( ! _btnPrev.hasClass ( _disabledPrevClass ) ) {
					if(_stopAfterClick) stopAutoSlide();
					prevSlide();
				}
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				if ( ! _btnNext.hasClass ( _disabledNextClass ) ) {
					if(_stopAfterClick) stopAutoSlide();
					nextSlide();
				}
				return false;
			});
		}
		if(_generatePagination.length) {
			_generatePagination.empty();
			recalcOffsets();
			var _list = $('<ul />');
			for(var i=0; i<_stepCount; i++) $('<li><a href="#">'+(i+1)+'</a></li>').appendTo(_list);
			_list.appendTo(_generatePagination);
			_pagerLinks = _list.children();
		}
		if(_pagerLinks.length) {
			_pagerLinks.each(function(_ind){
				jQuery(this).bind(_controlEvent,function(){
					if(_currentStep != _ind) {
						if(_stopAfterClick) stopAutoSlide();
						_currentStep = _ind;
						switchSlide();
					}
					return false;
				});
			});
		}

		// gallery animation
		function prevSlide() {
			recalcOffsets();
			if(_currentStep > 0) _currentStep--;
			else if(_circleSlide) _currentStep = _stepCount-1;
			switchSlide();
		}
		function nextSlide() {
			recalcOffsets();
			if(_currentStep < _stepCount-1) _currentStep++;
			else if(_circleSlide) _currentStep = 0;
			switchSlide();
		}
		function refreshStatus() {
			if(_pagerLinks.length) _pagerLinks.removeClass(_activeClass).eq(_currentStep).addClass(_activeClass);
			if(!_circleSlide) {
				_btnPrev.removeClass(_disabledPrevClass);
				_btnNext.removeClass(_disabledNextClass);
				if(_currentStep == 0) _btnPrev.addClass(_disabledPrevClass);
				if(_currentStep == _stepCount-1) _btnNext.addClass(_disabledNextClass);
			}
			if(_curNum.length) _curNum.text(_currentStep+1);
			if(_allNum.length) _allNum.text(_stepCount);
		}
		function switchSlide() {
			recalcOffsets();
			if(_vertical) _slider.animate({marginTop:_offset},{duration:_duration,queue:false,easing:_easing});
			else _slider.animate({marginLeft:_offset},{duration:_duration,queue:false,easing:_easing});
			refreshStatus();
			autoSlide();
		}

		// autoslide function
		function stopAutoSlide() {
			if(_timer) clearTimeout(_timer);
			_this.addClass(_pauseClass);
			_autoRotation = false;
		}
		function autoSlide() {
			if(!_autoRotation || _hover || _pause) return;
			if(_timer) clearTimeout(_timer);
			_timer = setTimeout(nextSlide,_switchTime+_duration);
		}
		if(_pauseOnHover) {
			_this.hover(function(){
				_hover = true;
				if(_timer) clearTimeout(_timer);
			},function(){
				_hover = false;
				autoSlide();
			});
		}
		recalcOffsets();
		refreshStatus();
		autoSlide();

		// pause buttton
		if(_pauseButton.length) {
			_pauseButton.click(function(){
				if(_this.hasClass(_pauseClass)) {
					_this.removeClass(_pauseClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_this.addClass(_pauseClass);
					stopAutoSlide();
				}
				return false;
			});
		}
		
		_this.bind('pause', function() {
			_pause = true;
			if(_timer) clearTimeout(_timer);
		}).bind('play', function() {
			_pause = false;
			autoSlide();
		})

		if(_afterInit && typeof _afterInit === 'function') _afterInit(_this, _slides);
	});
};

// background resize init
function initBackgroundResize() {
	var holder = document.getElementById('bg');
	var images = holder.getElementsByTagName('img');
	for(var i = 0; i < images.length; i++) {
		backgroundStretcher.stretchImage(images[i]);
	}
	backgroundStretcher.setBgHolder(holder);
}

// image stretch module
backgroundStretcher = {
	images: [],
	holders: [],
	viewWidth: 0,
	viewHeight: 0,
	stretchByWindow: true, // or entire page
	init: function(){
		this.addHandlers();
		this.resizeAll();
		return this;
	},
	stretchImage: function(obj) {
		var img = new Image();
		img.onload = this.bind(function(){
			obj.iRatio = img.width / img.height;
			obj.iWidth = img.width;
			obj.iHeight = img.height;
			obj.style.msInterpolationMode = 'bicubic'; // IE7 fix
			this.resizeImage(obj);
		});
		img.src = obj.src;
		this.images.push(obj);
	},
	setBgHolder: function(obj) {
		this.holders.push(obj);
		this.resizeAll();
	},
	resizeImage: function(obj) {
		if(obj.iRatio) {
			var slideWidth = this.viewWidth;
			var slideHeight = slideWidth / obj.iRatio;
			if(slideHeight < this.viewHeight) {
				slideHeight = this.viewHeight;
				slideWidth = slideHeight * obj.iRatio;
			}
			obj.style.width = slideWidth+'px';
			obj.style.height = slideHeight+'px';
			obj.style.top = (this.viewHeight - slideHeight)/2+'px';
			obj.style.left = (this.viewWidth - slideWidth)/2+'px';
		}
	},
	resizeHolder: function(obj) {
		obj.style.width = this.viewWidth+'px';
		obj.style.height = this.viewHeight+'px';
	},
	getWindowWidth: function() {
		return typeof window.innerWidth === 'number' ? window.innerWidth : document.documentElement.clientWidth;
	},
	getWindowHeight: function() {
		return typeof window.innerHeight === 'number' ? window.innerHeight : document.documentElement.clientHeight;
	},
	getPageWidth: function() {
		if(!document.body) return 0;
		return Math.max(
			Math.max(document.body.clientWidth, document.documentElement.clientWidth),
			Math.max(document.body.offsetWidth, document.body.scrollWidth)
		);
	},
	getPageHeight: function() {
		if(!document.body) return 0;
		return Math.max(
			Math.max(document.body.clientHeight, document.documentElement.clientHeight),
			Math.max(document.body.offsetHeight, document.body.scrollHeight)
		);
	},
	resizeAll: function() {
		// crop holder width by window size
		for(var i = 0; i < this.holders.length; i++) {
			this.holders[i].style.width = '100%'; 
		}
		
		// delay required for IE to handle resize
		clearTimeout(this.resizeTimer);
		this.resizeTimer = setTimeout(this.bind(function(){
			// hide background holders
			for(var i = 0; i < this.holders.length; i++) {
				this.holders[i].style.display = 'none';
			}
			
			// calculate real page dimensions with hidden background blocks
			this.viewWidth = this[this.stretchByWindow ? 'getWindowWidth' : 'getPageWidth']();
			this.viewHeight = this[this.stretchByWindow ? 'getWindowHeight' : 'getPageHeight']();
			
			// show and resize all background holders
			for(i = 0; i < this.holders.length; i++) {
				this.holders[i].style.display = 'block';
				this.resizeHolder(this.holders[i]);
			}
			for(i = 0; i < this.images.length; i++) {
				this.resizeImage(this.images[i]);
			}
		}),10);
	},
	addHandlers: function() {
		if (window.addEventListener) window.addEventListener('resize', this.bind(this.resizeAll), false);
		else if (window.attachEvent) window.attachEvent('onresize', this.bind(this.resizeAll));
	},
	bind: function(fn, scope, args) {
		var newScope = scope || this;
		return function() {
			return fn.apply(newScope, args || arguments);
		}
	} 
}.init();
