(function($, undefined) {
	
	var $d = $(document),
		now = (new Date()).getTime(),
		log = window.console ? window.console.log : function( msg ){ window[now].push(msg); };
	
	
	$.fn.init_plugins = function(){
		return this.each(function() {
			$(this).find('.g-js').each(function(){
				var options = this.onmouseup instanceof Function ? this.onmouseup() : {};
				this.onmouseup = null;
				this.removeAttribute('onmouseup');
				try { $(this).removeClass('g-js')[ this.getAttribute('rel') ](options); } catch (e) {}
			});
		});
	};
	
	$.fn.check = function( options ) {
		
		var cssClass = {
			"check" : 'b-check',
			"check__ckecked" : 'b-check__checked',
			"link__active" : 'm-link_active'
		};
		
		var options = $.extend({label: null}, options);
		
		return this.each(function(){
			
			var $this = $(this);
				
			if(options.label){
				$(options.label).bind('click.'+now, function( e ) { 
					$this.toggleClass( cssClass["check__ckecked"] ); 
					$(this).toggleClass( cssClass["link__active"] );
					return false; 
				});
			} 
			
			$this.bind('click', function(e) { 
				$this.toggleClass( cssClass["check__ckecked"] );
				return false;
			});	
			
		});
		
	};
	
	$.fn.menu = function( options ) {
		
		var cssClass = {
			"menu" : 'b-menu',
			"menu__country" : 'b-menu__country',
			"menu__icon" : 'b-menu__icon',
			"menu__link" : 'b-menu__link',
			"menu__link_active" : 'm-menu__link_active',
			"menu__item" : 'b-menu__item',
			"menu__item_active" : 'm-menu__item_active',
			"menu__arrow" : 'b-menu__arrow',
			"check" : 'b-check',
			"check__checked" : 'b-check__checked'
		};
		
		return this.each(function(){
			var rChecked = [];
			$(this).bind('click', function ( e ) {
				var $target = $(e.target),
					$menu,
					isMenuLink = $target.is("."+cssClass["menu__link"]),
					isCheck = $target.is("."+cssClass["check"]),
					isLastLevel = false
				;
				
				if( !isCheck ) {
					if ( !isMenuLink ) {
						$target = $target.closest("."+cssClass["menu__link"]);
						isMenuLink = true;
					}
					$menu = $target.next('.'+cssClass["menu"]);
					isLastLevel = $menu.length == 0;
				}
				
				if( isMenuLink && !isLastLevel ) {
					$target.toggleClass(cssClass["menu__link_active"]).closest('.'+cssClass["menu__item"]).toggleClass(cssClass["menu__item_active"]);
				} else if ( (isMenuLink && isLastLevel) || isCheck ) {
					var $check = isCheck ? $target : $target.closest('.'+cssClass["menu__item"]).find("."+cssClass["check"]),
						$link = isMenuLink ? $target : $target.closest('.'+cssClass["menu__item"]).find("."+cssClass["menu__link"]);
						
					if ( !($check.length && $link.length) ) { return false; }
					
					$link.toggleClass(cssClass["menu__link_active"]).closest('.'+cssClass["menu__item"]).toggleClass(cssClass["menu__item_active"]);
					$check.toggleClass(cssClass["check__checked"]);
					
					var value = decodeURIComponent( $check.attr("id").replace("check__",'') ), index;
					
					if ( isCheck ) {
						
						if( $check.hasClass(cssClass["check__checked"]) ) {
							rChecked[rChecked.length] = value;
						} else {
							for ( var i = rChecked.length; i--; ) {
								if ( rChecked[i] === value ) {
									rChecked.splice(i, 1);
									break;
								}
							}
						}
						
						if( rChecked.length ) {
							ScriptDoLoad('getdata.php?sec=100003&subsec=DisplayBetableEvents&league_ids[]='+rChecked.join('&league_ids[]='),'content');
						}
						
					} else if ( isMenuLink ) {
						for( var i = rChecked.length; i--; ) {
							$( document.getElementById('check__' + encodeURIComponent( rChecked[i] ) ) )
								.removeClass(cssClass["check__checked"])
								.closest('.'+cssClass["menu__item"])
								.find(cssClass["menu__link_active"])
								.removeClass(cssClass["menu__link_active"])
								.end()
								.removeClass(cssClass["menu__item_active"])
							;
						}
						rChecked.length = 0;
						rChecked[ 0 ] = value;
						ScriptDoLoad('getdata.php?sec=100003&subsec=DisplayBetableEvents&league_ids[]='+value,'content');
					}
					
				}
				
				$target = $menu = null;
				return !isCheck && !isMenuLink;
				
			});
		});
	};

	$.fn.toggler = function( options ) {
		var options = $.extend({
			event: 'click',
			target: '#div'
		}, options);
		return this.each(function(){
			
			var $toggler = $(this),
				$target = $(options.target);
			
			$toggler.bind(options.event, function(e) {
				
				var action = $toggler.val() == "" ? 'addClass' : 'removeClass';
				$target[action]('g-hidden');
				
			});
			
		});
	};
	
	$.fn.banners = function(options){
		
		var Banners = function( id, options ){
			this.id = id;
			this.options = options;
			this.$wrapper = $( document.getElementById( id ) );
			this.step = this.$wrapper.height();
		};
		Banners.prototype = $.extend(Banners.prototype, {
			init: function(){
	
				this.$wrapper.find( this.options.banners ).height( this.step ).width( this.$wrapper.width() );
	
				this.$nav = this.$wrapper.find( this.options.nav ).each(function(i) { this.index = i; });
				this.$prev = this.$wrapper.find( this.options.prev );
				this.$next = this.$wrapper.find( this.options.next );
				this.$slider = this.$wrapper.find( this.options.slider );
				
				this.count = this.$nav.size();
				this.currentIndex = 0;
				this.$current = this.$nav.first().addClass('m-banners__nav_item_active');
				
				this.$slider.height( this.count * this.step );
	
				this.bindEvents().setTimer();
				
				return this;
				
			},
			bindEvents: function() {
				
				this.$nav.bind( 'click',$.proxy( this.showItem, this) );
				
				this.$prev.bind('click',$.proxy( this.prev, this ) );
				
				this.$next.bind('click',$.proxy( this.next, this ) );
				
				this.$wrapper.hover(
					$.proxy(function(){
						this.overed = 1;
						this.stopTimer();
					}, this), 
					$.proxy(function(){
						this.overed = 0;
						this.setTimer();
					}, this)
				);
				
				return this;
				
			},
			setTimer: function(){
				if ( this.overed ) { return; }
				this.timer = setInterval($.proxy(this.next, this), 3600);
			},
			stopTimer: function(){
				if( this.timer ) { clearInterval( this.timer ); }
			},
			showItem: function(e) {
				if( (' ' + e.target.className + ' ').indexOf(' m-banners__nav_item_active ') > -1 ) { return; }
				this.go( e.target.index );
			},
			go: function( index ) {
				if( this.isAnimate ){ return; }
				this.stopTimer();
				if( index < 0 || index >= this.count ) {
					index = 0;
				}
				this.currentIndex = index;
				this.$current.removeClass('m-banners__nav_item_active');
				this.$current = this.$nav.eq( this.currentIndex ).addClass('m-banners__nav_item_active');
				
				this.isAnimate = true;
				this.$slider.animate({top: '-'+ this.currentIndex * this.step}, 400, $.proxy(function() {
					this.isAnimate = false;	
					this.setTimer();
				}, this));
			},
			prev: function(){
				this.go( --this.currentIndex );
			},
			next: function(){
				this.go( ++this.currentIndex );
			}
		});
		
		var _default = {
			nav: 'a.b-banners__nav_item',
			prev: 'a.b-banners__nav_prev',
			next: 'a.b-banners__nav_next',
			banners : 'div.b-banners__item',
			slider: 'div.b-banners__body_inn'
		};
		var o = $.extend(_default, options);
		return this.each(function(){
			if( !this.id ) { this.id = 'banners' + parseInt( (new Date()).getTime() ).toString(parseInt(Math.random()*25)+10).toUpperCase(); }
			$(this).data("Banners",( new Banners( this.id, o) ).init());
		});
	};
	
})(jQuery);


(function($, w, undefined){
	/*
	 * @TODO: remove
	 */
	w.updateDateFilter = function(select) {
		var date_begin = new Date($("#year_select").val(), $("#month_select").val() - 1, 1);
		var date_end = new Date($("#year_select").val(), $("#month_select").val(), 0);

		date_end = new Date(Math.min(new Date().getTime(), date_end.getTime()));
		
		$("#trans_time_from").val(date_begin.getFullYear() + '-' + (date_begin.getMonth() + 1) + '-' + date_begin.getDate());
		$("#trans_time_to").val(date_end.getFullYear() + '-' + (date_begin.getMonth() + 1) + '-' + date_end.getDate());
	
		// weeks
		var shiftDate = function(date, day) { return new Date(date.getTime() + day * 24 * 60 * 60 * 1000); }
		var n = date_begin.getDay();
		if (n == 0) { n = 7; }
		var date = shiftDate(date_begin, 1 - n);
		var weeks = Array(), i = 0, str = '';
		while (date.getTime() < date_end.getTime()) {
			str = $.datepicker.formatDate('yy-mm-dd', date);
			date = shiftDate(date, 6);
			str += ' - ' + $.datepicker.formatDate('yy-mm-dd', date);
			date = shiftDate(date, 1);
			weeks[i++] = str;
		}
		w.updateWeekFilter(weeks, select);
	};
	
	w.updateWeekFilter = function(weeks, select) {
		if (document.getElementById("trans_time_weeks") == undefined) return;
		
		var now = new Date().getTime();
		if (select) now = $.datepicker.parseDate('yy-mm-dd', select).getTime();
		
		var item = $("#trans_time_weeks");
		item.children().remove();
		for (var i = 0; i < weeks.length; i++) {
			var dates = weeks[i].split(' - ');
			var selected = '';
			if (i == 0 || (now >= $.datepicker.parseDate('yy-mm-dd', dates[0]).getTime() && now <= $.datepicker.parseDate('yy-mm-dd', dates[1]).getTime())) {
				selected = 'selected="selected"';
				$("#trans_time_from").val(dates[0]);
				$("#trans_time_to").val(dates[1]);
			}
			item.append('<option ' + selected + ' value="' + weeks[i] + '">' + weeks[i] + '</option>');
		}
	}
	
	w.updateDateFilterByWeek = function() {
		if (document.getElementById("trans_time_weeks") == undefined) return;
		var dates = $("#trans_time_weeks").val().split(' - ');
		$("#trans_time_from").val(dates[0]);
		$("#trans_time_to").val(dates[1]);
	}

    $.fn.autoClear = function () {
        $(this).each(function() {
            $(this).data("autoclear", $(this).attr("value"));
        });
        $(this)
            .bind('focus', function() {
                if ($(this).attr("value") == $(this).data("autoclear")) {
                    $(this).attr("value", "").addClass('autoclear-normalcolor');
                }
            })
            .bind('blur', function() {
                if ($(this).attr("value") == "") {
                    $(this).attr("value", $(this).data("autoclear")).removeClass('autoclear-normalcolor');
                }
            });
        return $(this);
    }
 
$(function(){    
    $('.autoclear').autoClear();
});
})(jQuery, window);
