/** 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.
 */
var foreingKeyResults = [];
(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, imgValue]');
			return;
		}
		
		function handleResult (event, data) {
			$(options.hiddenField).val($.resolveKey(data, options.idValue));
			if(options.imgValue != undefined && options.imgValue != null){$(options.hiddenFieldImg).val($.resolveKey(data, options.imgValue));}
			if(typeof(options.hiddenField.prevObject)!= 'undefined'){
				if(options.hiddenField.prevObject.selector=="#FavoriteClubWidget"){
					if(data.Team.check=='true'){
						window.open(window.location.protocol+'//'+window.location.host+data.Team.url);
					}
				}
				if(options.hiddenField.prevObject.selector=="#FavoritePlayerWidget"){
					if(data.Player.id=='1'){
						window.open(window.location.protocol+'//'+window.location.host+data.Player.url);
					}
				}
			}
			if($.inArray(options.hiddenField,['#ProTransferTeamId','#ProTransferOldTeamId','#NationalTransferTeamId','#AmateurTransferTeamId','#TeamSquadPlayerNameId','#TeamStaffPlayerNameId'])!=-1){
				if(options.hiddenField == '#TeamSquadPlayerNameId' || options.hiddenField == '#TeamStaffPlayerNameId'){
					var teamName = data.Player.value;
				}else{
					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'){
					var id= $(options.hiddenField).val().split(';');
					if(id.length==1){
						if(id == 'notFoundPlayer'){
							showQuickCreateForm('Player', true, data.Player.value);
							$('.closeDiv').show();
						}else{
							$('.checkedPlayer').show();
							$('#allResults').load('/players/getInformations/'+$('#TeamSquadPlayerNameId').val()+'/Player', function(){
								clearEdit();
								$('.resultExistingPlayerTransfers').hide();
								$('.resultExistingPlayerButton').show();
								$('.closeDiv').show();
								NotFoundPlayer($('#PlayerNameTeamName').val(),'result','Player');
							});
						}
					}else{
						for(var i in id){
							$.ajax({
								url:'/players/getInformations/'+id[i]+'/Player',
								success:function(data){
									$('#allResults').append(data);
									$('.resultExistingPlayerTransfers').hide();
									$('.resultExistingPlayerButton').show();
									$('.closeDiv').show();
									var playerName = $('#PlayerNameTeamName').val().split(' (');
									NotFoundPlayer(playerName[0],'result','Player');
								}
							});
						}
					}
				}

				if(options.hiddenField == '#TeamStaffPlayerNameId'){
					var id= $('#TeamStaffPlayerNameId').val().split(';');
					if(id.length==1){
						if(id == 'notFoundStaff'){
							showQuickCreateForm('Staff', true, data.Player.value);
							$('.closeDiv').show();							
						}else{
							$('#staffAllResults').load('/players/getInformations/'+$('#TeamStaffPlayerNameId').val()+'/Staff', function(){
								clearEdit();
								$('.resultExistingPlayerTransfers').hide();
								$('.resultExistingPlayerButton').show();
								$('.closeDiv').show();
								NotFoundPlayer($('#StaffNameTeamName').val(),'result','Staff');
							});
						}
					}else{
						for(var i in id){
							$.ajax({
								url:'/players/getInformations/'+id[i]+'/Staff',
								success:function(data){
									$('#staffAllResults').append(data);
									$('.resultExistingPlayerTransfers').hide();
									$('.resultExistingPlayerButton').show();
								}
							});
						}
						$('.closeDiv').show();
						var playerName = $('#StaffNameTeamName').val().split(' (');
						NotFoundPlayer(playerName[0],'result','Staff');
					}
				}
			}
		};
		
		if (options.formatItem === undef) {
			options.formatItem = function (data, i, max, value, term) {	
				csswhitespace = '';  cssimg = '';
				
				if(typeof(data.Player) != 'undefined'){
					if(data.Player.linkimage == null){data.Player.linkimage = '/img/content/1px-alpha.gif';}
					if(data.Player.id == 'notFoundPlayer'){ 
						csswhitespace = "style='white-space: pre-wrap'";}else{
						cssimg = "<img height='25' width='25' title='"+$.resolveKey(data, options.nameValue)+"' src='"+data.Player.linkimage+"'>";
					}					
					return "<span "+csswhitespace+" title='"+$.resolveKey(data, options.nameValue)+"'>"+cssimg+$.resolveKey(data, options.nameValue)+'</span>';
				}else if(typeof(data.Team) != 'undefined'){
					if(data.Team.linkimage == null){ data.Venue={}; data.Venue.linkimage = '/img/content/1px-alpha.gif';}
					if(data.Team.id == 'notFoundTeam'){ 
						csswhitespace = "style='white-space: pre-wrap'";}else{
						cssimg = "<img height='25' width='25' title='"+$.resolveKey(data, options.nameValue)+"' src='"+data.Team.linkimage+"'>";
					}					
					return "<span "+csswhitespace+" title='"+$.resolveKey(data, options.nameValue)+"' />"+cssimg+$.resolveKey(data, options.nameValue)+'</span>';
				}else if(typeof(data.Venue) != 'undefined'){
					if(data.Venue.linkimage == null){data.Team.linkimage = '/img/content/1px-alpha.gif';}
					if(data.Venue.id == 'notFoundVenue'){ 
						csswhitespace = "style='white-space: pre-wrap'";}else{
						cssimg = "<img height='25' width='25' title='"+$.resolveKey(data, options.nameValue)+"' src='"+data.Venue.linkimage+"' />";
					}
					
					return "<span "+csswhitespace+" title='"+$.resolveKey(data, options.nameValue)+"'>"+cssimg+$.resolveKey(data, options.nameValue)+"</span>";
				}else if(typeof(data.Competition) != 'undefined'){
					if(data.Competition.linkimage == null){data.Competition.linkimage = '/img/content/1px-alpha.gif';}
					return "<img height='25' width='25' title='"+$.resolveKey(data, options.nameValue)+"' src='"+data.Competition.linkimage+"'>"+$.resolveKey(data, options.nameValue);
				}else{
					return "<span title='"+$.resolveKey(data, options.nameValue)+"'>"+$.resolveKey(data, options.nameValue)+"</span>";
				}
			};
		}
		
		if (options.parse === undef) {
			options.parse = function (response) {
				var unique = [];
				var count = {};
				var toDel = [];
				var parsed = [];
				var rows = response.data;
				foreingKeyResults = rows;
				var newRows = [];
				//Concatenation des resultat de recherche avec comptage
				//utilise pour le quick create/add player dans Team/Squad
				if(options.hiddenField == '#TeamSquadPlayerNameId' || options.hiddenField == '#TeamStaffPlayerNameId'){
					for(var i=0;i<rows.length;i++){
						if(rows[i]!=undefined){
							if($.inArray(rows[i].Player.name,unique) == -1){
								if(rows[i].Player.id == 1){
									rows = [];
									break;
								}
								unique.push(rows[i].Player.name);
								newRows.push(rows[i]);
								eval('count.'+str_to_key(addslashes(rows[i].Player.name))+' = {"count": "1","key":"'+(newRows.length-1)+'"}');
								
							}else{
								rows[eval('count.'+str_to_key(rows[i].Player.name)+'.key')].Player.id += ';'+rows[i].Player.id;
								eval('count.'+str_to_key(rows[i].Player.name)+'.count++;');
							}
						}
					}
					rows = newRows;
					$.each(count,function(key,value){
						if(value.count > 1){
							if(rows[value.key].hasOwnProperty('Player')){
								rows[value.key].Player.name += ' ('+ value.count+')';
							}
						}
						rows[value.key].Player.value = rows[value.key].Player.name;
					});
				}
				//alert(rows.length);
				//Si on est dans le squad et que l'on veut ajouter un player Et que la recherche est vide
				if(options.hiddenField == '#TeamSquadPlayerNameId'){			
					if(rows.length == 0){
						rows[0]={
							"Player":{
								id:"notFoundPlayer",
							    //Phrase: does not exist on YouFoot. Create this player?;
								name:$('#PlayerNameTeamName').val()+' '+YouFoot.i18n.get("does not exist on YouFoot. Create this player?"),
								value:$('#PlayerNameTeamName').val()
							}
						};
					}
				}
				//Si on est dans le staff et que l'on veut ajouter un player Et que la recherche est vide
			
				if(options.hiddenField == '#MatchHomeTeamId'){
					//alert('1');
					//alert(JSON.stringify(rows));
					if(rows.length == 0){
					$('#home-match-timezone').text('').css('display','none');
					$('.home-match-timezone').val('');
					$('#drop-down-timezone').css('display','inline');
					$("#MatchHomeTeam").toggleClass("ac_loading");					
					/*rows[0]={
							"Team":{
								id:"MatchHomeTeam",
								name:$('#MatchHomeTeam').val()+' '+YouFoot.i18n.get('does not exist on YouFoot. Create this team?'),
								value:$('#MatchHomeTeam').val()
							}
						};*/
					}
				}	
				
				if(options.hiddenField == '#MatchAwayTeamId'){
					if(rows.length == 0){
					$('#away-match-timezone').text('').css('display','none');
					$('.away-match-timezone').val('');
					$('#drop-down-timezone').css('display','inline');
					$("#MatchAwayTeam").toggleClass("ac_loading");
					}
				}				
				//Si on est dans le staff et que l'on veut ajouter un player Et que la recherche est vide
				if(options.hiddenField == '#TeamStaffPlayerNameId'){
					if(rows.length == 0){
						rows[0]={
							"Player":{
								id:"notFoundStaff",
								//Phrase: Create this staff member's page?    
								name:YouFoot.i18n.get("Create this staff members page?"), 
								value:$('#StaffNameTeamName').val()
							}
						};
					}
				}
				
				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 && options.hiddenField != '#TeamSquadPlayerNameId' && options.hiddenField != '#TeamStaffPlayerNameId'){
					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') {
						$("#TeamStadium").toggleClass("ac_loading");
						$('#venueCreateName1').attr('type',venueToCreateType);
						$('#venueCreateName1').html('<strong>'+venueToCreate+'</strong>');
						$('#valid_Stadium').attr("src","/img/forms/field_error_icon.png");
						$('#CreateVenueButton1').show();
					}else if(venueToCreateElementId == '#MatchVenueIdOther' || venueToCreateElementId == '.otherStadium'){
						
						$("#MatchOtherStadium").toggleClass("ac_loading");
						$('#venueCreateName').attr('type',venueToCreateType);
						$('#venueCreateName').html('<strong>'+venueToCreate+'</strong>');						
						//$('#valid_training_ground').attr("src","/img/forms/field_error_icon.png");
						$('#other-match-timezone').text('').css('display','none');
						$('.other-match-timezone').val('');
						$('#match-date-field').find('input').attr("disabled", "");
						if($('.selection').is(':checked') == false){
						$('#drop-down-timezone').css('display','inline');
						}
						$('#CreateVenueButton').show();	
					 
					}else{
						$("#TeamTrainingGround").toggleClass("ac_loading");
						$('#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 addslashes(ch) {
	var reg1 = new RegExp('[^a-zA-Z0-9_] ','g');
	ch = ch.replace(/\\/g,"\\\\");
	ch = ch.replace(reg1,"_");
	return ch;
}
function str_to_key(str){
	var reg = new RegExp("[ ]|[?]","g");
	return str.replace(reg,'_');
}

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