/** andre dominique amine
 * Resolve Key for autocomplete
 * Make it global to reuse in callbacks
 */
 (function ($) {
	$.resolveKey = function(dataset, name) {
			var keys = name.split('.'),
				current = keys.shift(),
				valueStack = dataset;

			while (current) {
				if (valueStack[current] == undefined) {
					return '';
				}
				valueStack = valueStack[current];
				current = keys.shift();
			}
			return valueStack;
	};
})(jQuery);


/**
 * Foreign Key autocomplete
 * Allows for foriegn Key autocompletion.
 * 
 * Options
 *  - idValue - the json key to your ID value ie. 'Team.id'
 *  - nameValue - the json key to your name value ie. 'Team.name'
 *  - hiddenField - Selector to hidden field.
 * 
 * You may also replace parse, and formatItem callbacks by specifying them in the options.
 */

(function ($) {
	$.fn.foreignKeyAutocomplete = function(url, options) {
		var undef;

		options = $.extend({}, $.fn.foreignKeyAutocomplete.defaults, options);

		if (options.hiddenField == null || options.nameValue == null || options.idValue == null) {
			alert('Missing required options, [hiddenField, nameValue, idValue]');
			return;
		}
		
		function handleResult (event, data) {
			$(options.hiddenField).val($.resolveKey(data, options.idValue));
			if($.inArray(options.hiddenField,['#ProTransferTeamId','#ProTransferOldTeamId','#NationalTransferTeamId','#AmateurTransferTeamId','#TeamSquadPlayerNameId'])!=-1){
				var teamName = $(options.hiddenField).prev().find('input:first').val();
				$(options.hiddenField).prev().find('input:first').hide().next().show().find('label:first').html(teamName);
				
				if(options.hiddenField == '#TeamSquadPlayerNameId'){
					$('.checkedPlayer').show();
					$('#resultExistingPlayerInfobox').load('/players/getInformations/'+$('#TeamSquadPlayerNameId').val());
					$('#resultExistingPlayerTransfers').load('/transfers/viewer/'+$('#TeamSquadPlayerNameId').val(), function(){
						clearEdit();
						$('#resultExistingPlayerTransfers').hide()
						$('#resultExistingPlayerButton').show();
						$('.closeDiv').show();
					});
				}
			}
		};
		
		if (options.formatItem === undef) {
			options.formatItem = function (data, i, max, value, term) {
				return $.resolveKey(data, options.nameValue)
			};
		}
		
		if (options.parse === undef) {
			options.parse = function (response) {
				var parsed = [];
				var rows = response.data;
				for (var i in rows) {
					var curRow = rows[i];
					parsed[i] = {
						data : curRow,
						value : $.resolveKey(curRow, options.nameValue),
						result : $.resolveKey(curRow, options.nameValue)
					};
				}
				var pages = ['teams/add','matches/add','matches/edit','teams/edit'];
				var url = $.url.segment(0)+'/'+$.url.segment(1);
				if(rows.length == 0 && $.inArray(url,pages)!= -1 ){
					if($.url.segment(0) =='matches' ){
						var venueToCreate = $('#MatchOtherStadium').val();
					}else{
						var venueToCreate =$(options.hiddenField).prev('div').children('input:first').val();
						
					}
					venueToCreateElementId = options.hiddenField;
					var venueToCreateType = options.extraParams.type;
					
					
					$('#TeamStadium').flushCache();
					$('#TeamTrainingGround').flushCache();
					$('#TeamHeadquarters').flushCache();
					$(".ac_results").hide();
					//aucun resultat afficher create venue
				
					if (venueToCreateElementId == '#TeamHomeVenueId') {
						$('#venueCreateName1').attr('type',venueToCreateType);
						$('#venueCreateName1').html('<strong>'+venueToCreate+'</strong>');
						$('#valid_Stadium').attr("src","/img/forms/field_error_icon.png");
						$('#CreateVenueButton1').show();
					}else{
						$('#venueCreateName2').attr('type',venueToCreateType);
						$('#venueCreateName2').html('<strong>'+venueToCreate+'</strong>');						
						$('#valid_training_ground').attr("src","/img/forms/field_error_icon.png");
						$('#CreateVenueButton2').show();
					}
				}else{
					$('#TeamStadium').flushCache();
					$('#TeamTrainingGround').flushCache();
					$('#TeamHeadquarters').flushCache();
					//$(options.hiddenField).parent().children('div:last').hide();
					
					if(typeof(venueToCreateElementId) != 'undefined'){
						if (venueToCreateElementId == '#TeamHomeVenueId') {
							$('#CreateVenueButton1').hide();
						}else{
							$('#CreateVenueButton2').hide();
						}
					}
					$('#Quick-Create-Venue-div').fadeOut();
					return parsed;
				}
			};
		}
		
		return this.each(function() {
			var $this = $(this);
			if (options.handlerFunction == null) {
				$this.autocomplete(url, options).result(handleResult);
			} else {
				$this.autocomplete(url, options).result(options.handlerFunction);
			}
		});
	};

	$.fn.foreignKeyAutocomplete.defaults = {
		hiddenField : null,
		dataType : 'json',
		idValue : null,
		nameValue : null
	};
})(jQuery);


/**
 * Clear input jquery plugin.
 * binds a click event to an element, allowing it to clear
 * an adjacent input element.
 * 
 */
 (function ($) {
	$.fn.clearField = function (options) {

		var doClear = function (event) {
			$(this).siblings('input').val('');
			return false;
		}

		return this.each(function () {
			$(this).bind('click', doClear);
		});
	};
	
	$.fn.clearField.defaults = {
		
	};
})(jQuery);

/**
 * disableInputs()
 * enableInputs()
 * toggleInputs()
 * 
 * Disable all the inputs inside an element. and hide the form.
 * Enable all inputs inside an element and show the form
 * Toggle the inputs / element from hidden to shown.
 */
(function ($) {
	$.fn.toggleInputs = function(options) {
		var state = bool ? fn : $(this).is(":hidden");

		return this.each(function () {
			$(this).form[ state ? "enableInputs" : "disableInputs" ]();
		})
	}

	$.fn.disableInputs = function (options) {
		options = jQuery.extend({}, $.fn.disableInputs.defaults, options);
		
		return this.each(function () {
			if (options.hide) {
				$(this).hide();
			}
			$(options.selector, this).attr('disabled', 'disabled');
		});
	};

	$.fn.enableInputs = function (options) {
		options = jQuery.extend({}, $.fn.disableInputs.defaults, options);
		
		return this.each(function () {
			if (options.hide) {
				$(this).show();
			}
			$(options.selector, this).removeAttr('disabled');
		});
	};
	
	$.fn.disableInputs.defaults = {
		hide : true,
		selector : 'input[type!=submit]'
	};
})(jQuery);

// Simple add and remove of disabled attribute and 
// Disabled classname.
(function ($) {
	$.fn.disable = function (className) {
		className = className || 'disabled';
		this.addClass(className);
		this.attr('disabled', 'disabled');
		return this;
	}
	$.fn.enable = function (className) {
		className = className || 'disabled';
		this.removeClass(className);
		this.removeAttr('disabled');
		return this;
	}
})(jQuery);

// Add table sorter widgets
if ($.tablesorter) {
	//
	// keepStyle widget
	//
	// Maintains style info when table rows are resorted
	// used on competition tables to ensure tables stay coloured properly.
	$.tablesorter.addWidget({
		id: 'keepStyle',
		headerCache: null,
		format: function (table) {
			if (!this.headerCache) {
				var headerCache = this.headerCache = []; 
				$('tbody tr', table).each(function () {
					headerCache.push($(this).attr('style'));
				});
			}
			for (var i = 0, len = this.headerCache.length; i < len; i++) {
				if (!table.tBodies[0].rows[i]) {
					continue;
				}
				$(table.tBodies[0].rows[i]).attr('style', this.headerCache[i]);
			}
		}
	});
}





function showGridNow(){
	if($('#GridToolbox').css('display') != 'none'){
		$('#GridToolbox').css('display','none');
	}
	else{
		$('#GridToolbox').css('display','block');
	}
}
