//Init page scripts
jQuery(function(){
	initMainNavigation();
	initClear();
	initGallery();
	initSlideBox();
	initTabs();
jQuery('#email-story').attr('href',jQuery('li.forward_links a').attr('href'));
jQuery('#print-story').attr('href',jQuery('li.book_printer a').attr('href'));
jQuery('#bookmark-story').attr('href',jQuery('li.flag-bookmarks a').attr('href'));

});



//Init tabs
function initTabs(){
	jQuery('ul.tabset').each(function(){
		var _list = jQuery(this);
		var _links = _list.find('a.tab');

		_links.each(function() {
			var _link = jQuery(this);
			var _href = _link.attr('href');
			var _tab = jQuery(_href);

			if(_link.hasClass('active')) _tab.show();
			else _tab.hide();

			_link.click(function(){
				_links.filter('.active').each(function(){
					jQuery(jQuery(this).removeClass('active').attr('href')).hide();
				});
				_link.addClass('active');
				_tab.show();
				return false;
			});
		});
	});
}
//Init clear form elements
function initClear(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: true,
		addClassFocus: "focus",
		filterClass: "default"
	});
}
function clearFormFields(o)
{
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filterClass) o.filterClass = "default";
	if(o.clearInputs) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++ ) {
			if((inputs[i].type == "text") && inputs[i].className.indexOf(o.filterClass) == -1) {
				inputs[i].valueHtml = inputs[i].value;
				inputs[i].onfocus = function ()	{
					if(this.valueHtml == this.value) this.value = "";
					if(this.fake) {
						inputsSwap(this, this.previousSibling);
						this.previousSibling.focus();
					}
					if(o.addClassFocus && !this.fake) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				inputs[i].onblur = function () {
					if(this.value == "") {
						this.value = this.valueHtml;
						if(o.passwordFieldText && this.type == "password") inputsSwap(this, this.nextSibling);
					}
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
				if(o.passwordFieldText && inputs[i].type == "password") {
					var fakeInput = document.createElement("input");
					fakeInput.type = "text";
					fakeInput.value = inputs[i].value;
					fakeInput.className = inputs[i].className;
					fakeInput.fake = true;
					inputs[i].parentNode.insertBefore(fakeInput, inputs[i].nextSibling);
					inputsSwap(inputs[i], null);
				}
			}
		}
	}
	if(o.clearTextareas) {
		var textareas = document.getElementsByTagName("textarea");
		for(var i=0; i<textareas.length; i++) {
			if(textareas[i].className.indexOf(o.filterClass) == -1) {
				textareas[i].valueHtml = textareas[i].value;
				textareas[i].onfocus = function() {
					if(this.value == this.valueHtml) this.value = "";
					if(o.addClassFocus) {
						this.className += " " + o.addClassFocus;
						this.parentNode.className += " parent-" + o.addClassFocus;
					}
				}
				textareas[i].onblur = function() {
					if(this.value == "") this.value = this.valueHtml;
					if(o.addClassFocus) {
						this.className = this.className.replace(o.addClassFocus, "");
						this.parentNode.className = this.parentNode.className.replace("parent-"+o.addClassFocus, "");
					}
				}
			}
		}
	}
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}
// browser detect script
browserDetect = {
	matchGroups: [
		[
			{uaString:'win', className:'win'},
			{uaString:'mac', className:'mac'},
			{uaString:['linux','x11'], className:'linux'}
		],
		[
			{uaString:'msie', className:'trident'},
			{uaString:'applewebkit', className:'webkit'},
			{uaString:'gecko', className:'gecko'},
			{uaString:'opera', className:'presto'}
		],
		[
			{uaString:'msie 9.0', className:'ie9'},
			{uaString:'msie 8.0', className:'ie8'},
			{uaString:'msie 7.0', className:'ie7'},
			{uaString:'msie 6.0', className:'ie6'},
			{uaString:'firefox/2', className:'ff2'},
			{uaString:'firefox/3', className:'ff3'},
			{uaString:'firefox/4', className:'ff4'},
			{uaString:['opera','version/11'], className:'opera11'},
			{uaString:['opera','version/10'], className:'opera10'},
			{uaString:'opera/9', className:'opera9'},
			{uaString:['safari','version/3'], className:'safari3'},
			{uaString:['safari','version/4'], className:'safari4'},
			{uaString:['safari','version/5'], className:'safari5'},
			{uaString:'chrome', className:'chrome'},
			{uaString:'safari', className:'safari2'},
			{uaString:'unknown', className:'unknown'}
		]
	],
	init: function() {
		this.detect();
		return this;
	},
	addClass: function(className) {
		this.pageHolder = document.documentElement;
		document.documentElement.className += ' '+className;
	},
	detect: function() {
		for(var i = 0, curGroup; i < this.matchGroups.length; i++) {
			curGroup = this.matchGroups[i];
			for(var j = 0, curItem; j < curGroup.length; j++) {
				curItem = curGroup[j];
				if(typeof curItem.uaString === 'string') {
					if(this.uaMatch(curItem.uaString)) {
						this.addClass(curItem.className);
						break;
					}
				} else {
					for(var k = 0, allMatch = true; k < curItem.uaString.length; k++) {
						if(!this.uaMatch(curItem.uaString[k])) {
							allMatch = false;
							break;
						}
					}
					if(allMatch) {
						this.addClass(curItem.className);
						break;
					}
				}
			}
		}
	},
	uaMatch: function(s) {
		if(!this.ua) {
			this.ua = navigator.userAgent.toLowerCase();
		}
		return this.ua.indexOf(s) != -1;
	}
}.init();

//Init main navigation
function initMainNavigation(){
	var set =  jQuery('#nav');
	var setWidth = set.outerWidth(true);
	jQuery('> li', set).each(function(i){
		var item = jQuery(this);
		var itemWidth = item.outerWidth(true);
		var drop = jQuery('.drop', item);
		var dropWidth = drop.width();
		var dropFlexEl = jQuery('.holder > ul', drop);
		var nullPosition = item.position().left - set.position().left + dropWidth;
		if(nullPosition > setWidth){
			drop.css({ left: setWidth - nullPosition });
		}
		if(jQuery.browser.msie && jQuery.browser.version < 8){
			if(dropWidth < itemWidth){
				dropFlexEl.css({ width: itemWidth })
				drop.css({ width: itemWidth })
			};
		}
		else {
			if(dropWidth < itemWidth){
				dropFlexEl.css({ width: item.width() })
			}
		}
	
		item.bind('mouseenter', function(){
			drop.show();
		}).bind('mouseleave', function(){
			drop.hide();
		});
	});
}
function initSlideBox(){
	jQuery('div.gallery').each(function(){
		var set = jQuery(this);
		jQuery('.gallery-slider > li', set).each(function(){
			var slideItem = jQuery(this);
			var slideBox = jQuery('.text-holder', slideItem);
			var slideHeight = slideBox.outerHeight(true) - slideBox.find('.title').outerHeight(true) - 2;
			slideBox.css({ bottom: -slideHeight });
			slideItem.bind('mouseenter', function(){
				slideBox.animate({ bottom: 0 }, { queue: false, duration: 500 });
			}).bind('mouseleave', function(){
				slideBox.animate({ bottom: -slideHeight }, { queue: false, duration: 500 });
			});
		});
	});
}
//Init gallery
function initGallery(){
	jQuery('div.gallery').scrollGallery({
		sliderHolder: 'div.gallery-wrapper'
	});
}
jQuery.fn.scrollGallery = function(_options){
	var _options = jQuery.extend({
		sliderHolder: '>div',
		slider:'>ul',
		slides: '>li',
		pagerLinks:'div.pager a',
		btnPrev:'a.btn-prev',
		btnNext:'a.btn-next',
		activeClass:'active',
		disabledClass:'disabled',
		generatePagination:'div.pg-holder',
		curNum:'em.scur-num',
		allNum:'em.sall-num',
		circleSlide:true,
		pauseClass:'gallery-paused',
		pauseButton:'none',
		pauseOnHover:true,
		autoRotation:true,
		stopAfterClick:false,
		switchTime:5000,
		duration:650,
		easing:'swing',
		event:'click',
		afterInit:false,
		vertical:false,
		step:true,
		startElement : 0,
		autoHeight: false
	},_options);

	return this.each(function(){
		var _this = jQuery(this);
		var _sliderHolder = jQuery(_options.sliderHolder, _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 _disabledClass = _options.disabledClass;
		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 autoHeight = _options.autoHeight;
		var _afterInit = _options.afterInit;
		
		if(!_slides.length) return;
		var _currentStep = _options.startElement;
		var _sumWidth = 0;
		var _sumHeight = 0;
		var _hover = false;
		var _stepWidth;
		var _stepHeight;
		var _stepCount;
		var _offset;
		var _timer;

		_slides.each(function(){
			_sumWidth+=jQuery(this).outerWidth(true);
			_sumHeight+=jQuery(this).outerHeight(true);
		});
		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;
				}
			}
		}
		if(_btnPrev.length) {
			_btnPrev.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				prevSlide();
				return false;
			});
		}
		if(_btnNext.length) {
			_btnNext.bind(_controlEvent,function(){
				if(_stopAfterClick) stopAutoSlide();
				nextSlide();
				return false;
			});
		}
		if(_generatePagination.length) {
			_generatePagination.empty();
			recalcOffsets();
			var _list = jQuery('<ul />');
			for(var i=0; i<_stepCount; i++) jQuery('<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;
				});
			});
		}
		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(_disabledClass);
				_btnNext.removeClass(_disabledClass);
				if(_currentStep == 0) _btnPrev.addClass(_disabledClass);
				if(_currentStep == _stepCount-1) _btnNext.addClass(_disabledClass);
			}
			if(_curNum.length) _curNum.text(_currentStep+1);
			if(_allNum.length) _allNum.text(_stepCount);
			if(autoHeight) _slider.animate({ height: _slides.eq(_currentStep).outerHeight(true) }, { queue: false, duration: 250 });
		}
		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();
		}
		function stopAutoSlide() {
			if(_timer) clearTimeout(_timer);
			_autoRotation = false;
		}
		function autoSlide() {
			if(!_autoRotation || _hover) 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();
		if(_vertical){
			_slider.css({ marginTop:_offset });
		}
		else {
			_slider.css({ marginLeft:_offset });
		}
		
		if(_pauseButton.length) {
			_pauseButton.click(function(){
				if(_this.hasClass(_pauseClass)) {
					_this.removeClass(_pauseClass);
					_autoRotation = true;
					autoSlide();
				} else {
					_this.addClass(_pauseClass);
					stopAutoSlide();
				}
				return false;
			});
		}
		if(_afterInit && typeof _afterInit === 'function') _afterInit(_this, _slides);
	});
}

