/*loading forms in popups */
function show_form(title, form_type, btn1_label, btn2_label, extra_vars){
	
	if(btn1_label == null) btn1_label = 'Okay';
	if(btn2_label == null) btn2_label = 'Cancel';
	
	var d = new Dialog(1, form_type).showChoice(title, '',btn1_label,btn2_label).setStyle({'height':'600px','width':'400px'});
	$("dialog_user_content").innerHTML = 'Loading form, please wait...';
	d._button_okay.disabled = true;
	var params = {
					'ajax':'forms',
					'form_type':form_type,
					'extra_var':extra_vars
				};
	if(arguments[5]) params['extra_var2']=arguments[5];
	if(arguments[6]) params['extra_var3']=arguments[6];
	new Ajax.Request('index.php',{
		method:'get',
		parameters: params,
		onSuccess: function(transport){
			var response = transport.responseText;
			if(response){
				$("dialog_user_content").innerHTML=response;
				d._button_okay.disabled = false;
			}
			
			d.onconfirm = function(){
				d._button_okay.disabled = true;
				// validation here
				var errors = validate(form_type);
				if(errors == ''){
					params = get_form_params(form_type);
				
					new Ajax.Request('index.php',{
						method:'post',
						parameters: params,
						onSuccess: function(transport){
							// an update here
							var response = transport.responseText;
							var result = response.search(/<!-- error: -->/);
							//alert(response);
							//alert(result);
							if(result == -1){
								update_div(form_type,params,response);
								d.destroy();
							}else{
								// was included for outputing error after submission
								d._button_okay.disabled = false;
								var e = new Dialog(1, 'error').showMessage('Error', response, 'Close');
								e.onconfirm = function(){e.destroy();}
							}
							if(form_type=='update_info2'){
								show_form('Getting Started', 'get_started', 'Okay','Skip');
							}
							if(form_type=='get_started'){
								create_team();
							}
						},
						onFailure: function(){}
						
					});
					//d.destroy();
				}else{
					d._button_okay.disabled = false;
					var e = new Dialog(1, 'error').showMessage('Error', errors, 'OK');
					e.onconfirm = function(){e.destroy();}
				}
			};
/*			d.oncancel = function(){
				if(form_type=='update_info2'){
					var txt = '<a href="?p=home&section=games">Create a pickup game.</a><br>';
					txt += '<a href="?p=home&section=games">Create a league game.</a><br>';
					txt += '<a href="?p=home&section=games">Create a tournament game.</a><br>';
					txt += '<a href="?p=home&section=teams">Create a team page for you and your teammates.</a><br>';
					var d3 = new Dialog(1, 'Getting Started').showMessage('Getting Started', txt, 'Skip this step.');
					d3.onconfirm = function(){d3.destroy();}
				}
				d.destroy();
			};*/

        	//d.showMessage('Relationship Changed','A relationship request has been sent to '+full_name+'.','OK');
		}.bindAsEventListener(d),
		onFailure: function(){}
	});
}

// getting form parameters for submission
function get_form_params(form_type){
	var params = new Array();
	
	switch(form_type){
		case 'create_game': 
			params = {
				'fa'			: 'games',
				'action'		: 'save_game',
				'name'			: $('name').value,
				'tagline'		: $('tagline').value,
				'network_id'	: $('network').value,
				'network_name'	: $('network').options[$('network').selectedIndex].text,
				'host_text'		: $('host_text').value,
				'host_select'	: $('host_select').value,
				'host_name'		: $('host_select').options[$('host_select').selectedIndex].text,
				'category'		: $('category').value,   //6, // Sports
				'subcategory'	: $('subcategory').value,
				'description'	: $('description').value,
				'start_month'	: $('start_month').value,
				'start_day'		: $('start_day').value,
				'start_year'	: $('start_year').value,
				'start_hour'	: $('start_hour').value,
				'start_minute'	: $('start_minute').value,
				'start_meridian': $('start_meridian').value,
				'end_month'		: $('end_month').value,
				'end_day'		: $('end_day').value,
				'end_year'		: $('end_year').value,
				'end_hour'		: $('end_hour').value,
				'end_minute'	: $('end_minute').value,
				'end_meridian'	: $('end_meridian').value,
				'age_group'		: $('agegroup').value,
				'gender'		: $('gender').value,
				'size'			: $('size').value,
				'min_needed'	: $('min_needed').value,
				'coaches'		: $('coaches').value,
				'referees'		: $('referees').value,
				'location'		: $('location').value,
				'street'		: $('street').value,
				'city'			: $('city').value,
				'phone'			: $('phone').value,
				'email'			: $('email').value,
				'domain'		: $('site_url').value 	// needed for redirection
			};
			break;
		case 'join_game':
			var position = '';
			if($('type_select').value == 'player'){
				position = $('position_select').value;
			}else if($('type_select').value == 'coach'){
				position = $('coachtype_select').value;
			}
			params = {
				'fa'			: 'games',
				'action'		: 'join_game',
				'game_id'		: $('game_id').value,
				'game_name'		: $('game_name').value,
				'team_id'		: 1,
				'type'			: $('type_select').value,
				'position' 		: position
			};
			break;	
		case 'create_team':
			params = {
				'fa'			: 'teams',
				'action'		: 'save_team',
				'name'			: $('name').value,
				'network'		: $('network').value,
				'description'	: $('description').value,
				'category'		: $('category').value,
				'subcategory'	: $('subcategory').value,
				'age_group'		: $('agegroup').value,
				'gender'		: $('gender').value,
				'rnews'			: $('rnews').value,
//				'office'		: $('office').value,
//				'street'		: $('street').value,
				'homefield'		: $('home_field').value,
				'city'			: $('city').value,
				'state'			: $('state').value,
				'email'			: $('email').value,
				'domain'		: $('site_url').value 	// needed for redirection
			};
			 break;
		case 'edit_team':
			params = {
				'fa'			: 'teams',
				'action'		: 'edit_team',
				'team_id'		: $('team_id').value,
				'name'			: $('name').value,
				'network'		: $('network').value,
				'description'	: $('description').value,
				'category'		: $('category').value,
				'subcategory'	: $('subcategory').value,
				'age_group'		: $('agegroup').value,
				'gender'		: $('gender').value,
				'rnews'			: $('rnews').value,
//				'office'		: $('office').value,
//				'street'		: $('street').value,
				'homefield'		: $('home_field').value,
				'city'			: $('city').value,
				'state'			: $('state').value,
				'email'			: $('email').value,
				'domain'		: $('site_url').value 	// needed for redirection
			};
			 break;
		case 'join_team':
			var position = '';
			if($('type_select').value == 'player'){
				position = $('position_select').value;
			}else if($('type_select').value == 'coach'){
				position = $('coachtype_select').value;
			}
			params = {
				'fa'			: 'teams',
				'action'		: 'join_team',
				'team_id'		: $('team_id').value,
				'team_name'		: $('team_name').value,
				'type'			: $('type_select').value,
				'position' 		: position,
				'jerseyNum'		: $('jerseyNumber').value
			};
			break;		 	
		case 'update_info':
			params = {
//				'fa'			: 'user_info',
				'fa'			: 'profiles',
				'action'		: 'profile_save',
				'fan'			: $('fan').checked,
				'player'		: $('player').checked,
				'coach'			: $('coach').checked,
				'referee'		: $('referee').checked,
				'email'			: $('email').value,
				'height'		: $('height').value,
				//'weight'		: $('weight').value,
				'jersey_number'	: $('jersey_number').value,
				'skill_level'	: $('skill_level').value,
				'teams_played_for' : $('teams_played_for').value,
				'lr_footed'		: $('lr_footed').value,
				'position'		: $('position').value,
				'fav_teams'		: $('fav_teams').value,
				'fav_brand'		: $('fav_brand').value,
				'fav_players'	: $('fav_players').value,
				'future_team'	: $('future_team').value,
				'other_sports'	: $('other_sports').value,
				'city'			: $('city').value,
				'state'			: $('state').value,
				'country'		: $('country').value,
				'timezone'		: $('timezone').value
			};	 
			break;
		case 'update_info2':
			params = {
//				'fa'			: 'user_info',
				'fa'			: 'profiles',
				'action'		: 'profile_save',
				'fan'			: $('fan').checked,
				'player'		: $('player').checked,
				'coach'			: $('coach').checked,
				'referee'		: $('referee').checked,
				'email'			: $('email').value,
				'height'		: $('height').value,
				//'weight'		: $('weight').value,
				'jersey_number'	: $('jersey_number').value,
				'skill_level'	: $('skill_level').value,
				'teams_played_for' : $('teams_played_for').value,
				'lr_footed'		: $('lr_footed').value,
				'position'		: $('position').value,
				'fav_teams'		: $('fav_teams').value,
				'fav_brand'		: $('fav_brand').value,
				'fav_players'	: $('fav_players').value,
				'future_team'	: $('future_team').value,
				'other_sports'	: $('other_sports').value,
				'city'			: $('city').value,
				'state'			: $('state').value,
				'country'		: $('country').value,
				'timezone'		: $('timezone').value
			};	 
			break;
		case 'update_timezone':
			params = {
				'fa'			: 'profiles',
				'action'		: 'update_timezone',
				'timezone'		: $('timezone').value
			};
			break;
		case 'profile_message':
			params = {
//				'fa'			: 'profile_message',
				'fa'			: 'profiles',
				'action'		: 'profile_message',
				'pid'			: $('pid').value,
				'subject'		: $('subject').value,
				'message'		: $('message').value
			};	 
			break;
		case 'profile_addfriend':
			params = {
//				'fa'			: 'profile_addfriend',
				'fa'			: 'profiles',
				'action'		: 'profile_addFriend',
				'pid'			: $('pid').value,
				'fbpid'			: $('fbpid').value
			};	 
			break;
		case 'profile_removefriend':
			params = {
//				'fa'			: 'profile_removefriend',
				'fa'			: 'profiles',
				'action'		: 'profile_removeFriend',
				'pid'			: $('pid').value
			};	 
			break;
		case 'profile_fan':
			params = {
//				'fa'			: 'profile_fan',
				'fa'			: 'profiles',
				'action'		: 'profile_fan',
				'pid'			: $('pid').value,
				'fid'			: $('fid').value
			};	 
			break;
		case 'remove_member':
			params = {
//				'fa'			: 'profile_fan',
				'fa'			: 'teams',
				'action'		: 'remove_member',
				'mid'			: $('mid').value,
				'tid'			: $('tid').value,
				'mname'			: $('mname').value
			};	 
			break;
		case 'leave_team':
			params = {
//				'fa'			: 'profile_fan',
				'fa'			: 'teams',
				'action'		: 'leave_team',
				'tid'			: $('tid').value
			};	 
			break;
		case 'choose_account_type':
			params = {
//				'fa'			: 'choose_account_type',
				'fa'			: 'profiles',
				'action'		: 'profile_setType',
				'player'		: $('player').checked,
				'coach'			: $('coach').checked,
				'referee'		: $('referee').checked,
				'fan'			: $('fan').checked
			};	 
			break;
		case 'team_fan':
			params = {
				//'fa'			: 'team_fan',
				'fa'			: 'teams',
				'action'		: 'team_fan',
				'tid'			: $('tid').value,
				'tname'			: $('tname').value
			};	 
			break;
		case 'game_fan':
			params = {
				'fa'			: 'games',
				'action'		: 'game_fan',
				'eid'			: $('eid').value,
				'ename'			: $('ename').value
			};	 
			break;
		case 'invite_to_gameS':
			params = {
				'fa'			: 'games',
				'action'		: 'invite_to_gameS',
				'eid'			: $('eid').value,
				'uid'			: $('uid').value
			};	 
			break;
		case 'invite_to_teamS':
			params = {
				'fa'			: 'teams',
				'action'		: 'invite_to_teamS',
				'tid'			: $('tid').value,
				'uid'			: $('uid').value
			};	 
			break;
		case 'invite_to_team':
			params = {
				'fa'			: 'invite_to_team',
				'friends'			: friendsSelectedIds
			};	 
			break;
		case 'invite_to_game_team_fan':
			params = {
				'fa'			: 'teams',
				'action'		: 'invite_to_game_team_fan',
				'tid'			: $('tid').value,
				'eid'			: $('eid').value,
				'uid'			: $('uid').value
			};	 
			break;
		case 'goal_stats_team':
			params = {
				'fa'			: 'teams',
				'action'		: 'goal_stats_team',
				'tid'			: $('tid').value,
				'val'			: $('val').value,
				'mid'			: $('mid').value
			};	 
			break;
		case 'assist_stats_team':
			params = {
				'fa'			: 'teams',
				'action'		: 'assist_stats_team',
				'tid'			: $('tid').value,
				'val'			: $('val').value,
				'mid'			: $('mid').value
			};	 
			break;
		case 'save_stats_team':
			params = {
				'fa'			: 'teams',
				'action'		: 'save_stats_team',
				'val'			: $('val').value,
				'tid'			: $('tid').value,
				'mid'			: $('mid').value
			};	 
			break;
		case 'goal_stats_game':
			params = {
				'fa'			: 'games',
				'action'		: 'goal_stats_game',
				'eid'			: $('eid').value,
				'val'			: $('val').value,
				'mid'			: $('mid').value
			};	 
			break;
		case 'assist_stats_game':
			params = {
				'fa'			: 'games',
				'action'		: 'assist_stats_game',
				'eid'			: $('eid').value,
				'val'			: $('val').value,
				'mid'			: $('mid').value
			};	 
			break;
		case 'save_stats_game':
			params = {
				'fa'			: 'games',
				'action'		: 'save_stats_game',
				'eid'			: $('eid').value,
				'val'			: $('val').value,
				'mid'			: $('mid').value
			};	 
			break;
		case 'view_complete_schedule':
			params = {
				'fa'			: 'teams',
				'action'		: 'view_complete_schedule'
			};	 
			break;
		case 'manage_team':
			params = {
				'fa'			: 'teams',
				'action'		: 'manage_team'
			};	 
			break;
		case 'modify_schedule':
			params = {
				'fa'			: 'teams',
				'action'		: 'save_schedule_team',
				'tid'	: $('tid').value,
				'eventType1'	: $('eventType1').value,
				'eventMonth1'	: $('eventMonth1').value,
				'eventDay1'	: $('eventDay1').value,
				'eventHour1'	: $('eventHour1').value,
				'eventMinute1'	: $('eventMinute1').value,
				'eventMeridian1'	: $('eventMeridian1').value,
				'eventTimeZone1'	: $('eventTimeZone1').value,
				'eventLocation1'	: $('eventLocation1').value,
				'eventType2'	: $('eventType2').value,
				'eventMonth2'	: $('eventMonth2').value,
				'eventDay2'	: $('eventDay2').value,
				'eventHour2'	: $('eventHour2').value,
				'eventMinute2'	: $('eventMinute2').value,
				'eventMeridian2'	: $('eventMeridian2').value,
				'eventTimeZone2'	: $('eventTimeZone2').value,
				'eventLocation2'	: $('eventLocation2').value,
				'eventType3'	: $('eventType3').value,
				'eventMonth3'	: $('eventMonth3').value,
				'eventDay3'	: $('eventDay3').value,
				'eventHour3'	: $('eventHour3').value,
				'eventMinute3'	: $('eventMinute3').value,
				'eventMeridian3'	: $('eventMeridian3').value,
				'eventTimeZone3'	: $('eventTimeZone3').value,
				'eventLocation3'	: $('eventLocation3').value,
				'eventType4'	: $('eventType4').value,
				'eventMonth4'	: $('eventMonth4').value,
				'eventDay4'	: $('eventDay4').value,
				'eventHour4'	: $('eventHour4').value,
				'eventMinute4'	: $('eventMinute4').value,
				'eventMeridian4'	: $('eventMeridian4').value,
				'eventTimeZone4'	: $('eventTimeZone4').value,
				'eventLocation4'	: $('eventLocation4').value,
				'private1'	: $('private1').checked,
				'private2'	: $('private2').checked,
				'private3'	: $('private3').checked,
				'private4'	: $('private4').checked
			};	 
			break;
		case 'load_content':
			params = {
				'fa'		: 'notifications',
				'action'	: 'load',
				'id'		: $('notification_id').value
			};
			break;
	}
	return params;
}

// for validating forms
function validate(form_type){
	var errors = '';//new Array();
	
	switch(form_type){
		case 'create_game':
			if(trim($('name').value) == '') errors += 'Name is required.<br>';
			if(trim($('host_text').value) == '' && $('host_select').value == 0) errors += 'Host is required.<br>';
			if($('category').value == '') errors += 'Main Type is required.<br>';
			if($('subcategory').value == '') errors += 'Sub Type is required.<br>';
			if($('description').value == '') errors += 'Description is required.<br>';
			
			
			var start_month = parseInt($('start_month').value, 10);
			var start_day = parseInt($('start_day').value, 10);
			var start_year = parseInt($('start_year').value, 10);
			var start_hour = parseInt($('start_hour').value, 10);
			var start_minute = parseInt($('start_minute').value, 10);
			var start_meridian = $('start_meridian').value;
			var end_month = parseInt($('end_month').value, 10);
			var end_day = parseInt($('end_day').value, 10);
			var end_year = parseInt($('end_year').value, 10);
			var end_hour = parseInt($('end_hour').value, 10);
			var end_minute = parseInt($('end_minute').value, 10);
			var end_meridian = $('end_meridian').value;
			
			if(start_meridian == 'pm' && start_hour < 12){
				start_hour += 12;
			}else if (start_meridian == 'am' && start_hour == 12){
				start_hour = 00;
			}

			if(end_meridian == 'pm' && end_hour < 12){
				end_hour += 12;
			}else if (end_meridian == 'am' && end_hour == 12){
				end_hour = 00;
			}
			
			var start_time = mktime(start_hour, start_minute, 0, start_month, start_day, start_year);
			var end_time = mktime(end_hour, end_minute, 0, end_month, end_day, end_year);
			
			var month_diff = end_month - start_month;
			if(month_diff < 0) month_diff += 12;
			
			if(start_time >= end_time) errors += 'End Time should be later than the Start Time.<br>';
			else if((month_diff) > 4) {
				errors += 'Duration of the game should be within 4 months only.<br>';
			}else if((month_diff) == 4){
				if (end_day > start_day) {
					errors += 'Duration of the game should be within 4 months only.<br>';
				}
			}
			
			if($('agegroup').value == '') errors += 'Age Group is required.<br>';
			if($('gender').value == '') errors += 'Gender is required.<br>';
			
			if($('min_needed').value == null || $('min_needed').value == '') $('min_needed').value = 0; 
			else if(!$('min_needed').value.toString().match(/^\d+$/)) errors += 'Minimum players needed must be a positive whole number.<br>';
			else if($('min_needed').value > $('size').value*2) errors += 'Minimum players needed exceeded the total number of players.<br>';
			
			if($('location').value == '') errors += 'Location is required.<br>';
			//console.log('start year: %i || end year: %i', start_year, end_year);
			//console.log('difference in months: %i', month_diff);
			if(trim($('city').value) == '') errors += 'City/Town is required.<br>';
			break;	
		
		case 'join_game':
			if($('type_select').value == 'player' && $('position_select').value == '')
				errors += 'Please select your position.';
			if($('type_select').value == 'coach' && $('coachtype_select').value == '')
				errors += 'Please select your position.';
			break;
				
		case 'create_team':
			if(trim($('name').value) == '') errors += 'Name is required.<br>';
			if($('description').value == '') errors += 'Description is required.<br>';
			if($('category').value == '') errors += 'Game Type is required.<br>';
			if($('subcategory').value == '') errors += 'Sub category is required.<br>';
			if($('agegroup').value == '') errors += 'Age Group is required.<br>';
			if($('gender').value == '') errors += 'Gender is required.<br>';
			if(trim($('city').value) == '') errors += 'City/Town is required.<br>';
			if(trim($('state').value) == '') errors += 'State/Province is required.<br>';
			break;	
			
		case 'join_team':
			if($('type_select').value == 'player' && $('position_select').value == '')
				errors += 'Please select your position.';
			if($('type_select').value == 'coach' && $('coachtype_select').value == '')
				errors += 'Please select your position.';
			break;	
			
		case 'update_info': case 'choose_account_type':
			if($('fan').checked == false && $('player').checked == false && $('coach').checked == false && $('referee').checked == false){
				errors += 'You must select at least one type.<br>';
			}
			try{
				if(trim($('city').value) == '') errors += 'City/Town is required.<br>';
				if(trim($('state').value) == '') errors += 'State/Province is required.<br>';	
				if(trim($('country').value) == '') errors += 'Country is required.<br>';	
				if(trim($('timezone').value) == '') errors += 'Timezone is required.<br>';	
			}catch(e){}
			break;
		case 'update_info2': case 'choose_account_type':
			if($('fan').checked == false && $('player').checked == false && $('coach').checked == false && $('referee').checked == false){
				errors += 'You must select at least one type.<br>';
			}
			try{
				if(trim($('city').value) == '') errors += 'City/Town is required.<br>';
				if(trim($('state').value) == '') errors += 'State/Province is required.<br>';	
				if(trim($('country').value) == '') errors += 'Country is required.<br>';
				if(trim($('timezone').value) == '') errors += 'Timezone is required.<br>';
			}catch(e){}
			break;
	}
	
	//console.log(errors);
	return errors;
}


// for updating divs
function update_div(form_type,params,response){
	switch(form_type){
		case 'goal_stats_game':
			if(response!='')
				$('statistics').innerHTML = response;
			break;
		case 'assist_stats_game':
			if(response!='')
				$('statistics').innerHTML = response;
			break;
		case 'save_stats_game':
			if(response!='')	
				$('statistics').innerHTML = response;
			break;
		case 'goal_stats_team':
			if(response!='')
				$('statistics').innerHTML = response;
			break;
		case 'assist_stats_team':
			if(response!='')	
				$('statistics').innerHTML = response;
			break;
		case 'save_stats_team':
			if(response!='')	
				$('statistics').innerHTML = response;
			break;
		case 'leave_team':
			window.location.reload(true);
			break;
		case 'edit_team':
			window.location.reload(true);
			break;
		case 'remove_member':
			window.location.reload(true);
			break;
		case 'create_game':
			//$('games_list').innerHTML = response;
			var template_data = {
				"name" : params['name'],
				"location" : params['location'],
				"eid" : response,
				"type" : "Game",
				"description": params['description']
			}
			var continuation = function() { 
			   //window.location.reload(true);
			   window.location = params['domain']+"?p=gameinfo&eid="+response+'&auto_join=1';
			   //show_form('Join Game', 'join_game', 'Join Now!', 'Maybe Later', response);
			};
			showFeedDialog("created_game",template_data,continuation);
			//FB.Connect.showFeedDialog(77642234930,template_data,undefined,undefined, null, FB.RequireConnect.promptConnect, continuation);
			break;
		case 'join_game':
			var template_data = {
				"type" : "Game",
				"name" : params['game_name'],
				"page" : "?p=gameinfo&eid="+params['game_id'],
				"user_type" : params['position']
			}
			var continuation = function() { 
				window.location.reload(true);
			};
			showFeedDialog("joined_game_team",template_data,continuation);
			
			//alert('the screen should reload');
			//window.location.reload(true);
			break;	
		case 'create_team':
			//$('teams_list').innerHTML = response;
			//window.location.reload(true);
			 var template_data = {
				"name" : params['name'],
				"tid" : response,
				"type" : "Team",
				"description": params['description']
			}
			var continuation = function() { 
				//location.reload(true);
				window.location = params['domain']+"?p=teaminfo&tid="+response+"&auto_join=1";
			};
			showFeedDialog("created_team",template_data,continuation);
			//FB.Connect.showFeedDialog(77640994930,template_data,undefined,undefined, null, FB.RequireConnect.promptConnect, continuation);
			break;
		case 'join_team':
			var template_data = {
				"type" : "Team",
				"name" : params['team_name'],
				"page" : "?p=teaminfo&tid="+params['team_id'],
				"user_type" : params['position']
			}
			var continuation = function() { 
				window.location.reload(true);
			};
			showFeedDialog("joined_game_team",template_data,continuation);
			
			//alert('the screen should reload');
			//window.location.reload(true);
			break;		
		case 'update_info2':
			//window.location="?p=default";
			break;
		case 'update_info': 
			// place update here
			/*var desc=new Array('','','','','','Height','Weight','Skill Level','Left/Right footed','Position','Favorite teams','Favorite brand','Favorite move','Favorite players','Teams i would like to play for in the future','Other favorite sports');
			str="";
			j=0;
			for ( var i in params)
			{   if(params[i]!="" && j>4){
					str+='<div style="margin-top:10px;"><div class="grey bold">'
					str+=desc[j] +':</div><div>'+ params[i]+'</div></div>';
			  	}	 
			  	j++;
		    }*/
		    //$("infoProfile").innerHTML=response;
			break;
			//window.location.reload(true);
		case 'choose_account_type':
			window.location.reload(true);
			break;
		case 'modify_schedule':
			location.reload(true);
			break;
		case 'profile_fan': 
			// place update here
		    var template_data = {
				"target_fbid" : params['fid']
			}
			showFeedDialog("fan_of_user",template_data);
			//FB.Connect.showFeedDialog(75403244930,template_data);
			//$("fansDiv").innerHTML=response;
			location.reload(true);
		    $("beafan").style.display='none';
			break;
		case 'profile_addfriend': 
			// place update here
		    var template_data = {
				"target_fbid" : params['fbpid']
			}
			var continuation = function() { 
				location.reload(true);
			};
			showFeedDialog("friend_request",template_data,continuation);
			//FB.Connect.showFeedDialog(77911319930,template_data,undefined,undefined, null, FB.RequireConnect.promptConnect, continuation);
			break;
		case 'profile_removefriend': 
			location.reload(true);
			break;
		case 'team_fan': 
			// place update here
		    var template_data = {
				"name" : params['tname'],
				"type" : "Team",
				"url" : "teaminfo&tid="+params['tid']
			}
			showFeedDialog("fan_of_game_team",template_data);
			//FB.Connect.showFeedDialog(77620879930,template_data);
			try{
				$("fansDiv").innerHTML=response;
				$("beafan").style.display='none';
			}
			catch(e){
				window.location.reload(true);
			}
		    break;
		case 'game_fan': 
			// place update here
		    var template_data = {
				"name" : params['ename'],
				"type" : "Game",
				"url" : "gameinfo&eid="+params['eid']
			}
			showFeedDialog("fan_of_game_team",template_data);
			//FB.Connect.showFeedDialog(77620879930,template_data);
			try{
				$("fansDiv").innerHTML=response;
				$("beafan").style.display='none';
			}
		    catch(e){
		    	window.location.reload(true);
		    }
		    
			break;
		case 'profileComment':
			$('profileComment').style.display="block";
			$('profileGame').style.display="none";
			$('profileTeam').style.display="none";
			$('profileInformation').style.display="none";
			break;
		case 'profileGame':
			$('profileComment').style.display="none";
			$('profileGame').style.display="block";
			$('profileTeam').style.display="none";
			$('profileInformation').style.display="none";
			break;
		case 'profileTeam':
			$('profileComment').style.display="none";
			$('profileGame').style.display="none";
			$('profileTeam').style.display="block";
			$('profileInformation').style.display="none";
			break;
		case 'profileInformation':
			$('profileComment').style.display="none";
			$('profileGame').style.display="none";
			$('profileTeam').style.display="none";
			$('profileInformation').style.display="block";
			break;
		case 'searchFan':
			$('searchPlayer').innerHTML='';
			$('searchCoach').innerHTML='';
			$('searchReferee').innerHTML='';
			$('searchTeam').innerHTML='';
			break;
		case 'searchPlayer':
			$('searchFan').innerHTML='';
			$('searchCoach').innerHTML='';
			$('searchReferee').innerHTML='';
			$('searchTeam').innerHTML='';
			break;
		case 'searchCoach':
			$('searchFan').innerHTML='';
			$('searchPlayer').innerHTML='';
			$('searchReferee').innerHTML='';
			$('searchTeam').innerHTML='';
			break;
		case 'searchReferee':
			$('searchFan').innerHTML='';
			$('searchPlayer').innerHTML='';
			$('searchCoach').innerHTML='';
			$('searchTeam').innerHTML='';
			break;
		case 'searchTeam':
			$('searchFan').innerHTML='';
			$('searchPlayer').innerHTML='';
			$('searchCoach').innerHTML='';
			$('searchReferee').innerHTML='';
			break;
		case 'inviteFriends':
			$('inviteFriends').style.display="block";
			$('inviteOthers').style.display="none";
			$('teamJoinRequests').style.display="none";
			break;
		case 'inviteOthers':
			$('inviteFriends').style.display="none";
			$('inviteOthers').style.display="block";
			$('teamJoinRequests').style.display="none";
			break;
		case 'teamJoinRequests':
			$('inviteFriends').style.display="none";
			$('inviteOthers').style.display="none";
			$('teamJoinRequests').style.display="block";
			break;
		case 'playersDiv':
			$('playersDiv').style.display="block";
			$('coachesDiv').style.display="none";
			break;
		case 'coachesDiv':
			$('playersDiv').style.display="none";
			$('coachesDiv').style.display="block";
			break;
		case 'load_content':	
			document.location="?p=notifications&section=notification_email&action=compose&load="+params['id'];
			break;		
		}
}

function tg(id){
	pre = document.getElementById(id);
	if(pre.style.display == 'block')
		pre.style.display='none';
	else 
		pre.style.display='block';
}

function jsTabs(id){
	$('1').className='';
	$('2').className='';
	pre = document.getElementById(id);
	if(pre.className == '')
		pre.className='selected';
}

function jsTabs2(id){
	$('1').className='';
	$('2').className='';
	$('3').className='';
	$('4').className='';
	$('5').className='';
	pre = document.getElementById(id);
	if(pre.className == '')
		pre.className='selected';
}
function jsTabs3(id){
	$('s1').className='';
	$('s2').className='';
	pre = document.getElementById(id);
	if(pre.className == '')
		pre.className='selected';
}
function jsTabs4(id){
	$('s1').className='';
	$('s2').className='';
	$('s3').className='';
	pre = document.getElementById(id);
	if(pre.className == '')
		pre.className='selected';
}

// for validation use functions
function date_month_change(obj, target_obj){
	var stamp = new Date(); 
	var month = obj.value;
	var year = stamp.getFullYear();
	var curr_month = stamp.getMonth() + 1;
	
	var start_month = parseInt($('start_month').value, 10);
	var end_month   = parseInt($('end_month').value, 10);
//	console.log('start month is: %i', start_month);
//	console.log('end month is: %i', end_month);	
	
	if(start_month < curr_month && end_month <= curr_month){
		$('start_year').value = year + 1;
		$('end_year').value = year + 1;
//		console.log('start year is: %i', year + 1);
//		console.log('end year is: %i', year + 1);
	}else{
		if(start_month > end_month){
	 		year += 1; 
	 		$('end_year').value = year;
//	 		console.log('start year is: %i', year);
// 			console.log('end year is: %i', year);
		}else{
			$('end_year').value = year;
//			console.log('start year is: %i', year);
//	 		console.log('end year is: %i', year);
		}
	}
	
	switch(month){
		case '01': //January
		case '03': //March
		case '05': //May
		case '07': //July
		case '08': //August
		case '10': //October
		case '12': //December
			if(target_obj.options.length != 31){ 				
				while(target_obj.options.length < 31){
					var num = target_obj.options.length + 1;
					var opt = document.createElement('option');
					opt.text = num;
					opt.value = num;
					//target_obj.add(opt);
					try{
						target_obj.add(opt, null); // standards compliant
					}catch(ex){
						target_obj.add(opt); // IE only
					}
				}
			}
			break;
		case '04': //April
		case '06': //June
		case '09': //September
		case '11': //October
			if(target_obj.options.length < 30){ 				
				while(target_obj.options.length < 30){
					var num = target_obj.options.length + 1;
					var opt = document.createElement('option');
					opt.text = num;
					opt.value = num;
					target_obj.add(opt);
				}
			}else if(target_obj.options.length > 30){
				target_obj.remove(30) // remove 31
			}
			break;
		default:   //February
			var low = 0;
			if(year % 4 == 0) low = 29;
			else low = 28;
			
			var i = target_obj.options.length - 1; 	
			
			while(target_obj.options.length > low){
				target_obj.options[i]=null;
				i--;
			}
	}
	
}

// joining teams
function join_team(team_id, team_name, type, game_id, game_name, is_type, of_team_id, of_team_name){
	var message = '';
	var params = '';
	if(arguments[8]) invited=1;else invited=0;
	if(!game_id && !game_name){ // joining on a team
		//message  = '<p>Do you want to join ' + team_name + '?</p>';
		
		message = '<div style="padding:10px;">';
		message += '	<div id="select_type">';
		message += '		<div style="width:110px;display:inline-table;"">Join the team as:</div>';
		message += '		<div style="display:inline">';
		message += '			<select id="type_select" style="margin-left:10px;" onchange="check_type();">';
		message += '    			<option id="type_player" value="player">Player</option>';
		message += '    			<option id="type_coach" value="coach">Coach</option>';
		message += '  			</select>';
		message += '		</div>';
		message += '	</div>';
		message += '	<div id="select_position" style="margin-top:10px">';
		message += '		<div style="width:120px;display:inline-table;">Your Position:</div> ';
		message += '		<div style="display:inline">';
		message += '			<select id="position_select" style="width:180px;">';
		message += '    			<option value="">Select Position:</option>';
		message += '    			<option value="Forward">Forward</option>';
		message += '    			<option value="Midfield">Midfield</option>';
		message += '    			<option value="Wing Midfield">Wing Midfield</option>';
		message += '    			<option value="Center Midfield">Center Midfield</option>';
		message += '    			<option value="Defender">Defender</option>';
		message += '    			<option value="Sweeper">Sweeper</option>';
		message += '   		 		<option value="Stopper">Stopper</option>';
		message += '    			<option value="Goal Keeper">Goal Keeper</option>';
		message += '  			</select>';
		message += '		</div>';
		message += '	</div>';
		message += '	<div id="select_coachtype" style="margin-top:10px;display:none">';
		message += '		<div style="width:120px;display:inline-table;">Your Position:</div> ';
		message += '		<div style="display:inline">';
		message += '			<select id="coachtype_select" style="width:180px;">';
		message += '    			<option value="">Select Position:</option>';
		message += '    			<option value="Head Coach">Head Coach</option>';
		message += '    			<option value="Assistant Coach">Assistant Coach</option>';
		message += '    			<option value="Goal Keeper Coach">Goal Keeper Coach</option>';
		message += '  			</select>';
		message += '		</div>';
		message += '	</div>';
		message += '	<div id="input_jersey" style="margin-top:10px;">';
		message += '		<div style="width:120px;display:inline-table;">Jersey Number:</div> ';
		message += '		<div style="display:inline">';
		message += '			<input id="jerseyNumber" type="text" maxlength="3" style="width:200px;">';
		message += '		</div>';
		message += '	</div>';
		message += '</div>';
		
	}else{ //joining on a game
		if(is_type != type){
			if(type == 'player')
				message = 'Are you sure you want to join the ' + team_name + ' to play ' + game_name + '?';
			else if(type == 'coach')
				message = 'Are you sure you want to coach for the ' + team_name + ' to play ' + game_name + '?';
		}else{
			if(type == 'player'){
				if(team_id != of_team_id){
					message = 'You already joined for the ' + of_team_name + '! Do you want to play for the ' + team_name + ' instead?';
				}else{
					message = 'You are already playing for the ' + team_name + '. Or do you want to change position?';
				}
			}else if(type == 'coach'){
				if(team_id != of_team_id){
					message = 'You\'re already a coach for the ' + of_team_name + '! Do you want to coach for the ' + team_name + ' instead?';
				}else{
					message = 'You are already coaching for the ' + team_name + '. Or do you want to change position?';
				}
			}
		}
		
		message += '<table>';
		if(!game_id && !game_name){
			message += '<tr><td width="100px"><b>Your Position:</b><br><small style="color:#a7a09d">(required)</small></td><td>';
		}else{
			message += '<tr><td width="100px"><b>Your Position:</b></td><td>';
		}
		
		message += '<select id="position" name="position" style="width:145px;">';
		if(type == 'player'){	
			message += '    <option value="">Select Position:</option>';
			message += '    <option value="Forward">Forward</option>';
			message += '    <option value="Midfield">Midfield</option>';
			message += '    <option value="Wing Midfield">Wing Midfield</option>';
			message += '    <option value="Center Midfield">Center Midfield</option>';
			message += '    <option value="Defender">Defender</option>';
			message += '    <option value="Sweeper">Sweeper</option>';
			message += '    <option value="Stopper">Stopper</option>';
			message += '    <option value="Goal Keeper">Goal Keeper</option>';
		}else if(type == 'coach'){
			message += '    <option value="">Select Position:</option>';
			message += '    <option value="Head Coach">Head Coach</option>';
			message += '    <option value="Assistant Coach">Assistant Coach</option>';
			message += '    <option value="Goal Keeper Coach">Goal Keeper Coach</option>';
		}
			message += '  </select></td></tr>';
		if(!game_id && !game_name && type == 'player'){
			message += '<tr><td width="100px"><b>Jersey Number:</b></td><Td><input id="jerseyNumber" type="text" style="width:300px;"></td></tr>';
		}
		message += '</table>';
	}
	
		
	
	var d = new Dialog(1, 'confirm');
	//if(is_player == null || (is_player != null && team_id != of_team_id)){
		var ok_btn = '';
		//alert('is_type: '+is_type+'\ntype: '+type+'\nof_team_id: '+of_team_id+'\nteam_id: '+team_id);
		
		if(is_type == undefined && of_team_id == undefined) ok_btn = 'Join Now!';
		else if(is_type != type && team_id != of_team_id) ok_btn = 'Switch Team!';
		else if(is_type == type && team_id != of_team_id) ok_btn = 'Switch Team!';
		else if(is_type != type && team_id == of_team_id) ok_btn = 'Change Position!';
		else if(is_type == type && team_id == of_team_id) ok_btn = 'Change Position!';
		 
		d.showChoice('Join Team Confirmation', message, ok_btn, 'Maybe later');
		d.onconfirm = function(){
			if(!game_id && !game_name){		// join team
				//validation
				var jerseyNum = $('jerseyNumber').value;
				if(($('type_select').value == 'player' && $('position_select').value == '') || ($('type_select').value == 'coach' && $('coachtype_select').value == '')){
					var e = new Dialog(1, 'error').showMessage('Error', 'You must choose your position.', 'Close');
					e.onconfirm = function(){
						e.destroy();
					}
				}else if(jerseyNum.length > 0 && is_numeric(jerseyNum) == false){
					var e = new Dialog(1, 'error').showMessage('Error', 'Invalid Jersey Number.', 'Close');
					e.onconfirm = function(){
						e.destroy();
					}
				}else{
					var position = '';
					if($('type_select').value == 'player'){
						position = $('position_select').value;
					}else if($('type_select').value == 'coach'){
						position = $('coachtype_select').value;
					}
					
					params = {
					'fa':'teams', 
					'action':'join_team', 
					'team_id':team_id,
					'type':$('type_select').value,
					'position': position,
					'jerseyNum': $('jerseyNumber').value,
					'invited': invited
					};
					new Ajax.Request('index.php',{
						method:'post',
						parameters: params,
						onSuccess: function(transport){
							d.destroy();
							
							var template_data = {
								"type" : "Team",
								"name" : team_name,
								"page" : "?p=teaminfo&tid="+team_id,
								"user_type" : position
							}
							var continuation = function() { 
							   window.location.reload(true);
							};
							//showFeedDialog("joined_game_team",template_data,continuation);
							//FB.Connect.showFeedDialog(77652719930,template_data,undefined,undefined, null, FB.RequireConnect.promptConnect, continuation);
							
							// show popup
							var txt = 'Your request to join <b>' + team_name + '</b> has been sent to the team administrator for approval.';
							var d2 = new Dialog(1, 'Join Team').showMessage('Join Team', txt, 'OK.');
							d2.onconfirm = function(){d2.destroy();window.location.reload(true);}
						},
						onFailure: function(){}
					});
					
				}
			}else{				// join game
				if($('position').value == ''){
					var e = new Dialog(1, 'error').showMessage('Error', 'You must choose your position.', 'Close');
					e.onconfirm = function(){
						e.destroy();
					}
				}else{
					params = {
					'fa':'games', 
					'action':'join_game', 
					'team_id':team_id,
					'game_id':game_id,
					'type':type,
					'position': $('position').value,
					'invited': invited
					};
					new Ajax.Request('index.php',{
						method:'post',
						parameters: params,
						onSuccess: function(transport){
							d.destroy();
							var template_data = {
								"type" : "Game",
								"name" : game_name,
								"page" : "?p=gameinfo&eid="+game_id,
								"user_type" : params['position']
							}
							var continuation = function() { 
							   window.location.reload(true);
							};
							showFeedDialog("joined_game_team",template_data,continuation);
							//FB.Connect.showFeedDialog(77652719930,template_data,undefined,undefined, null, FB.RequireConnect.promptConnect, continuation);
						},
						onFailure: function(){}
					});
				}
			}
		}
	//}else{
	//	d.showMessage('Join Team Confirmation', message,'Close');
	//	d.onconfirm = function(){
	//		d.destroy();
	//	}
	//}
}

function set_rsvp(game_id, game_name, status){
	if(status == 'Playing'){
		edit_position(game_id, game_name);
	}else if(status == 'Not Playing' || status == 'Maybe Playing'){
		params = {
			'fa':'games', 
			'action':'set_rsvp',
			'game_id':game_id,
			'rsvp':status			
		};
			
		new Ajax.Request('index.php',{
			method:'post',
			parameters: params,
			onSuccess: function(transport){
				window.location.reload(true);
			},
			onFailure: function(){}
		});
	}
}

function join_game_as(game_id,game_name,type){
	var d = new Dialog(1,'confirmation').showChoice('Join Game Confirmation', 'Are you sure you want to join ' + game_name + ' as a ' + type + '?','Join Now!','Maybe Later');
	d.onconfirm = function(){
		params = {
			'fa':'games', 
			'action':'join_game', 
			'game_id':game_id,
			'type':type,
			'team_id': 0,
			'position': ''
			};
			
		new Ajax.Request('index.php',{
			method:'post',
			parameters: params,
			onSuccess: function(transport){
				d.destroy();
				var template_data = {
					"type" : "Game",
					"name" : game_name,
					"page" : "?p=gameinfo&eid="+game_id,
					"user_type" : type
				}
				var continuation = function() { 
				   window.location.reload(true);
				};
				showFeedDialog("joined_game_team",template_data,continuation);
				//FB.Connect.showFeedDialog(75388174930,template_data,undefined,undefined, null, FB.RequireConnect.promptConnect, continuation);
			},
			onFailure: function(){}
		});
	}
}

function edit_position(game_id,game_name){
	
	var content = ''; 

	content += '<div style="padding:10px;">';
	content += '	<div id="select_type">';
	content += '		<div style="width:110px;display:inline-table;"">Join the game as:</div>';
	content += '		<div style="display:inline">';
	content += '			<select id="type_select" style="margin-left:10px;" onchange="check_type();">';
	content += '    			<option id="type_player" value="player">Player</option>';
	content += '    			<option id="type_coach" value="coach">Coach</option>';
	content += '    			<option id="type_referee" value="referee">Referee</option>';
	content += '  			</select>';
	content += '			<select id="team_select" style="margin-left:10px;">';
	content += '    			<option id="team_home" value="1">Home Team</option>';
	content += '    			<option id="team_away" value="2">Away Team</option>';
	content += '  			</select>';
	content += '		</div>';
	content += '	</div>';
	content += '	<div id="select_position" style="margin-top:10px">';
	content += '		<div style="width:120px;display:inline-table;">Your Position:</div> ';
	content += '		<div style="display:inline">';
	content += '			<select id="position_select" style="width:180px;">';
	content += '    			<option value="">Select Position:</option>';
	content += '    			<option value="Forward">Forward</option>';
	content += '    			<option value="Midfield">Midfield</option>';
	content += '    			<option value="Wing Midfield">Wing Midfield</option>';
	content += '    			<option value="Center Midfield">Center Midfield</option>';
	content += '    			<option value="Defender">Defender</option>';
	content += '    			<option value="Sweeper">Sweeper</option>';
	content += '   		 		<option value="Stopper">Stopper</option>';
	content += '    			<option value="Goal Keeper">Goal Keeper</option>';
	content += '  			</select>';
	content += '		</div>';
	content += '	</div>';
	content += '	<div id="select_coachtype" style="margin-top:10px;display:none">';
	content += '		<div style="width:120px;display:inline-table;">Your Position:</div> ';
	content += '		<div style="display:inline">';
	content += '			<select id="coachtype_select" style="width:180px;">';
	content += '    			<option value="">Select Position:</option>';
	content += '    			<option value="Head Coach">Head Coach</option>';
	content += '    			<option value="Assistant Coach">Assistant Coach</option>';
	content += '    			<option value="Goal Keeper Coach">Goal Keeper Coach</option>';
	content += '  			</select>';
	content += '		</div>';
	content += '	</div>';
	content += '</div>';
	
	var d = new Dialog(1, 'edit_position').showChoice(' ', content, 'Submit', 'Cancel');
	d.onconfirm = function(){
		if(($('type_select').value == 'player' &&  $('position_select').value == '') || ($('type_select').value == 'coach' &&  $('coachtype_select').value == '')){
			var e = new Dialog(1, 'error').showMessage('Error', 'You must select a Position', 'Close');
			e.onconfirm = function(){ e.destroy(); };
		}else{
			var position = '';
			if($('type_select').value == 'player'){
				position = $('position_select').value;
			}else if($('type_select').value == 'coach'){
				position = $('coachtype_select').value;
			}
			
			params = {
				'fa'	   : 'games', 
				'action'   : 'join_game',
				'type'     : $('type_select').value, 
				'team_id'  : $('team_select').value,
				'position' : position,
				'game_id'  : game_id
			};
			
			if($('type_select').value == 'referee'){
				position = 'Referee';
			}
			
			new Ajax.Request('index.php',{
				method:'post',
				parameters: params,
				onSuccess: function(transport){
					response = transport.responseText;
					if(response != ''){
						var e = new Dialog(1, 'error').showMessage('Error', response, 'Close');
						e.onconfirm = function(){ e.destroy(); };
					}else{
					d.destroy();
					//window.location.reload(true);
					
					var template_data = {
						"type" : "Game",
						"name" : game_name,
						"page" : "?p=gameinfo&eid="+game_id,
						"user_type" : position
					}
					var continuation = function() { 
				 	  	window.location.reload(true);
					};
					showFeedDialog("joined_game_team",template_data,continuation);
					
					}
				},
				onFailure: function(){}
			});
		}
	}
}

function check_type(){
	if($('type_select').value == 'player'){
		$('select_position').style.display = 'block';
		$('select_coachtype').style.display = 'none';
		try{$('team_select').style.display = 'inline';}catch(e){}		
		try{
			$('input_jersey').style.display = 'block';
			$('input_jersey').value = '';
		}catch(e){} 
	}else if($('type_select').value == 'coach'){
		$('select_position').style.display = 'none';
		$('select_coachtype').style.display = 'block';
		try{$('team_select').style.display = 'inline';}catch(e){}
		try{
			$('input_jersey').style.display = 'none';
			$('input_jersey').value = '';
		}catch(e){} 
	}else if($('type_select').value == 'referee'){
		$('select_position').style.display = 'none';
		$('select_coachtype').style.display = 'none';
		try{$('team_select').style.display = 'none';}catch(e){}
		try{
			$('input_jersey').style.display = 'none';
			$('input_jersey').value = '';
		}catch(e){} 
	}
}

function showTypesForm(){
	show_form('Modify My Account Type', 'choose_account_type', 'Save', 'Cancel');	
}

function searchFocus(txtbox){
	if(txtbox.value=='Search')
		txtbox.value='';
}
function searchBlur(txtbox){
	if(txtbox.value=='')
		txtbox.value='Search';
}

function newEventForm(num){
	divName = 'eventForm'+num;
	$('eventForm'+num).style.display="block";
	$('newFormButton'+(num-1)).style.display="none";
}


function trim (str, charlist) {
    // Strips whitespace from the beginning and end of a string  
    // version: 905.1001
    // discuss at: http://phpjs.org/functions/trim
    // *     example 1: trim('    Kevin van Zonneveld    ');
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: trim('Hello World', 'Hdle');
    // *     returns 2: 'o Wor'
    // *     example 3: trim(16, 1);
    // *     returns 3: 6
    var whitespace, l = 0, i = 0;
    str += '';
    
    if (!charlist) {
        // default list
        whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
    } else {
        // preg_quote custom list
        charlist += '';
        whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
    }
    
    l = str.length;
    for (i = 0; i < l; i++) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(i);
            break;
        }
    }
    
    l = str.length;
    for (i = l - 1; i >= 0; i--) {
        if (whitespace.indexOf(str.charAt(i)) === -1) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    
    return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
}

function is_numeric( mixed_var ) {
    // Returns true if value is a number or a numeric string  
    // version: 904.317
    // discuss at: http://phpjs.org/functions/is_numeric
    // *     example 1: is_numeric(186.31);
    // *     returns 1: true
    // *     example 2: is_numeric('Kevin van Zonneveld');
    // *     returns 2: false
    // *     example 3: is_numeric('+186.31e2');
    // *     returns 3: true
    // *     example 4: is_numeric('');
    // *     returns 4: false
    if (mixed_var === '') {
        return false;
    }

    return !isNaN(mixed_var * 1);
}


// for checking if image exist
//function checkImage(url,type){
//	//type are: pic_square, pic_big, team_sm, team_pic, team_big
//	
//	var img, xmlrequest;
//	img = document.getElementById('image');
//
//	if(window.XMLHttpRequest){
//		xmlrequest = XMLHttpRequest();
//	}else if(window.ActiveXObject){
//		xmlrequest = ActiveXObject('Microsoft.XMLHTTP');
//	}
//
//	xmlrequest.onreadystatechange = function(){
//		if(xmlrequest.readyState == 4){
//			if(xmlrequest.status == 200){
//				img.style.display = 'block';
//				img.src = url;
//			}else{
//				if(type == 'pic_square')img.src = 'images/default_sm.gif';
//				if(type == 'pic_big')   img.src = 'images/default_mx.gif';
//				if(type == 'team_sm')   img.src = 'images/t_sampleteam.gif';
//				if(type == 'team_pic')  img.src = 'images/s_sampleteam.gif';
//				if(type == 'team_big')  img.src = 'images/sampleteam.gif';
//				img.style.display = 'block';
//			}
//		}
//	};
//}




/////////-------------------------------------------------------------------------------

var Feed = {};

Feed.check = function(textarea, ontype){
	var message = textarea.value;
	
	if(ontype == 'onfocus'){
		if(trim(message) == textarea.title){
			textarea.value = '';
		}
	}else if(ontype == 'onblur'){
		if(trim(message) == ''){
			textarea.value = textarea.title;
		}
	}
}

Feed.checkPost = function(form){
	var publish_to_fb = 0;
	var error = 0;
	try{
		if($('send_to_members').checked && $('send_to_fans').checked)
			publish_to_fb = 1;
		else if(!$('send_to_members').checked && !$('send_to_fans').checked){
			alert('One of the checkboxes must be checked!');
			error = 1;	
		}
	}catch(e){
		try{
			if($('post_to_facebook').checked)
				publish_to_fb = 1;
		}catch(e){
			publish_to_fb = 0;
		}
	}
	
	if(!error){
		if(publish_to_fb == 1){
			checkExtendedPerms('publish_stream', 'Feed.post', form);
		}else{
			Feed.post(form);
		}
	}
}

Feed.post = function(form){
	var params = $(form).serialize(true);
	
	var textarea = $('wall_comment');
	$('loading_page').style.display = 'block';//show();
	
	params['ajax'] = 'feeds';
	params['action'] = 'Feeds.post';
	params['message'] = $(textarea).value;
	params['type'] = $('post_type').value;
	params['page'] = $('curr_page').value;
	params['page_id'] = $('curr_page_id').value;
	params['xid'] = $('xid').value;
	params['curr_title'] = $('curr_title').value;
	params['url'] = $('url').value;
	
	var t_change = $(textarea).readAttribute('title');
	var t_val = $(textarea).value;
	
	if(t_val=='' || t_val==' ' || t_val==t_change){
		//alert('return false');
		return false;
	}
	


	new Ajax.Request('index.php',
	{
		method:'post',
		parameters: params,
		onSuccess: function(transport){
			$j(textarea).attr('value','Write a comment...');
			textarea.blur();
			
			$('feeds_container').innerHTML = transport.responseText;
			$('loading_page').hide();

			loadTextChange();
		},
		onFailure: function(){}
	});
	
}
//Comment.del = function(comment_id, type){
//	var params = data;
//	params['ajax'] = 'comments';
//	params['action'] = 'Comments.del';
//	params['comment_id'] = comment_id;
//	
//	try{
//		params['page'] = $('curr_page').value;
//		params['page_id'] = $('curr_page_id').value;
//	}catch(e){}
//	
//	new Ajax.Request('index.php',
//	{
//		method:'post',
//		parameters: params,
//		onSuccess: function(transport){
//			$('feeds_container').innerHTML = transport.responseText;
//
////			$('comments_'+params['identifier_id']).innerHTML = transport.responseText;
//			loadTextChange();
//		},
//		onFailure: function(){}
//	});
//}
//Comment.limitText = function(obj,limit,spanID){
//	if(obj.value.length > limit){
//		obj.value=obj.value.substring(0,limit);
//	}
//	$(spanID).innerHTML = limit-obj.value.length;
//}
//
//var Comments = {};
//
//Comments.showAllComments = function(){
//	var mc = $j('.tg_friend');
//	var mcl = mc.length;
//	var i;
//	var mci;
//	for(i=0;i<mcl;i++){
//		mci = $j(mc[i]);
//		if(mci.hasClass('all_comments_flag')){
//			mci.show();
//		}else{
//			mci.hide();
//		}
//	}
//}







var Comment = {};
Comment.activate = function(feed_id){
	$('comment_for_'+feed_id).show();
	$('add_comment_text_'+feed_id).focus();

}

Comment.check = function(textarea, ontype, feed_id, action){
	var comment = textarea.value;
	
	if(ontype == 'onfocus'){
		if(trim(comment) == textarea.title){
			textarea.value = '';
			$("comments_add_box_submit_"+feed_id).show();

		}
	}else if(ontype == 'onblur'){
		if(trim(comment) == ''){
			textarea.value = textarea.title;
			if(action == 'hide')
				$('comment_for_'+feed_id).hide();
			else{
				$("comments_add_box_submit_"+feed_id).hide();
			}
		}
	}
}

Comment.checkPost = function(form, feed_id){
	var publish_to_fb = 0;
	
	try{
		if($('comment_post_to_facebook').checked)
			publish_to_fb = 1;
	}catch(e){
		publish_to_fb = 0;
	}
	
	if(publish_to_fb == 1){
		checkExtendedPerms('publish_stream', 'Comment.post', form, feed_id);
	}else{
		Comment.post(form, feed_id);
	}
}

Comment.post = function(form, feed_id){
	var params = $(form).serialize(true);
	var textarea = $('add_comment_text_'+feed_id);
	
	params['ajax'] = 'comments';
	params['action'] = 'Comments.post';
	params['comment'] = $(textarea).value;
	
	params['id'] = feed_id;	
	//params['page'] = $('curr_page').value;
	//params['page_id'] = $('curr_page_id').value;
	
//	alert('feed id: '+params['id']);
//	alert('page: '+params['page']);
//	alert('page id: '+params['page_id']);
	
	var t_change = $(textarea).readAttribute('title');
	var t_val = $(textarea).value;
	
	if(t_val=='' || t_val==' ' || t_val==t_change){
		//alert('return false');
		return false;
	}
	
	new Ajax.Request('index.php',
	{
		method:'post',
		parameters: params,
		onSuccess: function(transport){
			
			$('comments_'+feed_id).innerHTML = transport.responseText;

			loadTextChange();
		},
		onFailure: function(){}
	});
	
}
//Comment.del = function(feed_id, type){
//	var params = data;
//	params['ajax'] = 'comments';
//	params['action'] = 'Comments.del';
//	params['feed_id'] = feed_id;
//	
//	try{
//		params['page'] = $('curr_page').value;
//		params['page_id'] = $('curr_page_id').value;
//	}catch(e){}
//	
//	//$('comment_row_'+params['comment_id']).style.opacity = '0.5';
//	new Ajax.Request('index.php',
//	{
//		method:'post',
//		parameters: params,
//		onSuccess: function(transport){
//			if(type){
//				$('reply_comments_list_'+comment_to_id).innerHTML = transport.responseText;
//			}else{
//				$('comments_container').innerHTML = transport.responseText;
//			}
////			$('comments_'+params['identifier_id']).innerHTML = transport.responseText;
//			loadTextChange();
//		},
//		onFailure: function(){}
//	});
//}
Comment.limitText = function(obj,limit,spanID){
	if(obj.value.length > limit){
		obj.value=obj.value.substring(0,limit);
	}
	$(spanID).innerHTML = limit-obj.value.length;
}

var Comments = {};

Comments.showAllComments = function(){
	var mc = $j('.tg_friend');
	var mcl = mc.length;
	var i;
	var mci;
	for(i=0;i<mcl;i++){
		mci = $j(mc[i]);
		if(mci.hasClass('all_comments_flag')){
			mci.show();
		}else{
			mci.hide();
		}
	}
}

///////--------------------------------------
// For tinyMCE

var tinyMceBuffers    = new Object();
var tinyMceCharCounts = new Object();
var charLimit = 2000;

// Event fired when something in TinyMCE changes such as when an undo
// level is added like after a copy/paste.
function tinyMceOnChange(inst){ 
	tinyMceCheckContentLength(inst.id,charLimit); 
}

// Event fired for any normal UI event such as a key or mouse press.
function tinyMceEventHandler(e){
	//console.log('eventhandler!');
    switch (e.type) {
        case 'keyup': tinyMceOnChange(tinyMCE.activeEditor); break;
    }
    return true;
}

// Strips all html tags from a given string, leaving only plain text
function stripHtmlTags(strContent) { 
//	return strContent.replace(/(<([^>]+)>)/ig, "");
	strContent = strContent.replace(/<br>|<br\/>|<br \/>/ig, " "); 
	strContent = strContent.replace(/\s\s+/ig, " "); // /\s{2,}/ig
	return strContent.replace(/<[p].*?>|<\/[p]>|<br.*?>|\s+mce_href="[^"]*"|&nbsp;/ig, ""); 
}

function tinyMceCheckContentLength(strEditorId, intMaxLength) {
    var editorInstance   = tinyMCE.get(strEditorId);
    if (editorInstance   == null || editorInstance   == undefined) { alert('NO EDITOR'); }

    var contentContainer = editorInstance.getBody();
    if (contentContainer == null || contentContainer == undefined) { alert('NO CONTENT CONTAINER'); }

    var strContent       = contentContainer.innerHTML;
    var intContentLength = strContent.length;
    var intCharCount     = stripHtmlTags(strContent).length;
	var stripped         = stripHtmlTags(strContent);
    
    if (intCharCount <= intMaxLength) {
        // The user has not passed the maximum amount of content in the editor...

        // Save away the current contents in case they have typed too much and we have to
        // revert back to this state.
        tinyMceBuffers   [strEditorId] = strContent;
        tinyMceCharCounts[strEditorId] = intCharCount;
        $('textlimit').innerHTML = charLimit - intCharCount;
        console.log('HTML: %s',stripped);

    } else {
        // The user has put more than the maximum amount of content in the editor...
        // We must now revert back to the last good contents that we had for the editor,
        // or else whatever fits if we never had anything saved from there.
        var bm = editorInstance.selection.getBookmark(); // Stores a bookmark of the current selection
        editorInstance.setContent((tinyMceBuffers[strEditorId]) ? tinyMceBuffers[strEditorId] : strContent.substring(0, intMaxLength - 10));
        var intDelta = intCharCount - tinyMceCharCounts[strEditorId];
        if (bm['start'] && bm['start'] > intDelta) {
            bm['start'] -= intDelta;
            bm['end']   =  bm['start'];
        }
        editorInstance.selection.moveToBookmark(bm); // Restore the selection bookmark

        alert('You have exceeded the maximum size for this text and we have undone your last change.');
    }
}
