/*-------------------------------------------------------------------- 
 * JQuery Plugin: "EqualHeights" & "EqualWidths"
 * by:
   Scott Jehl (scott@filamentgroup.com) 
   Todd Parker (todd@filamentgroup.com)
   http://www.filamentgroup.com
 *
 * Copyright (c) 2007 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
 *
 * Description: Compares the heights of the first-children of a provided element 
 								  and sets their min-height to the tallest height. Sets in em units by default if pxToEm() method is available.
 * Dependencies: jQuery library, pxToEm method (article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)						  
 * Usage Example: $(element).equalHeights();
   						      Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
 * Version: 1.0, 08.02.2007
 * Changelog:
 *  08.02.2007 initial Version 1.0
--------------------------------------------------------------------*/

$.fn.equalHeights = function(px) {
	$(this).each(function(){
		var currentTallest = 0;
		$(this).children().each(function(i){
			if($(this).height() > currentTallest) { currentTallest = $(this).height(); }
		});
		if(!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm($(this)); //use ems unless px is specified or 
		// for ie6, set height since min-height isn't supported
		var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
		if ($.browser.msie && (ie6)) { $(this).children().css({'height': currentTallest}); }
		$(this).children().css({'min-height': currentTallest}); 
	});
	return $(this);
};

$.fn.equalWidths = function(px) {
	$(this).each(function(){
		var currentWidest = 0;
		$(this).children().each(function(i){
				if($(this).width() > currentWidest) { currentWidest = $(this).width(); }
		});
		if(!px || !Number.prototype.pxToEm) currentWidest = currentWidest.pxToEm($(this)); //use ems unless px is specified or 
		// for ie6, set width since min-width isn't supported
		var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
		if ($.browser.msie && (ie6)) { $(this).children().css({'width': currentWidest}); }
		$(this).children().css({'min-width': currentWidest}); 
	});
	return $(this);
};


/*-------------------------------------------------------------------- 
 * javascript method: "pxToEm"
 * by:
   Scott Jehl (scott@filamentgroup.com) 
   Maggie Wachs (maggie@filamentgroup.com)
   http://www.filamentgroup.com
 *
 * Copyright (c) 2008 Filament Group
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 *
 * Description: Extends the native Number and String objects with pxToEm method. pxToEm converts a pixel value to ems depending on inherited font size.  
 * Article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/
 * Demo: http://www.filamentgroup.com/examples/pxToEm/	 	
 *							
 * Options:  	 								
 		scope: string or jQuery selector for font-size scoping
 		reverse: Boolean, true reverses the conversion to em-px
 * Dependencies: jQuery library						  
 * Usage Example: myPixelValue.pxToEm(); or myPixelValue.pxToEm({'scope':'#navigation', reverse: true});
 *
 * Version: 2.0, 08.01.2008 
 * Changelog:
 *		08.02.2007 initial Version 1.0
 *		08.01.2008 - fixed font-size calculation for IE
--------------------------------------------------------------------*/

Number.prototype.pxToEm = String.prototype.pxToEm = function(settings){
	//set defaults
	settings = jQuery.extend({
		scope: 'body',
		reverse: false
	}, settings);
	
	var pxVal = (this == '') ? 0 : parseFloat(this);
	var scopeVal;
	var getWindowWidth = function(){
		var de = document.documentElement;
		return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
	};	
	
	/* When a percentage-based font-size is set on the body, IE returns that percent of the window width as the font-size. 
		For example, if the body font-size is 62.5% and the window width is 1000px, IE will return 625px as the font-size. 	
		When this happens, we calculate the correct body font-size (%) and multiply it by 16 (the standard browser font size) 
		to get an accurate em value. */
				
	if (settings.scope == 'body' && $.browser.msie && (parseFloat($('body').css('font-size')) / getWindowWidth()).toFixed(1) > 0.0) {
		var calcFontSize = function(){		
			return (parseFloat($('body').css('font-size'))/getWindowWidth()).toFixed(3) * 16;
		};
		scopeVal = calcFontSize();
	}
	else { scopeVal = parseFloat(jQuery(settings.scope).css("font-size")); };
			
	var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px' : (pxVal / scopeVal).toFixed(2) + 'em';
	return result;
};


/*-------------------------------------------------------------------- 
Utility functions
Version: 1.0, 01.18.2008

By: Maggie Costello Wachs (maggie@filamentgroup.com)
	http://www.filamentgroup.com
		
Copyright (c) 2007 Filament Group
Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)

Dependencies:
	jQuery library
--------------------------------------------------------------------*/

function sortBigToSmall(a, b) { return b - a; };

function getScrollTop(){
	return self.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
};

function getScrollLeft(){
	return self.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
};

function getWindowHeight(){
	var de = document.documentElement;
	return self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
};

function getWindowWidth(){
	var de = document.documentElement;
	return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
};

// getTotalWidth/Height finds the width/height of an element including padding
jQuery.fn.getTotalWidth = function(){
	return $(this).width() + parseInt($(this).css('paddingRight')) + parseInt($(this).css('paddingLeft'));
};

jQuery.fn.getTotalHeight = function(){
	return $(this).height() + parseInt($(this).css('paddingTop')) + parseInt($(this).css('paddingBottom'));
};

// assign random ids to a single element or a group of child elements
jQuery.fn.setRandomId = function(settings){
	var settings = jQuery.extend({
		children: null, // selectors for child elements (acts only on the caller element by default)
		attribute: null // attribute, if not id (default)
	}, settings);
	
	var thisAttr = settings.attribute || 'id';
		
	var setId = function(el){
		var newId = 'id_' + Math.floor(Math.random()*9999);
		el.attr(thisAttr, newId);
	};
	
	if (settings.children) {
		$(this).find(settings.children).each(setId($(this)));
	}
	else { setId($(this)); }
	
	return $(this);
};
/**
 * jQuery.ScrollTo
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 3/9/2009
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Works with jQuery +1.2.6. Tested on FF 2/3, IE 6/7, Opera 9.5/6, Safari 3, Chrome 1 on WinXP.
 *
 * @author Ariel Flesler
 * @version 1.4.1
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} duration The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 *	 @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends. 
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @desc Scroll to a fixed position
 * @example $('div').scrollTo( 340 );
 *
 * @desc Scroll relatively to the actual position
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @dec Scroll using a selector (relative to the scrolled element)
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @ Scroll to a DOM element (same for jQuery object)
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');																   
 *			}});
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window).scrollable();
	};

	// Hack, hack, hack... stay away!
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn.scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this.scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					Dim = axis == 'x' ? 'Width' : 'Height';

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[Dim.toLowerCase()]() * settings.over[pos];
				}else
					attr[key] = targ[pos];

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

			// Max scrolling position, works on quirks mode
			// It only fails (not too badly) on IE, quirks mode.
			function max( Dim ){
				var scroll = 'scroll'+Dim;
				
				if( !win )
					return elem[scroll];
				
				var size = 'client' + Dim,
					html = elem.ownerDocument.documentElement,
					body = elem.ownerDocument.body;

				return Math.max( html[scroll], body[scroll] ) 
					 - Math.min( html[size]  , body[size]   );
					
			};

		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );

function fixBookmarks(){
	var fixBookmarkHash = location.hash.replace(/#/,'');
	var fixBookmarkElement = $(".bookmark[data-target='"+fixBookmarkHash+"']:eq(0)");
	if( fixBookmarkElement.attr('data-target') ) {
		$.scrollTo(fixBookmarkElement,10,{offset:{top: -150, left: 0}});
	}
}

function goToBookmark(obj) {
	$.scrollTo(obj,10,{offset:{top: -150, left: 0}});
	location.hash = '#' + obj.attr('data-target');
}

var showTable = '';
/***/
$(document).ready( function() {
	$('.smart-field').focus( function() {
		if(!$(this).attr('data-changed')) {
			if($(this).attr("value") == $(this).attr('data-default-value')) {
				$(this).attr({value: ""});
				$(this).removeAttr('style');
			}
		}
	});
	
	$('.smart-field').blur( function() {
		if($(this).attr("value") == "") {
			$(this).attr({value: $(this).attr('data-default-value')});
			$(this).css({color: "#aaa"});
		}
	});
	
	$('.smart-field').change( function() {
		$(this).attr({'data-changed': 1});
	});
	
	$('.smart-form').submit( function() {
		jQuery.each( $('.smart-field', this), function() {
			if(!$(this).attr('data-changed')) {
				if( $(this).attr('value') == $(this).attr('data-default-value') ) {
					$(this).attr({value: ""});
				}
			}
		});
		
		if( $(this).hasClass('login-form') ) {
			$('#login-error').hide();
			$(".login-form input[type='submit']").attr({ disabled: "disabled", value: "Проверяю..."})
			$.post($(this).attr('data-ajax'), $('.login-form').serializeArray(), function(data){
				if (data && data.result == 'true') {
					window.location.reload();
				}
				else { 
					$('#login-error').show();
					jQuery.each( $('.login-form .smart-field'), function() {
						if( $(this).attr('value') == "") {
							$(this).attr({value: $(this).attr('data-default-value')});
							$(this).css({color: "#aaa"});
							$(this).removeAttr('data-changed');
						}
					});
					$(".login-form input[type='submit']").attr({value: "Войти"});
					$(".login-form input[type='submit']").removeAttr('disabled');
				}
			}, 'json');
			return false;
		} else {
			return true;
		}
	});
	
	$('.smart-control-popup-show').click(function(){
		$('.smart-popup').css({display: 'none'});
		$('.'+$(this).attr('data-popup-ui')).css({display: 'block'});
		return false;
	});
	
	$('.smart-control-popup-hide').click(function(){
		$('.smart-popup').css({display: 'none'});
		$('.'+$(this).attr('data-popup-ui')).css({display: 'none'});
		return false;
	});
	
	$('.popup-helper').click(function() {
		$('.smart-popup').css({display: 'none'});
	});

	jQuery.each( $('.smart-field'), function() {
		if( $(this).attr('value') == "") {
			$(this).attr({value: $(this).attr('data-default-value')});
			$(this).css({color: "#aaa"});
		}
	});
	
	if(showTable) {
		$('.league_table').css({display: 'block'});
		$(".league-navi-button[data-act='table']").addClass('active');
	}
	else {
		$('.league_photos').css({display: 'block'});
		$(".league-navi-button[data-act='photo']").addClass('active');
	}
	
	$('.league-navi-button').click( function() {
		if( !$(this).hasClass('active') ){
			$('.league_table').stop(true,true);
			$('.league_photos').stop(true,true);
			if( $(this).attr('data-act') == 'table' ) {
				$(".league-navi-button[data-act='table']").addClass('active');
				$(".league-navi-button[data-act='photo']").removeClass('active');
				$('.league_photos').slideUp(300, function() {$('.league_table').slideDown(300)});
			}
			else {
				$(".league-navi-button[data-act='photo']").addClass('active');
				$(".league-navi-button[data-act='table']").removeClass('active');
				$('.league_table').slideUp(300, function() {$('.league_photos').slideDown(300)});
			}
		}
	});
    
    $('.form-add-club').click(function() {
        $.post($(this).attr('data-ajax'), {club_id: $(this).attr('data-club-id')}, function(data) {
            if (data && data.result == 'true') {
                window.location.reload();
            }
        }, 'json');
        return false;
    });
        
    $('.form-link-club').click(function() {
        window.location = $(this).attr('href');
    });

    $('.form-delete-club').click(function() {
        if (confirm("Вы уверены, что хотите удалить этот клуб из закладок ?")) {
            $.post($(this).attr('data-ajax'), {club_id: $(this).attr('data-club-id')}, function(data) {
                if (data && data.result == 'true') {
                    window.location.reload();
                }
            }, 'json');
        }
        return false;
    });
    
	fixBookmarks();	
	$('a').click( function () {
		fixBookmarks();
	});
	
	$("#clubsInput").keydown(function(e) {
		var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
		if(key == 13) {
			e.preventDefault();
			addSelectedClub();
		}
	});
	
});

