(function($){
	$.fn.slider = function(options){
		var defaults = {
			
			},
			self = $( this ).css('padding-left','0px'),
			ulwidth = 694,
			liwidth = 347,
			lilength = self.find('li').length,
			selectedLi = self.find("li.slider_selected");

		self.parent().css({ width: ulwidth, overflow:'hidden' });
		
		if(lilength % 2 === 1){
			lilength++;
			self.append( $('<li>').html('&nbsp;') );
		}
		

		self.css({ 'width':lilength * liwidth, 'overflow':'hidden'});
		self.find('li').each(function( i, elem ){
			$( elem ).css({ 'list-style-type': 'none', 'float':'left', 'width': liwidth});
		});
		
		$('.slide_left').bind('click',function(){
			if( $(this).parent('li').prev('li').length === 0){
				return false;
			}

			self.animate({ 'margin-left': '+='+ ulwidth},{ easing: "easeOutBack", duration: 600});
			return false;
		});
		
		$('.slide_right').bind('click',function(){
			
			if( $(this).parent('li').next().length === 0){
				return false;
			}
			
			self.animate({ 'margin-left': '-='+ ulwidth},{ easing: "easeOutBack", duration: 600});
			return false;
		});
		
		if( selectedLi.length === 1 ){
			var index = selectedLi.index()+1,
				isOdd = index%2 === 0 ? false : true;
			
			self.css("margin-left", - ( parseInt( ( isOdd ? index : (index-1) ) / 2)* ulwidth ) );
		
		}
		
		return this;
	
	}


})(jQuery);

(function($){
	$.fn.blogmenu = function(options){
		var self = $(this),
			parent = self.parent(),
			defaults = {
				elemWidth: self.first().width(),
				width: parent.width(),
				liMargin: 1
			},
			o = $.extend({},defaults,options),
			outerParent = parent.parent();
			self.parent().css('width', self.length * (o.elemWidth+ o.liMargin));
			
			self.css('margin-left',o.liMargin)
			
			if(self.filter('.leftMenuItem_sel').length === 1){
				if( parent.width() - (self.filter('.leftMenuItem_sel').index()*(o.elemWidth+o.liMargin)) < outerParent.width() ){
					parent.css('left', -(parent.width() - outerParent.width()) );
				}
				else{
					parent.css('left',-(self.filter('.leftMenuItem_sel').index()*(o.elemWidth+o.liMargin)));
				}
			}
			
			
			if( outerParent.width() > parent.width() ){
				$('.leftMenuRightButton, .leftMenuLeftButton').hide();
			}
		
		
			$('.leftMenuLeftButton').bind('click',function(){
				
				if( parseInt( parent.css('left') ) === 0 ){
					return false;
				}
				parent.animate({'left': '+='+ (o.elemWidth+o.liMargin)},function(){
					if( parseInt( parent.css('left') ) === 0 ){
						parent.stop();
						parent.clearQueue();
					}
				});
			});
			
			$('.leftMenuRightButton').bind('click',function(){
				if( parent.width() + parseInt( parent.css('left') ) === outerParent.width() ){
					return false;
				}
				parent.animate({'left': '-='+ (o.elemWidth+o.liMargin)},function(){
					if( parent.width() + parseInt( parent.css('left') ) === outerParent.width() ){
						parent.stop();
						parent.clearQueue();
					}
				});
			});
		
		return this;
	};

})(jQuery);

(function($){
	$.fn.bigwidget = function(options){
		var self = this,
			defaults = {
			
			},
			o = $.extend({}, defaults, options),
			list = self.find('ul'),
			point = self.find('.bigwidget_control_point'),
			arrow = self.find('.bigwidget_controls_arrow'),
			cpWidth = point.first().height() + parseInt( point.first().css('margin-bottom') ),
			liHeight = list.find('li:first').height(),
			imageHolder = self.find('.bigwidget_bigimage'),
			isMouseOut = true,
			autoSlidingInterval = null;

		//set active first elem
		list.find('li:first').addClass('bigwidget_control_listelem_active');
		point.first().addClass('bigwidget_control_point_active');
		imageHolder.css('background-image', 'url("'+ list.first().find('a.bigwidget_right_data').data('image') +'")');

		
		
		self.bind('mouseenter mouseleave', function(e){
			switch (e.type){
				case 'mouseenter':
					e.preventDefault();
					clearInterval( autoSlidingInterval );
					break;
				case 'mouseleave':
					autoSlidingInterval = setInterval( loadNext, 7000 );
					break;
				default:
					break;
			
			}
		});
		
		point.bind('click',function(){
			var self = $(this),
				targetLi = list.find('li:eq('+self.index()+')');
			
			if(targetLi.hasClass('bigwidget_control_listelem_active')){
				return false;
			}
			
			
			$('.bigwidget_control_point_active').removeClass('bigwidget_control_point_active');
			
			self.addClass('bigwidget_control_point_active');
			
			list.animate({ top: '-'+targetLi.position().top },function(){
				$('.bigwidget_control_listelem_active').removeClass('bigwidget_control_listelem_active');
				targetLi.addClass('bigwidget_control_listelem_active')
			});
			//move the arrow: .bigwidget_controls_arrow
			//change the bgimage: .bigwidget_bigimage
			//change the ribbon text: .bigwidget_bigimage_ribbon
			arrow.animate({ 'top': cpWidth * self.index() });
			
			var targetA = targetLi.find('a.bigwidget_right_data');
			
			imageHolder.fadeOut('slow',function(){
				$( this ).css('opacity',1); //forcing opacity:1
				$(this).clearQueue();
				$(this).css('background-image', 'url("'+targetA.data('image')+'")').fadeIn(function(){
					$( this ).css('opacity',1);//forcing opacity:1
					$( this ).clearQueue();
				});
			})
			
			$('div.bigwidget_bigimage_ribbon > a').fadeOut(function(){
				$(this).replaceWith( targetA.clone().removeAttr('data-image') );
			});
			
			
		});
	
		function loadNext(){
			var next =  $('.bigwidget_control_point_active').next('.bigwidget_control_point');
			if( next.length === 0){
				point.first().click();
			}
			else{
				next.first().click();
			}
		}
		
		//start auto sliding interval
		$(document).ready(function(){
			self.trigger('mouseleave');
		});
		return this;
	};
})(jQuery);


(function($){
	$.fn.tmons = function(options){
		var self = $(this).disableSelection(),
			btnUp = self.find('.tmonsButtonUp'),
			btnDown = self.find('.tmonsButtonDown'),
			content = self.find('.tmonsContent'),
			list = content.find('ul').css('top',0),
			liHeight = list.find('li:first').height(),
			autoSlidingInterval = null;
		
		list.css('height', liHeight* list.find('li').length );
		
		self.bind('mouseenter mouseleave', function(e){
			switch (e.type){
				case 'mouseenter':
					clearInterval( autoSlidingInterval );
					break;
				case 'mouseleave':
					autoSlidingInterval = setInterval( loadNext, 7000 );
					break;
				default:
					break;
			
			}
		});
		
		btnDown.bind('click',function(){
			if( Math.abs( parseInt( list.css('top') ) ) + content.height() >=  list.height() ){
			
				return false;
			}
			list.animate({ top: '-='+liHeight},function(){
				if( Math.abs( parseInt( list.css('top') ) ) + content.height() >=  list.height() ){
					list.stop();
					list.clearQueue();
				}
			});
			return false;
		
		});
		
		btnUp.bind('click',function(){
			if( parseInt( list.css('top') ) === 0){
				return false;
			}
			
			list.animate({ top: '+='+liHeight},function(){
				if( parseInt( list.css('top') ) === 0){
					
					list.stop();
					list.clearQueue();
				}	
			});	
		
			return false;
		});
		
		function loadNext(){
			if( Math.abs( parseInt( list.css('top') ) ) + content.height() >=  list.height() ){
				list.animate({ top: 0});
			}
			else{
				btnDown.trigger('click');
			}
			
		}
		
		//start auto sliding interval
		$(document).ready(function(){
			self.trigger('mouseleave');
		});
		
		return this;
	}	

})(jQuery);

(function($){

	$.fn.pressSlider = function(){ 
		var callbackCount = 0;
		var self = $( this ).disableSelection(),
			left = self.find('.press-slider-left-button'),
			right = self.find('.press-slider-right-button'),
			content = self.find('.press-slider-content-holder'),
			contentWidth = content.width(),
			list = content.find('ul'),
			liWidth = list.find('li:first').width(),
			selectedImage = list.find("a.selected_image");

		
		
		list.css('width', list.find('li').length * liWidth );
		list.css('margin-left',0);
		left.bind('click',function(){
			if( list.is(':animated')  || parseInt( list.css('margin-left') ) === 0 ){
				return false;
			}
			list.animate({ 'margin-left': '+='+liWidth },function(){
				if( parseInt( list.css('margin-left') ) === 0){ //because of some strange behaviour, TODO remove after testing
					list.stop();
					list.clearQueue();
				}
			});
		});
		
		right.bind('click',function( e ){

			if(  list.is(':animated')  || list.width() + parseInt( list.css('margin-left') ) <= contentWidth ){
					return false;
			}
		
			list.animate({ 'margin-left': '-='+liWidth});/*,function(){
				if( list.width() + parseInt( list.css('margin-left') ) === contentWidth ){
					list.stop();
					list.clearQueue();
				}
			});*/
			return false;
		});
		
		if( selectedImage.length === 1 ){
			var maxShownElems = parseInt (contentWidth / liWidth ),
				index = selectedImage.parents("li").index();
			console&&console.log( "index: "+ index );
			console&&console.log( "maxShowElems: "+maxShownElems );
			console&&console.log( "margin left: " + ( - ( (index ) * liWidth ) ) );
			list.css("margin-left", - ( (index ) * liWidth ) );
			selectedImage.click();
		
		}
	
		return this;
	}

})(jQuery);

(function($){
	$.fn.videoSlider = function(options){
		var self = this,
			videoObject = self.find('.widget_videoHolder'),
			list = self.find('ul.media-container');
			listElems = list.find('li'),
			btnNext = self.find('.next-video-button'),
			btnPrev = self.find('.prev-video-button'),
			overlayBox = self.find('.video-overlay-box'),
			liWidth = 400,
			posterHolder = listElems.find('.posterHolder');
		list.css({'width': listElems.length * liWidth, 'margin-left': 0});
	
		btnNext.bind('click',function(){
			if( list.width() + parseInt( list.css('margin-left') ) <= liWidth ){
				return false;
			}
		
			stopIfPlaying();
		
			list.animate({ 'margin-left': '-='+liWidth }, function(){
				if( list.width() + parseInt( list.css('margin-left') ) <= liWidth ){
					list.stop();
					list.clearQueue();
				}	
			});
		});
	
		btnPrev.bind('click',function(){
			if( parseInt( list.css('margin-left') ) === 0 ){
				return false;
			}
		
			stopIfPlaying();
		
			list.animate({ 'margin-left': '+='+liWidth }, function(){
				if( parseInt( list.css('margin-left') ) === 0 ){
					list.stop();
					list.clearQueue();
				}
			});
		});
	
		posterHolder.bind('click',function(){
			$( this ).siblings('.videoHolder').jwPlayer({
						swf:'_mmentor2_scripts/player.swf',
						id: 'jwPlayer',
						width:400,
						height:250,
						file:$( this ).parents('li').data('file'),
						"controlbar":"bottom",
						autostart:true
					});
		});
	
		function stopIfPlaying(){
			listElems.each(function(i,elem){
				if( $( elem ).find('.videoHolder').data('jwPlayer') ){
					$( elem ).find('.videoHolder').jwPlayer('destroy');
				}
			});
		}
	
		/*$(document).ready(function(){
			setTimeout(function(){
				listElems.each(function(i,elem){
					$( elem ).find('.videoHolder').jwPlayer({
						swf:'_mmentor2_scripts/player.swf',
						id: 'jwPlayer'+i,
						width:400,
						height:250,
						flashvars:{
							image:$( elem ).data('image'),
							file:$( elem ).data('file'),
							id: 'jwPlayer'+i,
							"controlbar":"bottom"
						}
					});
				});
			}, 2000);
		});*/

		return this;
	};

})(jQuery);

$(document).ready(function(){
	$('a.img-link').each(function( i , elem ){
		
		$( document.body ).append( $('<img>').css('display','none').attr( { width: 0, height: 0, src: $( elem ).attr('href') }) );
	});

			if ($('#gallery-big-image').length!=0) {
					$('a.img-link').click(function(e){
								var self = $( this );
								$('#gallery-big-image img').fadeOut(function(){ $( this ).removeAttr('height').css('margin-top', '').attr( { 'src': self.attr('href')  } ) });	
					return false;
					}); 
			} else {	 $('a.img-link').lightBox();	}
	
	$('ul.prevnext_slider').slider();

	$('.leftMenuItem, .leftMenuItem_sel').blogmenu();
	
	$('#bigwidget').bigwidget();
	
	$('.tmonsHolder').tmons();
	
	$('.press-slider').pressSlider();
	
	$('.widget_video').videoSlider();

	
	$('#gallery-big-image img').bind('load', function(e){
		
		var parentHeight = $( '#gallery-hold' ).height(),
			thisHeight = e.target.height;
		//$( this ).css('margin-top', 0 );
		if ( parentHeight < thisHeight ){
		
			$( this ).attr('height', parentHeight );
		
		}
		else{
			$( this ).css('margin-top', ( parentHeight - thisHeight  )/ 2 );
		}
		
		$( this ).fadeIn();
	
	});
	
	$(window).bind('scroll', function(){
		if($(this).scrollTop() !== 0){
			$('#scrollTop').fadeIn();
		}
		else{
			$('#scrollTop:visible').fadeOut();
		}
		
	})
		
	$('#scrollTop').bind('click',function(){
		var target;
		if( $.browser.opera){
			target = $('html');
		}else{
			target = $('html, body');
		}
		target.animate({ scrollTop: 0 },'slow');
		return false;
	});
	
	$('.docs-link').click(function(){
		var self = $( this ),
			target = $('#muvi'),
			embeddingInput = $('#embedlink');

		if( !!target.data( 'jwPlayer' ) ){
			target.jwPlayer( 'destroy' );
		}
		
		target.jwPlayer({
			swf: $('<a>').attr('href','/_mmentor2_scripts/player.swf')[0].href,
			id: 'jwPlayer_mtv',
			file: self[0].href,
			"controlbar":"bottom",
			autostart:true,
			image: $('<a>').attr('href',self.data( 'image' ))[0].href,
			width:560,
			height:324
		});
		
		embeddingInput.val( target.html().replace(/&(amp;)?autostart=true/,'') ).bind('focus click', function(e){ 
			this.focus();
			this.select(); 
		});
		return false;
	});
	
});


(function($) {
    $.fn.tipsy = function(options) {

        options = $.extend({}, $.fn.tipsy.defaults, options);
        
        return this.each(function() {
            
            var opts = $.fn.tipsy.elementOptions(this, options);
            
            $(this).hover(function() {

                $.data(this, 'cancel.tipsy', true);

                var tip = $.data(this, 'active.tipsy');
                if (!tip) {
                    tip = $('<div class="tipsy"><div class="tipsy-inner"/></div>');
                    tip.css({position: 'absolute', zIndex: 100000});
                    $.data(this, 'active.tipsy', tip);
                }

                if ($(this).attr('title') || typeof($(this).attr('original-title')) != 'string') {
                    $(this).attr('original-title', $(this).attr('title') || '').removeAttr('title');
                }

                var title;
                if (typeof opts.title == 'string') {
                    title = $(this).attr(opts.title == 'title' ? 'original-title' : opts.title);
                } else if (typeof opts.title == 'function') {
                    title = opts.title.call(this);
                }

                tip.find('.tipsy-inner')[opts.html ? 'html' : 'text'](title || opts.fallback);

                var pos = $.extend({}, $(this).offset(), {width: this.offsetWidth, height: this.offsetHeight});
                tip.get(0).className = 'tipsy'; // reset classname in case of dynamic gravity
                tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
                var actualWidth = tip[0].offsetWidth, actualHeight = tip[0].offsetHeight;
                var gravity = (typeof opts.gravity == 'function') ? opts.gravity.call(this) : opts.gravity;

                switch (gravity.charAt(0)) {
                    case 'n':
                        tip.css({top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('tipsy-north');
                        break;
                    case 's':
                        tip.css({top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2}).addClass('tipsy-south');
                        break;
                    case 'e':
                        tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth}).addClass('tipsy-east');
                        break;
                    case 'w':
                        tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}).addClass('tipsy-west');
                        break;
                }

                if (opts.fade) {
                    tip.css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: 0.8});
                } else {
                    tip.css({visibility: 'visible'});
                }

            }, function() {
                $.data(this, 'cancel.tipsy', false);
                var self = this;
                setTimeout(function() {
                    if ($.data(this, 'cancel.tipsy')) return;
                    var tip = $.data(self, 'active.tipsy');
                    if (opts.fade) {
                        tip.stop().fadeOut(function() { $(this).remove(); });
                    } else {
                        tip.remove();
                    }
                }, 100);

            });
            
        });
        
    };
    
    // Overwrite this method to provide options on a per-element basis.
    // For example, you could store the gravity in a 'tipsy-gravity' attribute:
    // return $.extend({}, options, {gravity: $(ele).attr('tipsy-gravity') || 'n' });
    // (remember - do not modify 'options' in place!)
    $.fn.tipsy.elementOptions = function(ele, options) {
        return $.metadata ? $.extend({}, options, $(ele).metadata()) : options;
    };
    
    $.fn.tipsy.defaults = {
        fade: false,
        fallback: '',
        gravity: 'n',
        html: false,
        title: 'title'
    };
    
    $.fn.tipsy.autoNS = function() {
        return $(this).offset().top > ($(document).scrollTop() + $(window).height() / 2) ? 's' : 'n';
    };
    
    $.fn.tipsy.autoWE = function() {
        return $(this).offset().left > ($(document).scrollLeft() + $(window).width() / 2) ? 'e' : 'w';
    };
    
})(jQuery);

