$(function(){
	initCufon();
	hideFormText();
	initOffer(500);
	var gallery1 = $('.visual').gallery({
		duration: 600,
		listOfSlides: '.visual-list>li',
		effect: 'fade',
		autoRotation: 10000
	});
	$('.visual').mouseenter(function(){
		gallery1.stop();
	}).mouseleave(function(){
		gallery1.play();
	});
	initPopups();
	initPopupGallery();
})

function initCufon() {
	Cufon.replace('#nav a', { fontFamily: 'gotham-med', hover: true });
	//Cufon.replace('.offer-holder span.text', { fontFamily: 'gotham-book' });
	Cufon.replace('.offer-holder .button-offer', { fontFamily: 'gotham-med', hover: true });
	Cufon.replace('.visual-block h2', { fontFamily: 'gotham-book' });
	Cufon.replace('.box h3', { fontFamily: 'gotham-book' });
	Cufon.replace('#main h1', { fontFamily: 'gotham-book' });
	Cufon.replace('#content .heading-holder h2', { fontFamily: 'gotham-book' });
	Cufon.replace('#sidebar .box .heading', { fontFamily: 'gotham-book' });
	
	Cufon.replace('.some-link span', { fontFamily: 'gotham-book' });
	Cufon.replace('.some-link strong', { fontFamily: 'gotham-book' });
	Cufon.replace('.some-link .more', { fontFamily: 'gotham-med' });

	Cufon.replace('.example h3', { fontFamily: 'BirchStd'});
	Cufon.replace('.example p', { fontFamily: 'ComicSans', hover: true});

	Cufon.replace('.effects-test .shadow', { textShadow: '#555 1px 1px, #000 2px 2px', fontFamily: 'Frutiger' });
	Cufon.replace('.effects-test .gradient', { color: '-linear-gradient(#aaa, 0.45=#888, 0.45=#555, #000)', fontFamily: 'Frutiger' });

	// cufon with hover effects:
	Cufon.replace('.effects-test .gradient2',{color: '-linear-gradient(#f00, 0.45=#faa, 0.45=#f55, #000)', hover: {
		color: '-linear-gradient(#aaf, 0.45=#00f, 0.45=#55f, #000)',
		textShadow: '5px 5px #999'
	}, fontFamily: 'Frutiger', hoverables: {strong: true}});
}

function initOffer(_speed){
	var _animSpeed = (_speed ? _speed : 600);
	$('.offer-holder').each(function(){
		var _holder = $(this);
		var _slideEl = $('.slide .slide-holder', _holder);
		var _slide = $('.slide', _holder);
		var _btn = $('.button-offer', _holder);
		_slideEl.show();
		var _h = _slideEl.height() - 1;
		_slideEl.hide();
		var _t;
		var _top = parseInt(_holder.css('top'));
		var _topHidden = _top - _h + 17;

		_btn.mouseenter(function(){
			if (_t) clearTimeout(_t);
			if (_slideEl.is(':hidden')) {
				_slideEl.show();
				_holder.css('top', _topHidden).stop().animate({'top': _top});
				
			}
		}).mouseleave(function(){
			if (_t) clearTimeout(_t);
			_t = setTimeout(function(){
				_holder.stop().animate({
					'top':_topHidden
				}, _animSpeed, function(){
					_slideEl.hide()
					_holder.css('top', _top)
				});
				
			})
		})
		_slide.mouseenter(function(){
			if (_t) clearTimeout(_t);
			if (_slideEl.is(':hidden')) {
				_slideEl.show();
				_holder.css('top', _topHidden).stop().animate({'top': _top});
				
			}
		}).mouseleave(function(){
			if (_t) clearTimeout(_t);
			_t = setTimeout(function(){
				_holder.stop().animate({
					'top':_topHidden
				}, _animSpeed, function(){
					_slideEl.hide()
					_holder.css('top', _top)
				});
				
			})
		})
	})
}

function initPopupGallery(_time){
	var _fadeSpeed = 700;
	var _dur = (_time ? _time : 10000)
	$('.popup-gallery').each(function(){
		var _holder = $(this);
		var _links = $('.visual-list a.open-popup', _holder);
		var _popup = $(_links.eq(0).attr('href'));
		var _gallery = $('.gallery-list', _popup);
		var _slides = $('>li', _gallery);
		var _next = $('.arrow-next', _popup);
		var _prev = $('.arrow-prev', _popup);
		var _active = 0;
		var _int;
		
		_links.bind('click', function(){
			_active = _links.index($(this));
			_popup.trigger('galleryStart');
		})
		
		function nextSlide(){
			var _newActive = _active < _slides.length-1 ? _active + 1 : 0;
			_slides.eq(_active).fadeOut(_fadeSpeed);
			_slides.eq(_newActive).fadeIn(_fadeSpeed, function(){
				_slides.eq(_active).removeClass('active');
				_slides.eq(_newActive).addClass('active');
				_active = _newActive;
			})
		}
		function prevSlide(){
			var _newActive = _active > 0 ? _active - 1 : _slides.length-1;
			_slides.eq(_active).fadeOut(_fadeSpeed);
			_slides.eq(_newActive).fadeIn(_fadeSpeed, function(){
				_slides.eq(_active).removeClass('active');
				_slides.eq(_newActive).addClass('active');
				_active = _newActive;
			})
		}

		_next.click(function(){
			if (_int) clearInterval(_int);
			nextSlide();
			_int = setInterval(nextSlide, _dur);
			return false;
		})
		_prev.click(function(){
			if (_int) clearInterval(_int);
			prevSlide();
			_int = setInterval(prevSlide, _dur);
		})

		_popup.bind('galleryStart', function(){
			if (_int) clearInterval(_int);
			_slides.hide().removeClass('active');
			_slides.eq(_active).show().addClass('active');
			_int = setInterval(nextSlide, _dur);
		})
	})
}

function hideFormText() {
	var _inputs = document.getElementsByTagName('input');
	var _txt = document.getElementsByTagName('textarea');
	var _value = [];
	
	if (_inputs) {
		for(var i=0; i<_inputs.length; i++) {
			if (_inputs[i].type == 'text' || _inputs[i].type == 'password') {
				
				_inputs[i].index = i;
				_value[i] = _inputs[i].value;
				
				_inputs[i].onfocus = function(){
					if (this.value == _value[this.index])
						this.value = '';
				}
				_inputs[i].onblur = function(){
					if (this.value == '')
						this.value = _value[this.index];
				}
			}
		}
	}
	if (_txt) {
		for(var i=0; i<_txt.length; i++) {
			_txt[i].index = i;
			_value['txt'+i] = _txt[i].value;
			
			_txt[i].onfocus = function(){
				if (this.value == _value['txt'+this.index])
					this.value = '';
			}
			_txt[i].onblur = function(){
				if (this.value == '')
					this.value = _value['txt'+this.index];
			}
		}
	}
}

(function($) {
	/* Gallery */
	function Gallery(el, options) {
		this._hold = $(el);
		this.initOptions(options);
		this._timer = options.autoRotation;
		this._t;
		this.initialize();
	}
	
	$.fn.gallery = function(options) {
		return new Gallery(this.get(0), options);
	};
	
	Gallery.prototype = {
		initOptions: function(_obj){
			this.options = {
				randomSlide: false,
				changeHeight: false,
				duration: 700,
				slideElement: 1,
				event: 'click',
				autoRotation: false,
				effect: false,
				listOfSlides: 'ul > li',
				switcher: false,
				disableBtn: false,
				nextBtn: 'a.next-link, a.btn-next, a.next, a.link-next, a.arrow-next',
				prevBtn: 'a.prev-link, a.btn-prev, a.prev, a.link-prev, a.arrow-prev',
				circle: true,
				direction: false,
				IE: false,
				swicherBuilder: false,
				titleReplace: false
			};
			for(key in _obj) this.options[key] = _obj[key];
		},
		initialize: function(){
			var _this = this;
			var _hold = _this._hold;
			var _speed = _this.options.duration;
			var _timer = _this.options.autoRotation;
			var _el = _hold.find(_this.options.listOfSlides);
			if(_el.length){
				_el.css('display','block');
				if (_this.options.effect){
					_el.css('position','absolute');
					var _list = _el;
				}
				else var _list = _el.parent();
				var _switcher = _hold.find(_this.options.switcher);
				var _next = _hold.find(_this.options.nextBtn);
				var _prev = _hold.find(_this.options.prevBtn);
				var _count = _el.index(_el.filter(':last'));
				var _w = _el.outerWidth(true);
				var _h = _el.outerHeight(true);
				if (_this.options.switcher) var _active = _switcher.index(_switcher.filter('.active:eq(0)'));
				else var _active = _el.index(_el.filter('.active:eq(0)'));
				if (_active < 0) _active = 0;
				var _last = _active;
				if(_this.options.swicherBuilder){
					this._hold.append('<ul class="'+_this.options.swicherBuilder+'" />');
					var _newSwitcher = $('.' + _this.options.swicherBuilder, this._hold);
					
					for (var i = 0; i < _el.length; i++){
						_newSwitcher.append('<li><a href="#">'+ (i+1) +'</a></li>');
						if(i==_active){
							_newSwitcher.find('li').eq(_active).addClass('active');
						}
					};
					
					_switcher = _newSwitcher.find('li');
				}
				if(_this.options.titleReplace){
					var titleReplace = _hold.find(_this.options.titleReplace);
					if(titleReplace.length){
						_el.each(function(i){
							var this_el = $(this);
							var this_title = this_el.attr('title');
							if(this_title.length){
								_el.eq(i).data("title", this_title);
							}else{
								_el.eq(i).data("title", 'No title');
							}
							this_el.removeAttr('title');
						});
						titleReplace.html(_el.eq(_active).data("title"));
					}
				}
				
				// Installation directions
				if (!_this.options.direction) {
					var _wrapHolderW = Math.ceil(_list.parent().width() / _w);
					if (((_wrapHolderW - 1) * _w + _w / 2) > _list.parent().width()) _wrapHolderW--;
				}
				else{
					var _wrapHolderW = Math.ceil(_list.parent().height()/_h);
					if (((_wrapHolderW-1)*_h + _h/2) > _list.parent().height()) _wrapHolderW--;
				}
				
				// Setting "fade" or "slide" effect
				if (!_this.options.effect) var rew = _count - _wrapHolderW + 1;
				else var rew = _count;
				if (!_this.options.effect) {
					if (!_this.options.direction) _list.css({marginLeft: -(_w * _active)})
					else _list.css({marginTop: -(_h * _active)})
				}
				else {
					_list.css({
						opacity: 0
					}).removeClass('active').eq(_active).addClass('active').css({
						opacity: 1
					}).css('opacity', 'auto');
					_switcher.removeClass('active').eq(_active).addClass('active');
					if ($.browser.msie && _this.options.IE){
						_list.css({
							display: 'none'
						});
						_list.eq(_active).css({
							display: 'block'
						});
					}
				}
				
				// Disable or enable buttons "prev next"
				if (_this.options.disableBtn) {
					if (_count < _wrapHolderW) _next.addClass(_this.options.disableBtn);
					_prev.addClass(_this.options.disableBtn);
				}
				
				// Function to "fade"
				if(_this.options.changeHeight){
					if (_this.options.effect){
						_el.parent().css({height: _list.eq(_active).outerHeight(true), overflow: 'hidden'});
					}else{
						if(_this.options.slideElement>1){
							var active_H = _list.children().eq(_active).outerHeight(true);
							for (var i = 1; i < _this.options.slideElement; i++){
								if(active_H<_list.children().eq(_active+i).outerHeight(true)){
									active_H=_list.children().eq(_active+i).outerHeight(true)
								}
							};
							_el.parent().css({height: active_H, overflow: 'hidden'});
						}else _el.parent().css({height: _list.children().eq(_active).outerHeight(true), overflow: 'hidden'});
					}
				}
				function fadeElement(){
					if ($.browser.msie && _this.options.IE){
						_list.eq(_last).css({
							opacity:0,
							display: 'none'
						});
						_list.removeClass('active').eq(_active).addClass('active').css({
							opacity:'auto',
							display: 'block'
						});
					}
					else{
						_list.eq(_last).animate({opacity:0}, {queue:false, duration: _speed});
						_list.removeClass('active').eq(_active).addClass('active').animate({
							opacity:1
						}, {queue:false, duration: _speed, complete: function(){
							$(this).css('opacity','auto');
						}});
					}
					if(_this.options.changeHeight){
						_el.parent().animate({
							height: _list.eq(_active).outerHeight(true)
						}, {queue:false, duration:_speed});
					}
					if (_this.options.switcher) _switcher.removeClass('active').eq(_active).addClass('active');
					_last = _active;
					if(titleReplace){
						titleReplace.html(_el.eq(_active).data("title"));
					}
				}
				// Function for "slide"
				function scrollEl(){
					if (!_this.options.direction) _list.animate({marginLeft: -(_w * _active)}, {queue:false, duration: _speed})
					else _list.animate({marginTop: -(_h * _active)}, {queue:false, duration: _speed})
					if (_this.options.switcher && _this.options.slideElement) _switcher.removeClass('active').eq(_active/_this.options.slideElement).addClass('active');
					else{
						if (_this.options.switcher) _switcher.removeClass('active').eq(_active).addClass('active');
					}
					if(_this.options.changeHeight){
						if(_this.options.slideElement>1){
							var active_H = _list.children().eq(_active).outerHeight(true);
							for (var i = 1; i < _this.options.slideElement; i++){
								if(active_H<_list.children().eq(_active+i).outerHeight(true)){
									active_H=_list.children().eq(_active+i).outerHeight(true)
								}
							};
							_el.parent().animate({
								height: active_H
							}, {queue:false, duration:_speed});
						}else{
							_el.parent().animate({
								height: _list.children().eq(_active).outerHeight(true)
							}, {queue:false, duration:_speed});
						}
					}
					if(titleReplace){
						titleReplace.html(_el.eq(_active).data("title"));
					}
				}
				function toPrepare(){
					if ((_active == rew) && _this.options.circle) _active = -_this.options.slideElement;
					for (var i = 0; i < _this.options.slideElement; i++){
						if(_this.options.randomSlide){
							var pre_active = _active;
							if(_this.options.listOfSlides.length){
								while(pre_active == _active){
									_active = parseInt(Math.random()*(_count+1));
								}
							}
						}else{
							_active++;
						}
						if (_active > rew) {
							_active--;
							if (_this.options.disableBtn &&(_count > _wrapHolderW)) _next.addClass(_this.options.disableBtn);
						}
					}
					if (_active == rew) if (_this.options.disableBtn &&(_count > _wrapHolderW)) _next.addClass(_this.options.disableBtn);
					if (!_this.options.effect) scrollEl();
					else fadeElement();
				}
				if(_this._timer){
					_this._hold.bind('runTimer', function(){
						if(_this._t) clearTimeout(_this._t);
						_this._t = setInterval(function(){
							toPrepare();
						}, _this._timer);
					});
				}
				_next.click(function(){
					if(_this._t) clearTimeout(_this._t);
					if (_this.options.disableBtn &&(_count > _wrapHolderW)) _prev.removeClass(_this.options.disableBtn);
					toPrepare();
					if (_this._timer) _this._hold.trigger('runTimer');
					return false;
				});
				_prev.click(function(){
					if(_this._t) clearTimeout(_this._t);
					if (_this.options.disableBtn &&(_count > _wrapHolderW)) _next.removeClass(_this.options.disableBtn);
					if ((_active == 0) && _this.options.circle) _active = rew + _this.options.slideElement;
					for (var i = 0; i < _this.options.slideElement; i++){
						_active--;
						if (_active < 0) {
							_active++;
							if (_this.options.disableBtn &&(_count > _wrapHolderW)) _prev.addClass(_this.options.disableBtn);
						}
					};
					if (_active == 0) if (_this.options.disableBtn &&(_count > _wrapHolderW)) _prev.addClass(_this.options.disableBtn);
					if (!_this.options.effect) scrollEl();
					else fadeElement();
					if (_this._timer) _this._hold.trigger('runTimer');
					return false;
				});
				if (_this.options.switcher) _switcher.click(function(){
					if (_this.options.event=='click'){
						if (_this.options.slideElement){
							_active = _switcher.index($(this))*_this.options.slideElement;
						}else{
							_active = _switcher.index($(this));
						}
						if(_this._t) clearTimeout(_this._t);
						if (!_this.options.effect) scrollEl();
						else fadeElement();
						if (_this._timer) _this._hold.trigger('runTimer');
					}
					return false;
				}).mouseenter(function(){
					if (_this.options.event=='hover'){
						if (_this.options.slideElement){
							_active = _switcher.index($(this))*_this.options.slideElement;
						}else{
							_active = _switcher.index($(this));
						}
						if(_this._t) clearTimeout(_this._t);
						if (!_this.options.effect) scrollEl();
						else fadeElement();
						if (_this._timer) _this._hold.trigger('runTimer');
					}
				});
				if (_this._timer) _this._hold.trigger('runTimer');
			}
		},
		stop: function(){
			var _this = this;
			if (_this._t) clearTimeout(_this._t);
		},
		play: function(){
			var _this = this;
			if (_this._t) clearTimeout(_this._t);
			if (_this._timer) _this._hold.trigger('runTimer');
		}
	}
}(jQuery));

// popups function
function initPopups() {
	var _zIndex = 1000;
	var _fadeSpeed = 350;
	var _faderOpacity = 0.65;
	var _faderBackground = '#000';
	var _faderId = 'lightbox-overlay';
	var _closeLink = 'a.btn-close, a.close, a.cancel';
	var _fader;
	var _lightbox = null;
	var _openers = jQuery('a.open-popup');
	var _page = jQuery(document);
	var _minWidth = jQuery('body > div:eq(0)').outerWidth();
	var _scroll = false;

	// init popup fader
	_fader = jQuery('#'+_faderId);
	if(!_fader.length) {
		_fader = jQuery('<div />');
		_fader.attr('id',_faderId);
		jQuery('body').append(_fader);
	}
	_fader.css({
		opacity:_faderOpacity,
		backgroundColor:_faderBackground,
		position:'absolute',
		overflow:'hidden',
		display:'none',
		top:0,
		left:0,
		zIndex:_zIndex
	});

	// IE6 iframe fix
	if(jQuery.browser.msie && jQuery.browser.version < 7) {
		if(!_fader.children().length) {
			var _frame = jQuery('<iframe src="javascript:false" frameborder="0" scrolling="no" />');
			_frame.css({
				opacity:0,
				width:'100%',
				height:'100%'
			});
			var _frameOverlay = jQuery('<div>');
			_frameOverlay.css({
				top:0,
				left:0,
				zIndex:1,
				opacity:0,
				background:'#000',
				position:'absolute',
				width:'100%',
				height:'100%'
			});
			_fader.empty().append(_frame).append(_frameOverlay);
		}
	}

	// lightbox positioning function
	function positionLightbox() {
		if(_lightbox) {
			var _windowHeight = jQuery(window).height();
			var _windowWidth = jQuery(window).width();
			var _lightboxWidth = _lightbox.outerWidth();
			var _lightboxHeight = _lightbox.outerHeight();
			var _pageHeight = _page.height();

			if (_windowWidth < _minWidth) _fader.css('width',_minWidth);
				else _fader.css('width','100%');
			if (_windowHeight < _pageHeight) _fader.css('height',_pageHeight);
				else _fader.css('height',_windowHeight);

			_lightbox.css({
				position:'absolute',
				zIndex:(_zIndex+1)
			});

			// vertical position
			if (_windowHeight > _lightboxHeight) {
				if (jQuery.browser.msie && jQuery.browser.version < 7) {
					_lightbox.css({
						position:'absolute',
						top: parseInt(jQuery(window).scrollTop()) + (_windowHeight - _lightboxHeight) / 2
					});
				} else {
					_lightbox.css({
						position:'fixed',
						top: (_windowHeight - _lightboxHeight) / 2
					});
				}
			} else {
				var _faderHeight = _fader.height();
				if(_faderHeight < _lightboxHeight) _fader.css('height',_lightboxHeight);
				if (!_scroll) {
					if (_faderHeight - _lightboxHeight > parseInt(jQuery(window).scrollTop())) {
						_faderHeight = parseInt(jQuery(window).scrollTop())
						_scroll = _faderHeight;
					} else {
						_scroll = _faderHeight - _lightboxHeight;
					}
				}
				_lightbox.css({
					position:'absolute',
					top: _scroll
				});
			}

			// horizontal position
			if (_fader.width() > _lightbox.outerWidth()) _lightbox.css({left:(_fader.width() - _lightbox.outerWidth()) / 2});
			else _lightbox.css({left: 0});
		}
	}

	// show/hide lightbox
	function toggleState(_state) {
		if(!_lightbox) return;
		if(_state) {
			_fader.fadeIn(_fadeSpeed,function(){
				_lightbox.fadeIn(_fadeSpeed);
			});
			_scroll = false;
			positionLightbox();
		} else {
			_lightbox.fadeOut(_fadeSpeed,function(){
				_fader.fadeOut(_fadeSpeed);
				_scroll = false;
			});
		}
	}

	// popup actions
	function initPopupActions(_obj) {
		if(!_obj.get(0).jsInit) {
			_obj.get(0).jsInit = true;
			// close link
			_obj.find(_closeLink).click(function(){
				_lightbox = _obj;
				toggleState(false);
				return false;
			});
		}
	}

	// lightbox openers
	_openers.each(function(){
		var _opener = jQuery(this);
		var _target = _opener.attr('href');
		var _reg = new RegExp(/\#[^\s]+/gi);

		// popup load type - ajax or static
		if(!_reg.test(_target)) {
			_opener.click(function(){
				// ajax load
				if(jQuery('div[rel*="'+_target+'"]').length == 0) {
					jQuery.ajax({
						url: _target,
						type: "POST",
						dataType: "html",
						success: function(msg){
							// append loaded popup
							_lightbox = jQuery(msg);
							_lightbox.find('img').load(positionLightbox)
							_lightbox.attr('rel',_target).hide().css({
								position:'absolute',
								zIndex:(_zIndex+1),
								top: -9999,
								left: -9999
							});
							jQuery('body').append(_lightbox);

							// init js for lightbox
							initPopupActions(_lightbox);

							// show lightbox
							toggleState(true);
						},
						error: function(msg){
							alert('AJAX error!');
							return false;
						}
					});
				} else {
					_lightbox = jQuery('div[rel*="'+_target+'"]');
					toggleState(true);
				}
				return false;
			});
		} else {
			if(jQuery(_target).length) {
				// init actions for popup
				var _popup = jQuery(_target).hide();
				initPopupActions(_popup);
					// open popup
					_opener.click(function(){
					if(_lightbox) {
						_lightbox.fadeOut(_fadeSpeed,function(){
							_lightbox = _popup.hide();
							toggleState(true);
						})
					} else {
						_lightbox = _popup.hide();
						toggleState(true);
					}
					return false;
				});
			}
		}
	});

	// event handlers
	jQuery(window).resize(positionLightbox);
	jQuery(window).scroll(positionLightbox);
	jQuery(document).keydown(function (e) {
		if (!e) evt = window.event;
		if (e.keyCode == 27) {
			toggleState(false);
		}
	})
	_fader.click(function(){
		if(!_fader.is(':animated')) toggleState(false);
		return false;
	})
}
