$(function(){
	
	$('input[placeholder], textarea[placeholder]').each(function(){if ($(this).val().length==0) { $(this).val($(this).attr('placeholder')).addClass('hinted') }; });
	$('input[placeholder], textarea[placeholder]').live("focus", function(){if ($(this).val() == $(this).attr('placeholder')) $(this).val('').removeClass('hinted'); });
	$('input[placeholder], textarea[placeholder]').live("blur", function(){if ($(this).val().length==0) { $(this).val($(this).attr('placeholder')).addClass('hinted') }; });	
	
$('.selectors select').live('change', function(){
	var sel = $(this).parent();
	
	if ($(this).hasClass('country')) {
		$(sel).children('.league').remove();
		var c = $(sel).children('.country').val();
		if (!isNaN(c) && $('#league_selectors').children('lcountry_'+c) != undefined) {
			$(sel).append($('#league_selectors').children('.lcountry_'+c));
		}
	}
	
	showLoading($('#matches'));
	ajaxCall('action=matches_get&date='+$(sel).children('.date').val()+'&country='+$(sel).children('.country').val()+'&league='+$(sel).children('.league').val(), 
			function(){showLoading($('#matches'));}, 
			function(){$('#matches').html(json.html)}
	)
})
})

function poolSettle(obj, pool, looser) {
	var h = $(obj).closest('.user');
	showLoading(h);
	ajaxCall('action=pool_settle&pool='+pool+'&looser='+looser, function(){removeLoading(h)}, function(){$(h).find('.settle').html(json.html)})
	return false;
}


function poolCreateTrigger(obj, id) {
	var holder = $(obj).closest('.content-center');
	showLoading(holder);
	$.ajax({type: "POST",url: $('#apiurl').val(),data: 'action=event_status_check&event='+id,
		success: function(msg){	
		json = null;
		try{json = eval("(" + msg + ")");}catch(exception){}
		removeLoading(holder);
			if (json == null || isNaN(json.rv)) {alert($('#unhandledErr').val())
			} else if (json.rv != 1){ alert(json.rt);
			} else {
				$(holder).children('.box-other').toggle();
				$('.pool-create').find('.error').html('').hide();
				$('.pool-create').find('[name="event"]').val(json.id);
				$('.pool-create').find('.name').text(json.name);
				$('.pool-create').find('.meta').text(json.meta);
				$('.pool-create').find('.p_location').hide();
				$('.pool-create').find('.x_stake').val('').blur();
				
				$('.selectors select').hide();				
			}
		}
	});		
}

function poolJoin() {
	var form = $('#bet_container');	
	showLoading(form);
	data = 'action=pool_join&pool='+$('#pool_id').val()+'&home_goals='+$('#home_goals').val()+'&away_goals='+$('#away_goals').val();
	
	$.ajax({type: "POST",url: $('#apiurl').val(),data: data,
		success: function(msg){	
		json = null;
		try{json = eval("(" + msg + ")");}catch(exception){}
		removeLoading(form);
			if (json == null || isNaN(json.rv)) {alert($('#unhandledErr').val());
			} else if (json.rv == 2){$(form).hide(); go(json.url);
			} else if (json.rv != 1){alert(json.rt);
			} else {$(form).hide(); go();
			}
		}
	
	});		
	return false;
}

function poolCreate() {
	var form = $('.pool-create');
	showLoading(form);
	var data = getPostFields(form);
	
	$.ajax({type: "POST",url: $('#apiurl').val(),data: data,
		success: function(msg){	
		json = null;
		try{json = eval("(" + msg + ")");}catch(exception){}
			removeLoading(form);
			if (json == null || isNaN(json.rv)) {alert($('#unhandledErr').val());
			} else if (json.rv != 1){ alert(json.rt);
			} else {$(form).hide(); go(json.link);
			}
		}
	
	});	
	return false;
}

function poolCreateCancel(obj) {
	$(obj).closest('.content-center').children().toggle();
	$('.selectors select').show();	
	return false;
}

function poolInviteFriend(obj, pool, friend) {
	var h = $(obj).parent();		
	var data = getPostFields(h);
	$(h).children().hide();
	$(h).children('.state_wait').show();
	
	$.ajax({type: "POST",url: $('#apiurl').val(),data: 'action=pool_invite_friend&pool='+pool+'&friend='+friend,
		success: function(msg){	
		json = null;
		try{json = eval("(" + msg + ")");}catch(exception){}
		$(h).children().hide();
		if (json == null || isNaN(json.rv)) {alert($('#unhandledErr').val());
		} else if (json.rv != 1){ alert(json.rt);
		} else {
			$(h).children('.state_done').show();			
		}
	}
	});		
	return false;	
}

function poolInvite(obj) {
	var h = $(obj).closest('.box-my');
	var error = $(h).find('.error'); 
	var note = $(h).find('.note'); 
	$(note).hide();		
	$(error).text('').hide();		
	showLoading(h);
	var data = getPostFields(h);
	
	$.ajax({type: "POST",url: $('#apiurl').val(),data: data,
		success: function(msg){	
		json = null;
		try{json = eval("(" + msg + ")");}catch(exception){}
		removeLoading(h);
			if (json == null || isNaN(json.rv)) {$(error).text($('#unhandledErr').val()).show();
			} else if (json.rv != 1){ $(error).text(json.rt).show();
			} else {$(note).show();	$(h).find('.email').val('').blur(); setTimeout(function() {$(note).hide();}, 10000);
			}
		}
	});		
	return false;	
	
}

function ajaxCall(data, callback, success) {
	$.ajax({
		type: "POST",url: $('#apiurl').val(),data: data,
		success: function(msg){	
		json = null;
			try{json = eval("(" + msg + ")");}catch(exception){}
			callback();
			if (json == null || isNaN(json.rv)) {
				alert($('#unhandledErr').val());
			} else if (json.rv != 1){
				if (json.rt != undefined) alert(json.rt); 
			} else {
				success();
			}
		}
	
	});	
}

function modalAjax(form) {
	$(form).find('.error').hide();
	$(form).find('.modify').hide();
	$(form).find('.loading').show();
	var data = getPostFields(form);
	
	$.ajax({
		type: "POST", url: $('#apiurl').val(), data: data,
		success: function(msg){
		$(form).find('.modify').show();
		$(form).find('.loading').hide();
		json = jsonQuery(msg);
		if (json == null || isNaN(json.rv)) {
			$(form).find('.error').html($('#unhandledErr').val()).show();
		} else if (json.rv != 1){
			$(form).find('.error').html(json.rt).show();
		} else {
			$(form).find('.modify').hide();
			if (json.rt != null) {$(form).find('.notify').html(json.rt).show();}
			if (json.js != null) {eval(json.js);}
		}
	}
	});			
}

function getPostFields(form) {
	var data = '';
	$(form).find('.post').each(function(index) {
		var val = $(this).val();
		if ( $(this).attr('type') == 'checkbox' ) {
			if ($(this).is(':checked')) {val = 1;} else {return;}
		} else if ( $(this).attr('type') == 'radio' ) {
			if ($(this).is(':checked') == false) return;
		} else {
			var ph = $(this).attr('placeholder');
			if (ph != undefined && ph == val) return;
		}
		if (data != '') data = data + '&';
		data = data + $(this).attr('name')+"="+encodeURIComponent(val);
	}); 
	return data;
}

function en(val) {return encodeURIComponent(val);}

function modalClean(id) {
	$('#'+id).find('.clean').val(''); 
	$('#'+id).find('.cleanh').html(''); 
	//$('#'+id).find('.cleanx').val('').attr('src', '').text(''); $('#'+id).find('.cleanh').html(''); $('#'+id).find('.cleanhide').hide(); $('#'+id).find('.addr_x').click();
}

function modalShow(id, clean) {
	if (clean) modalClean(id);
	var form = $('#'+id);
	$(form).find('.error').html('').hide();
	$(form).find('.notify').html('').hide(); 
	$(form).find('.buttons').show();
	$(form).show(); 
	$(document.body).css({'overflow': 'hidden'});
	return false;
} 
function modalHide() {$('.modal').hide(); $(document.body).css({'overflow': 'auto'}); return false;} 

function showLoading(into) {
	var loaders = into.find('.loading');
	if( loaders.length == 0 ) {
		into.css({'position': 'relative'}).append(getLoading());
	}
}
function removeLoading(from) {
	from.removeAttr('style');
	from.find('.loading').remove();
}

function getLoading() {
	var img = $('<img src="defaultskin/loading.gif">').addClass('loader-img').css({'border': 'none', 'position': 'relative', 'top': '50%'});
	var loader = $('<div>').addClass('loading').css(
		{'position': 'absolute',
		 'top': 0,
		 'bottom': 0,
		 'left': 0,
		 'right': 0,
		 'background-image': 'url(img/white.png)',
		 'background-repeat': 'repeat',
		 'background-color': 'transparent',
		 'text-align': 'center'
		}).append(img);
	return loader;
}

function jsonQuery(str){try{return eval("(" + str + ")");}catch(exception){return null;}}

function go(url, time) {
	if (isValue(url)) {
		if (isValue(time)) {setTimeout(function() {window.location.href = url}, time);} else {window.location.href = url;}
	} else {
		if (isValue(time)) {setTimeout(function() {location.reload()}, time);} else {location.reload();}
	}
}

function isValue(value) {
	if (value != undefined && value != null && value.length != 0) return true;
	return false;
}
