All pastes #329784 Raw Edit

Untitled

public text v1 · immutable
#329784 ·published 2007-01-27 01:24 UTC
rendered paste body
<?php
// ensure this file is being included by a parent file
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

// load language files
require_once( $mainframe->getPath( 'class', 'com_mls_lang' ) );
$l = new MLS_lang;
if(!$l->loadData()) {
	echo $l->_error;
}

// XML library
require_once( $mosConfig_absolute_path . '/includes/domit/xml_domit_lite_include.php' );
require_once( $mainframe->getPath( 'admin_html' ) );
require_once( $mainframe->getPath( 'class' ) );
require_once( $mainframe->getPath( 'class', 'com_mls_events' ) );

//Load league admin.php files
$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues` ORDER BY `name` ASC" );
$leagues = $database->loadObjectList();
if(count($leagues)) {
	foreach($leagues AS $league) {
		require_once( $mosConfig_absolute_path."/administrator/components/com_mls_tournaments/leagues/".$league->name."/admin.php" );
		require_once( $mosConfig_absolute_path."/administrator/components/com_mls_tournaments/leagues/".$league->name."/classes.php" );
	}
}
require_once( $mosConfig_absolute_path."/administrator/components/com_installer/installer.class.php" );
require_once( $mosConfig_absolute_path."/administrator/components/com_mls_tournaments/leagueinstaller.class.php" );


$cid = mosGetParam( $_POST, 'cid', array(0) );
if (!is_array( $cid )) {
	$cid = array(0);
}
if(file_exists($mosConfig_absolute_path."/administrator/components/".$option."/version")) {
	$act = "update";
}
switch($act) {
	case "update":
		//Start installation/upgrade
		include($mosConfig_absolute_path."/administrator/components/".$option."/comupgrade.class.php");
		$upgrade = new comUpgrade($option,"/install");
		$ret = $upgrade->doUpgrade();
		break;
	case "games":
		switch($task) {
			case "new":
				editMLS_tournaments_games('0',$option,$act);
				break;
			case "edit":
				editMLS_tournaments_games($cid[0],$option,$act);
				break;
			case "save":
				saveMLS_tournaments_games($option,$act);
				break;
			case "remove":
				removeMLS_tournaments_games($cid, $option,$act);
				break;
			default:
				listMLS_tournaments_games($option,$act);
				break;
		}
		break;
	case "servers":
		switch($task) {
			case "new":
				editMLS_tournaments_servers('0',$option,$act);
				break;
			case "edit":
				editMLS_tournaments_servers($cid[0],$option,$act);
				break;
			case "check_online":
				check_onlineMLS_tournaments_servers($cid,$option,$act);
				break;
			case "save":
				saveMLS_tournaments_servers($option,$act);
				break;
			case "remove":
				removeMLS_tournaments_servers($cid, $option,$act);
				break;
			default:
				listMLS_tournaments_servers($option,$act);
				break;
		}
		break;
	case "categories":
		switch($task) {
			case "new":
				editMLS_tournaments_categories('0',$option,$act);
				break;
			case "edit":
				editMLS_tournaments_categories($cid[0],$option,$act);
				break;
			case "save":
				saveMLS_tournaments_categories($option,$act);
				break;
			case "remove":
				removeMLS_tournaments_categories($cid, $option,$act);
				break;
			case "publish":
				genericChange($cid, "tournaments_categories","published",1,$option,$act);
				break;
			case "unpublish":
				genericChange($cid, "tournaments_categories","published",0,$option,$act);
				break;
			default:
				listMLS_tournaments_categories($option,$act);
				break;
		}
		break;
	case "tournaments":
		switch($task) {
			case "new":
				editMLS_tournaments_tournaments('0',$option,$act);
				break;
			case "edit":
				editMLS_tournaments_tournaments($cid[0],$option,$act);
				break;
			case "save":
				saveMLS_tournaments_tournaments($option,$act);
				break;
			case "remove":
				removeMLS_tournaments_tournaments($cid, $option,$act);
				break;
			case "publish":
				genericChange($cid, "tournaments","published",1,$option,$act);
				break;
			case "unpublish":
				genericChange($cid, "tournaments","published",0,$option,$act);
				break;
			case "registration":
				genericChange($cid, "tournaments","registration",1,$option,$act);
				break;
			case "unregistration":
				genericChange($cid, "tournaments","registration",0,$option,$act);
				break;
			case "start":
				//startform_MLS_tournaments_tournament($cid[0],$option,$act);
				start_MLS_tournaments_tournament($cid[0],$option,$act);
				break;
			case "save_start":
				save_start_MLS_tournaments_tournament( $option, $act );
				break;
			case "cancel_save":
				cancel_start_MLS_tournaments_tournament( $option, $act );
				break;
			case "preview":
				preview_MLS_tournaments_tournament( $option, $act );
				break;
			case "stop":
				stop_MLS_tournaments_tournament($cid[0],$option,$act);
				break;
			default:
				listMLS_tournaments_tournaments($option,$act);
				break;
		}
		break;
	case "participants":
		switch($task) {
			case "new":
				editMLS_tournaments_participants('0',$option,$act);
				break;
			case "edit":
				editMLS_tournaments_participants($cid[0],$option,$act);
				break;
			case "save":
				saveMLS_tournaments_participants($option,$act);
				break;
			case "remove":
				removeMLS_tournaments_participants($cid, $option,$act);
				break;
			default:
				listMLS_tournaments_participants($option,$act);
				break;
		}
		break;
	case "brackets":
		switch($task) {
			case "new":
				editMLS_tournaments_brackets('0',$option,$act);
				break;
			case "edit":
				editMLS_tournaments_brackets($cid[0],$option,$act);
				break;
			case "save":
				saveMLS_tournaments_brackets($option,$act);
				break;
			case "remove":
				removeMLS_tournaments_brackets($cid, $option,$act);
				break;
			case "submit_results":
				submitMLS_tournaments_brackets($cid[0], $option, $act);
				break;
			case "save_results":
				save_resultsMLS_tournaments_brackets( $option, $act );
				break;
			default:
				listMLS_tournaments_brackets($option,$act);
				break;
		}
		break;
	case "export":
		switch($task) {
			case "export_do":
				exportMLS_tournamentsDo( $option, $act, mosGetParam( $_REQUEST, "eventid" ), mosGetParam( $_REQUEST, "league" ), mosGetParam( $_REQUEST, "tournaments", array(0) ) );
				break;
			default:
				exportMLS_tournaments( $option, $act, mosGetParam( $_REQUEST, "eventid" ), mosGetParam( $_REQUEST, "league" ) );
				break;
		}
		break;
	case "leagues":
		switch($task) {
			case "detail":
				$league = $cid[0] ? $cid[0] : mosGetParam( $_REQUEST, 'league', "" );
				$baseurl = $mosConfig_live_site."/administrator/index2.php?option=".$option."&act=".$act."&task=".$task."&league=".$league;
				$function = "detail_".$league;
				$function( $option, $act, $task, $baseurl );
				break;
			case 'uploadfile':
				uploadPackage( $option, $act );
				break;
			case 'installfromdir':
				installFromDirectory( $option, $act );
				break;
			case 'remove':
				removeElement( $option, $act );
				break;
			default:
				listMLS_tournaments_leagues( $option, $act );
				break;
		}
		break;
}


/** Leagues */
function listMLS_tournaments_leagues( $option, $act ) {
	global $database, $my, $mainframe, $mosConfig_list_limit, $mosConfig_absolute_path;
	
	$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues` ORDER BY `id` ASC" );
	$rows = $database->loadObjectList();
	
	// Read the component dir to find components
	$componentBaseDir	= mosPathName( $mosConfig_absolute_path . '/administrator/components/' );
	$n = count( $rows );
	for ($i = 0; $i < $n; $i++) {
		$row =& $rows[$i];

		$dirName = $componentBaseDir . $option . "/leagues/" . $row->name;
		$xmlFilesInDir = mosReadDirectory( $dirName, '.xml$' );

		foreach ($xmlFilesInDir as $xmlfile) {
			// Read the file to see if it's a valid component XML file
			$xmlDoc = new DOMIT_Lite_Document();
			$xmlDoc->resolveErrors( true );

			if (!$xmlDoc->loadXML( $dirName . '/' . $xmlfile, false, true )) {
				continue;
			}

			$root = &$xmlDoc->documentElement;

			if ($root->getTagName() != 'mosinstall') {
				continue;
			}
			if ($root->getAttribute( "type" ) != "mlsleague") {
				continue;
			}

			$element 			= &$root->getElementsByPath('creationDate', 1);
			$row->creationdate 	= $element ? $element->getText() : 'Unknown';

			$element 			= &$root->getElementsByPath('author', 1);
			$row->author 		= $element ? $element->getText() : 'Unknown';

			$element 			= &$root->getElementsByPath('copyright', 1);
			$row->copyright 	= $element ? $element->getText() : '';

			$element 			= &$root->getElementsByPath('authorEmail', 1);
			$row->authorEmail 	= $element ? $element->getText() : '';

			$element 			= &$root->getElementsByPath('authorUrl', 1);
			$row->authorUrl 	= $element ? $element->getText() : '';

			$element 			= &$root->getElementsByPath('version', 1);
			$row->version 		= $element ? $element->getText() : '';
		}
	}
	HTML_MLS_tournaments_leagues::listLeagues( $rows, $option, $act );
}

function uploadPackage( $option, $act ) {
	global $mosConfig_live_site;
	$baseurl = $mosConfig_live_site . "/administrator/index2.php?option=".$option."&act=".$act;
	$installer = new mosInstallerMLSLeague();
	// Check if file uploads are enabled
	if (!(bool)ini_get('file_uploads')) {
		mosRedirect($baseurl . "&mosmsg=The installer can't continue before file uploads are enabled. Please use the install from directory method.");
		exit();
	}

	// Check that the zlib is available
	if(!extension_loaded('zlib')) {
		mosRedirect($baseurl . "&mosmsg=The installer can't continue before zlib is installed");
		exit();
	}
	
	$userfile = mosGetParam( $_FILES, 'userfile', null );
	
	if (!$userfile) {
		mosRedirect($baseurl . "&mosmsg=No file selected");
		exit();
	}

	$userfile_name = $userfile['name'];

	$msg = '';
	$resultdir = uploadFile( $userfile['tmp_name'], $userfile['name'], $msg );
	
	if ($resultdir !== false) {
		/** if (!$installer->upload( $userfile['name'] )) {
			mosRedirect($baseurl . "&mosmsg=Upload Failed");
		} */
		
		$installer->upload( $userfile['name'] );
		$ret = $installer->install();
		HTML_MLS_tournaments_leagues::showInstallMessage( $installer->getError(), 'Upload - '.($ret ? 'Success' : 'Failed'), $baseurl );
		cleanupInstall( $userfile['name'], $installer->unpackDir() );
	} else {
		mosRedirect($baseurl . "&mosmsg=Upload Error");
	}
}

/**
* @param string The name of the php (temporary) uploaded file
* @param string The name of the file to put in the temp directory
* @param string The message to return
*/
function uploadFile( $filename, $userfile_name, &$msg ) {
	global $mosConfig_absolute_path;
	$baseDir = mosPathName( $mosConfig_absolute_path . '/media' );

	if (file_exists( $baseDir )) {
		if (is_writable( $baseDir )) {
			if (move_uploaded_file( $filename, $baseDir . $userfile_name )) {
				if (mosChmod( $baseDir . $userfile_name )) {
					return true;
				} else {
					$msg = 'Failed to change the permissions of the uploaded file.';
				}
			} else {
				$msg = 'Failed to move uploaded file to <code>/media</code> directory.';
			}
		} else {
			$msg = 'Upload failed as <code>/media</code> directory is not writable.';
		}
	} else {
		$msg = 'Upload failed as <code>/media</code> directory does not exist.';
	}
	return false;
}

function removeElement( $option, $act ) {
	global $mosConfig_live_site;
	$baseurl = $mosConfig_live_site . "/administrator/index2.php?option=".$option."&act=".$act."&mosmsg=Uninstallation ";
	$cid = mosGetParam( $_REQUEST, 'cid', array(0) );
	if (!is_array( $cid )) {
		$cid = array(0);
	}

	$installer 	= new mosInstallerMLSLeague();
	$result 	= false;
	if ($cid[0]) {
		$result = $installer->uninstall( $cid[0], $option, $act );
	}

	$msg = $installer->getError();
	$baseurl .= $result ? 'Success ' : 'Failed ';
	mosRedirect($baseurl);
}

/** Export */
function exportMLS_tournamentsDo( $option, $act, $eventid=null, $leaguename=null, $tournamentids=null ) {
	global $database, $my, $mainframe, $l, $mosConfig_live_site;
	
	//League
	$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues` WHERE `name`='".$leaguename."'" );
	$database->loadObject( $league );
	
	//Event
	$database->setQuery( "SELECT * FROM `#__mls_events` WHERE `id`='".$eventid."'" );
	$database->loadObject( $event );
	if($league->events) {
		$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues_".$leaguename."_events` WHERE `parentid`='".$eventid."'" );
		$database->loadObject( $event->_league );
	}
	
	//Tournaments
	$database->setQuery( "SELECT * FROM `#__mls_tournaments` WHERE `id` IN (".implode(",",$tournamentids).")" );
	$tournaments = $database->loadObjectList();
	if($league->tournaments) {
		for($i = 0; $i < count($tournaments); $i++) {
			$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues_".$leaguename."_tournaments` WHERE `parentid`='".$tournaments[$i]->id."'" );
			$database->loadObject( $tournaments[$i]->_league );
		}
	}
	
	//loop through tournaments for various stuff..
	for($i = 0; $i < count($tournaments); $i++) {
		$t = new mosMLS_tournaments_tournament( $database );
		
		//Players (Teams, Users)
		$rankings = $t->getRankings($tournaments[$i]->id, "wwcl");
		
		if($tournaments[$i]->type == "C") {
			//Clans tournaments
			$tournaments[$i]->_teams = array();
			for($k = 0; $k < count($rankings); $k++) {
				$database->setQuery( "SELECT * FROM `#__mls_teams` WHERE `id`='".$rankings[$k]->id."'" );
				$database->loadObject($tournaments[$i]->_teams[$k]);
				$tournaments[$i]->_teams[$k]->rank = $rankings[$k]->rank;
				
				if($league->teams) {
					$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues_".$leaguename."_teams` WHERE `parentid`='".$tournaments[$i]->_teams[$k]->id."'" );
					$database->loadObject( $tournaments[$i]->_teams[$k]->_league );
				}
				
				//Get Members
				$database->setQuery( "SELECT u.*,m.leader FROM `#__mls_teams_members` AS `m`"
								."\n INNER JOIN `#__users` AS `u` ON u.id=m.userid"
								."\n WHERE m.teamid='".$tournaments[$i]->_teams[$k]->id."'" );
				$members = $database->loadObjectList();
				$tournaments[$i]->_teams[$k]->_members = array();
				for($m = 0; $m < count($members); $m++) {
					$tournaments[$i]->_teams[$k]->_members[$m] = $members[$m];
					if($league->users) {
						$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues_".$leaguename."_users` WHERE `parentid`='".$members[$m]->userid."'" );
						$database->loadObject( $tournaments[$i]->_teams[$k]->_members[$m]->_league );
					}
				}
			}
		} else {
			//Singleplayer Tournament
			for($k = 0; $k < count($rankings); $k++) {
				$database->setQuery( "SELECT * FROM `#__users` WHERE `id`='".$rankings[$k]->id."'" );
				$database->loadObject($tournaments[$i]->_teams[$k]);
				$tournaments[$i]->_teams[$k]->rank = $rankings[$k]->rank;
				
				if($league->users) {
					$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues_".$leaguename."_users` WHERE `parentid`='".$tournaments[$i]->_teams[$k]->id."'" );
					$database->loadObject( $tournaments[$i]->_teams[$k]->_league );
				}
			}
		}
		
		//Matches
		$database->setQuery( "SELECT * FROM `#__mls_tournaments_matches`"
						."\n WHERE `tournamentid`='".$t->id."' AND `bracket` IN ('l','w')"
						."\n ORDER BY `bracket` ASC, `roundnr` ASC, `matchnr` ASC" );
		
		$tmp = $database->loadObjectList();
		$tournaments[$i]->_brackets = array();
		foreach($tmp as $match) {
			$tournaments[$i]->_brackets[$match->bracket]->_rounds[$match->roundnr]->_matches[$match->matchnr] = $match;
		}
		
	}
	
	$function = "export_".$leaguename;
	$xmlData = $function( $event, $league, $tournaments );
	?>
	<textarea rows="38" cols="120"><?=$xmlData;?></textarea>
	<?php
}

function exportMLS_tournaments( $option, $act, $eventid=null, $league=null ) {
	global $database, $my, $mainframe, $l, $mosConfig_live_site;
	$l->setBlock( "export" );
	
	$lists = array();
	
	//load events
	$database->setQuery( "SELECT * FROM `#__mls_events` ORDER BY `start` DESC" );
	$events = $database->loadObjectList();
	$opt = array();
	$opt[] = mosHTML::makeOption( '0', $l->m("select_event") );
	foreach($events as $tmp) {
		$opt[] = mosHTML::makeOption( $tmp->id, $tmp->name );
	}
	$lists["event"] = mosHTML::selectList($opt, 'eventid', ' class="inputbox" size="1" onChange="document.location.href=\''.$mosConfig_live_site.'/administrator/index2.php?option=com_mls_tournaments&act=export&eventid=\' + this.value;"', 'value', 'text', $eventid);
	
	if($eventid) {
		//load leagues
		$database->setQuery( "SELECT l.*,COUNT(t.id) AS `num_tournaments` FROM `#__mls_tournaments_leagues` AS `l`"
						."\n LEFT JOIN `#__mls_tournaments`AS `t` ON t.league=l.name"
						."\n WHERE (t.eventid=".$eventid.") OR t.id IS NULL"
						."\n GROUP BY l.id"
						."\n ORDER BY l.name ASC" );
		$leagues = $database->loadObjectList();
		$opt = array();
		$opt[] = mosHTML::makeOption( '0', $l->m("select_league") );
		foreach($leagues as $tmp) {
			$opt[] = mosHTML::makeOption( $tmp->name, $tmp->description . " (".$tmp->num_tournaments." ".$l->m("tournaments"). ")" );
		}
		$lists["league"] = mosHTML::selectList($opt, 'league', ' class="inputbox" size="1" onChange="document.location.href=\''.$mosConfig_live_site.'/administrator/index2.php?option=com_mls_tournaments&act=export&eventid='.$eventid.'&league=\' + this.value;"', 'value', 'text', $league);
		
		if($league) {
			//load tournaments, only where the last match is played
			$database->setQuery( "SELECT DISTINCT t.* FROM `#__mls_tournaments` AS `t`"
							."\n LEFT JOIN `#__mls_tournaments_matches`AS `m` ON m.tournamentid=t.id"
							."\n WHERE t.league='".$league."' AND t.eventid='".$eventid."' AND t.started=1"
							."\n AND m.result_submit=1 AND m.bracket='w'"
							."\n ORDER BY m.roundnr DESC" );
			
			$database->setQuery( "SELECT t.* FROM `#__mls_tournaments` AS `t`"
							."\n WHERE t.league='".$league."' AND t.eventid='".$eventid."'"
							."\n ORDER BY t.name ASC" );
			$tournaments = $database->loadObjectList();
			$opt = array();
			foreach($tournaments as $t) {
				$opt[] = mosHTML::makeOption( $t->id, $t->name );
			}
			$lists["tournaments"] = mosHTML::selectList($opt, 'tournaments[]', ' class="inputbox" size="5" multiple', 'value', 'text', 0);
		}
	}
	
	HTML_MLS_tournaments_export::exportForm( $lists, $option, $act );
}


/** Games */
function listMLS_tournaments_games($option,$act) {
	global $database, $my, $mainframe, $mosConfig_list_limit;
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
	$limitstart = $mainframe->getUserStateFromRequest( "view_games_{$option}limitstart", 'limitstart', 0 );
	
	// get the total number of records
	$database->setQuery( "SELECT g.*,COUNT(t.id) AS `records`,COUNT(s.id) AS `server_records`"
					."\n FROM `#__mls_tournaments_games` AS `g`"
					."\n LEFT JOIN `#__mls_tournaments` AS `t` ON t.gameid=g.id"
					."\n LEFT JOIN `#__mls_tournaments_servers` AS `s` ON s.gameid=g.id"
					."\n GROUP BY g.id"
					."\n ORDER BY g.name ASC" );
	$database->query();
	$total = $database->getNumRows();
	
	//load PageNav
	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	
	//select records
	$database->setQuery( "SELECT g.*,COUNT(t.id) AS `records`,COUNT(s.id) AS `server_records`"
					."\n FROM `#__mls_tournaments_games` AS `g`"
					."\n LEFT JOIN `#__mls_tournaments` AS `t` ON t.gameid=g.id"
					."\n LEFT JOIN `#__mls_tournaments_servers` AS `s` ON s.gameid=g.id"
					."\n GROUP BY g.id"
					."\n ORDER BY g.name ASC"
					."\n LIMIT $pageNav->limitstart, $pageNav->limit" );
	
	$rows = $database->loadObjectList();
	HTML_MLS_tournaments_games::listGames($rows, $pageNav, $option, $act);
}

function editMLS_tournaments_games($id,$option,$act) {
	global $database, $my, $mainframe,$l;
	$l->setBlock("general");
	$row = new mosMLS_tournaments_game( $database );
	
	// load the row from the db table
	$row->load( $id );
	
	if ($id) {
		// do stuff for existing records
	} else {
		// do stuff for new records
	}
	
	HTML_MLS_tournaments_games::editGame($row, $option, $act);
}

function removeMLS_tournaments_games( &$cid, $option ) {
	global $database;

	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$database->setQuery( "DELETE FROM `#__mls_tournaments_games` WHERE `id` IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

	mosRedirect( "index2.php?option=$option&act=$act" );
}

function saveMLS_tournaments_games($option,$act) {
	global $database, $my, $mainframe;
	
	$row = new mosMLS_tournaments_game( $database );
	$row->save($_POST);
	mosRedirect( "index2.php?option=$option&act=$act" );
}

/** Servers */
function listMLS_tournaments_servers($option,$act) {
	global $database, $my, $mainframe, $mosConfig_list_limit;
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
	$limitstart = $mainframe->getUserStateFromRequest( "view_servers_{$option}limitstart", 'limitstart', 0 );
	
	// get the total number of records
	$database->setQuery( "SELECT s.*,COUNT(m.id) AS `records`, g.name AS `gamename`"
					."\n FROM `#__mls_tournaments_servers` AS `s`"
					."\n LEFT JOIN `#__mls_tournaments_games` AS `g` ON g.id=s.gameid"
					."\n LEFT JOIN `#__mls_tournaments_matches` AS `m` ON m.serverid=s.id"
					."\n GROUP BY s.id"
					."\n ORDER BY s.name ASC" );
	$database->query();
	$total = $database->getNumRows();
	
	//load PageNav
	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	
	//select records
	
	$database->setQuery( "SELECT s.*,COUNT(m.id) AS `records`, g.name AS `gamename`"
					."\n FROM `#__mls_tournaments_servers` AS `s`"
					."\n LEFT JOIN `#__mls_tournaments_games` AS `g` ON g.id=s.gameid"
					."\n LEFT JOIN `#__mls_tournaments_matches` AS `m` ON m.serverid=s.id"
					."\n GROUP BY s.id"
					."\n ORDER BY s.name ASC"
					."\n LIMIT $pageNav->limitstart, $pageNav->limit" );
	$rows = $database->loadObjectList();
	HTML_MLS_tournaments_servers::listServers($rows, $pageNav, $option, $act);
}

function editMLS_tournaments_servers($id, $option,$act) {
	global $database, $my, $mainframe,$l;
	$l->setBlock("general");
	$row = new mosMLS_tournaments_server( $database );
	
	// load the row from the db table
	$row->load( $id );
	
	if ($id) {
		// do stuff for existing records
	} else {
		// do stuff for new records
	}
	
	//make the html select lists
	$lists = array();
	$database->setQuery( "SELECT `id`, `name` FROM `#__mls_tournaments_games` ORDER BY `name` ASC" );
	$temp = $database->loadObjectList();
	$opt[] = mosHTML::makeOption( '0', $l->m("select_game") );
	foreach($temp as $tmp) {
		$opt[] = mosHTML::makeOption( $tmp->id, $tmp->name );
	}
	$lists["gameid"] = mosHTML::selectList($opt, 'gameid', ' class="inputbox"', 'value', 'text', $row->gameid);
	
	HTML_MLS_tournaments_servers::editServer($row, $lists, $option, $act);
}

function removeMLS_tournaments_servers( &$cid, $option ) {
	global $database;

	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$database->setQuery( "DELETE FROM `#__mls_tournaments_servers` WHERE `id` IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}
	
	mosRedirect( "index2.php?option=$option&act=$act" );
}

function saveMLS_tournaments_servers($option,$act) {
	global $database, $my, $mainframe;
	
	$row = new mosMLS_tournaments_server( $database );
	$row->bind($_POST);
	$row->checkOnline();
	$row->store();
	mosRedirect( "index2.php?option=$option&act=$act" );
}

function check_onlineMLS_tournaments_servers($cid, $option,$act) {
	global $database, $my, $mainframe,$l;
	$l->setBlock("general");
	
	foreach($cid as $id) {
		$row = new mosMLS_tournaments_server( $database );
		
		// load the row from the db table
		$row->load( $id );
		
		//check online status
		$row->checkOnline;
		$row->store();
	}
	mosRedirect( "index2.php?option=$option&act=$act" );
}

/** Categories */
function listMLS_tournaments_categories($option,$act) {
	global $database, $my, $mainframe, $mosConfig_list_limit;
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
	$limitstart = $mainframe->getUserStateFromRequest( "view_categories_{$option}limitstart", 'limitstart', 0 );
	
	// get the total number of records
	$database->setQuery( "SELECT c.id,c.name,c.published,COUNT(t.id) AS `records`"
					."\n FROM `#__mls_tournaments_categories` AS `c`"
					."\n LEFT JOIN `#__mls_tournaments` AS `t` ON t.categoryid=c.id"
					."\n GROUP BY c.id"
					."\n ORDER BY c.name ASC" );
	$database->query();
	$total = $database->getNumRows();
	
	//load PageNav
	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	
	//select records
	$database->setQuery( "SELECT c.id,c.name,c.published,COUNT(t.id) AS `records`"
					."\n FROM `#__mls_tournaments_categories` AS `c`"
					."\n LEFT JOIN `#__mls_tournaments` AS `t` ON t.categoryid=c.id"
					."\n GROUP BY c.id"
					."\n ORDER BY c.name ASC"
					."\n LIMIT $pageNav->limitstart, $pageNav->limit");
	$rows = $database->loadObjectList();
	HTML_MLS_tournaments_categories::listCategories($rows, $pageNav, $option, $act);
}

function editMLS_tournaments_categories($id,$option,$act) {
	global $database, $my, $mainframe,$l;
	$l->setBlock("general");
	$row = new mosMLS_tournaments_category( $database );
	
	// load the row from the db table
	$row->load( $id );
	
	if ($id) {
		// do stuff for existing records
	} else {
		// do stuff for new records
		$row->published = 0;
	}
	
	// build the html select lists
	$lists = array();
	$lists["published"] = mosHTML::yesnoRadioList('published', ' class="inputbox"', $row->published);
	
	HTML_MLS_tournaments_categories::editCategory($row, $lists, $option, $act);
}

function removeMLS_tournaments_categories( &$cid, $option ) {
	global $database;

	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$database->setQuery( "SELECT `id` FROM `#__mls_tournaments` WHERE `categoryid` IN ($cids)" );
		$rows = $database->loadObjectList();
		$tids = "";
		foreach($rows as $row) {
			$tids .= $row->id.",";
		}
		$tids = substr($row->id,0,strlen($tids) - 1);
		$database->setQuery( "DELETE FROM `#__mls_tournaments` WHERE `id` IN ($tids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
		$database->setQuery( "DELETE FROM `#__mls_tournaments_participants` WHERE `tournamentid` IN ($tids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
		$database->setQuery( "DELETE FROM `#__mls_tournaments_matches` WHERE `tournamentid` IN ($tids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
		$database->setQuery( "DELETE FROM `#__mls_tournaments_categories` WHERE `id` IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

	mosRedirect( "index2.php?option=$option&act=$act" );
}

function saveMLS_tournaments_categories($option,$act) {
	global $database, $my, $mainframe;
	
	$row = new mosMLS_tournaments_category( $database );
	$row->save($_POST);
	mosRedirect( "index2.php?option=$option&act=$act" );
}

function genericChange( $cid, $type, $field, $value, $option, $act ) {
	global $database,$my;
	
	$query = "UPDATE `#__mls_".$type."` SET `".$field."`='".$value."' WHERE `id` IN (".implode(",",$cid).")";
	$database->setQuery($query);
	$database->query();
	
	mosRedirect( "index2.php?option=$option&act=$act" );
}

/** Tournaments */
function stop_MLS_tournaments_tournament($id,$option,$act) {
	global $database, $my, $l;
	$t = new mosMLS_tournaments_tournament( $database );
	$t->load( $id );
	
	$database->setQuery( "DELETE FROM `#__mls_tournaments_matches` WHERE `tournamentid`='".$id."'" );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	$database->setQuery( "DELETE FROM `#__mls_tournaments_matches_temp` WHERE `tournamentid`='".$id."'" );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	$database->setQuery( "UPDATE `#__mls_tournaments` SET `started`='0', `registration`='1' WHERE `id`='".$id."'" );
	if (!$database->query()) {
		echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	mosRedirect( "index2.php?option=$option&act=$act" );
}

/**
* Start a tournament, prepare the form to select servers
**/
function startform_MLS_tournaments_tournament( $id, $option, $act ) {
	global $database, $my, $l;
	$l->setBlock("tournaments");
	
	/** First, get the tournament data */
	$t = new mosMLS_tournaments_tournament( $database );
	$t->load( $id );
	
	/** Get the event */
	$e = new mosMLS_events( $database );
	$e->load( $t->eventid );
	
	/** Load the list of servers for this game, if a game is defined **/
	if($t->gameid) {
		$database->setQuery( "SELECT *,IF(online=1,'".$l->m("online","servers")."','".$l->m("offline","servers")."') AS `onlinestatus` FROM `#__mls_tournaments_servers` WHERE `gameid`='".$t->gameid."'" );
		$servers = $database->loadObjectList();
		$opt = array();
		foreach($servers as $server) {
			$opt[] = mosHTML::makeOption( $server->id, $server->name . " (".$server->onlinestatus.")" );
		}
		
		$lists["servers"] = mosHTML::selectList( $opt, 'servers[]', ' class="inputbox" size="5" multiple', 'value', 'text', '0' );
	}
	
	/** Precalculate the nights for exclusion **/
	$startdate = strtotime($e->start);
	$enddate = strtotime($e->end);
	$exclusions["from"] = array();
	$exclusions["to"] = array();
	for($tmp = $startdate; $tmp < $enddate; $tmp += 86400) {
		$from = date( "Y-m-d", $tmp ) . " 22:00:00";
		if(strtotime( $from ) < $startdate ) {
			//The event begins before 10pm on the first day
			//So just set the start time to the event starttime
			$from = date( "Y-m-d H:i:s", $startdate );
		}
		$exclusions["from"][] = $from;
		
		
		$to = date( "Y-m-d", $tmp + 86400 ) . " 06:00:00";
		if(strtotime( $to ) > $enddate ) {
			//The event finishes before 6am on the last day (who knows, might happen :)
			//So just set the end time to the event endtime
			$to = date( "Y-m-d H:i:s", $enddate );
		}
		$exclusions["to"][] = $to;
	}
	
	HTML_MLS_tournaments_tournaments::startForm( $t, $e, $lists, $exclusions, $option );
}

/**
 * Cancel Start tournament. If you are arranging the matches but then cancel
 */
function cancel_start_MLS_tournaments_tournament( $option, $act ) {
	stop_MLS_tournaments_tournament( $_POST["id"], $option, $act );
}

function preview_MLS_tournaments_tournament( $option, $act ) {
	global $database, $l, $mosConfig_live_site;
	
	/** First, get our data (tournament and participants) */
	$l->setBlock("tournaments");
	$t = new mosMLS_tournaments_tournament( $database );
	$t->load( $_POST["id"] );
	$t->_temp = 1;
	
	/** Check number of matches */
	for($temp = count($_POST["matches"]); $temp > 1; $temp = $temp / 2) {
		if($temp < 2) {
			die("ERROR");
		} elseif($temp == 2) {
			continue;
		}
	}
	
	/** Clear temporary table */
	$database->setQuery( "DELETE FROM `#__mls_tournaments_matches_temp`  WHERE `tournamentid`='".$t->id."'" );
	$database->query();
	
	/** Now, fill it again with what's in the real table */
	$database->setQuery( "SELECT * FROM `#__mls_tournaments_matches`  WHERE `tournamentid`='".$t->id."'" );
	$matches = $database->loadObjectList();
	
	foreach($matches as $match) {
		$database->setQuery( "INSERT INTO `#__mls_tournaments_matches_temp` (`id`,`matchnr`,`roundnr`,`clan1id`,`clan2id`,`tournamentid`,`bracket`)"
						."\n VALUES ('".$match->id."','".$match->matchnr."','".$match->roundnr."','".$match->clan1id."','".$match->clan2id."','".$match->tournamentid."','".$match->bracket."')" );
		$database->query();
	}
	
	/** Update the temp table with the info from the form */
	$matchIDs = array();
	foreach($_POST["matches"] AS $matchid => $players) {
		$matchIDs[] = $matchid;
		$database->setQuery( "UPDATE `#__mls_tournaments_matches_temp` SET `clan1id`='".@$players[0]."', `clan2id`='".@$players[1]."' WHERE `id`='".$matchid."'" );
		$database->query();
	}
	
	/** Delete all empty matches */
	$database->setQuery( "DELETE FROM `#__mls_tournaments_matches_temp`  WHERE `tournamentid`='".$t->id."' AND `id` NOT IN (".implode(",",$matchIDs).")" );
	$database->query();
	
	/** Create all the other rounds and start the tournament */
	$t->createOtherRounds();
	
	?>
	<script language="JavaScript">
	window.open('<?php echo $mosConfig_live_site; ?>/index2.php?option=com_mls_tournaments&task=view_brackets&tournamentid=<?php echo $t->id; ?>&temp=1');
	</script>
	<?php
	start_MLS_tournaments_tournament( $t->id, $option, $act );
}

/**
 * This is the final step. Store the changes made to the first round and then calculate all the other shit and off we go!
 */
function save_start_MLS_tournaments_tournament( $option, $act ) {
	global $database, $l;
	
	/** First, get our data (tournament and participants) */
	$l->setBlock("tournaments");
	$t = new mosMLS_tournaments_tournament( $database );
	$t->load( $_POST["id"] );
	
	/** Update matches */
	$matchIDs = array();
	$i = 0;
	foreach($_POST["matches"] AS $matchid => $players) {
		$i++;
		$matchIDs[] = $matchid;
		//$database->setQuery( "INSERT INTO `#__mls_tournaments_matches` (`id`,`matchnr`,`roundnr`,`clan1id`,`clan2id`,`tournamentid`,`bracket`)"
		//				."\n VALUES ('','".$i."','1','".$players[0]."','".$players[1]."','".$t->id."','w')" );
		$database->setQuery( "UPDATE `#__mls_tournaments_matches` SET `clan1id`='".@$players[0]."', `clan2id`='".@$players[1]."' WHERE `id`='".$matchid."'" );
		$database->query();
	}
	
	/** Delete all empty matches */
	$database->setQuery( "DELETE FROM `#__mls_tournaments_matches`  WHERE `tournamentid`='".$t->id."' AND `id` NOT IN (".implode(",",$matchIDs).")" );
	$database->query();
	
	/** Create all the other rounds and start the tournament */
	$t->createOtherRounds();
	
	mosRedirect( "index2.php?option=$option&act=$act", $l->m("msg_tournament_started") );
}

/**
 * Start tournaments
 * Create first round only and then display the edit form to change the first round
 */
function start_MLS_tournaments_tournament( $id, $option, $act ) {
	global $database, $my, $l;
	
	/** First, get our data (tournament and participants) */
	$l->setBlock("tournaments");
	$t = new mosMLS_tournaments_tournament( $database );
	$t->load( $id );
	
	/** Delete all matches for this tournament */
	$database->setQuery( "DELETE FROM `#__mls_tournaments_matches` WHERE `tournamentid`='".$t->id."'" );
	$database->query();
	$database->setQuery( "DELETE FROM `#__mls_tournaments_matches_temp` WHERE `tournamentid`='".$t->id."'" );
	$database->query();
	
	/** Create the first round with all participants and defwins */
	if(!@$_POST["matches"]) {
		$t->createFirstRound();
		$t->_temp = 1;
		$t->createFirstRound();
	}
	$l->setBlock("brackets");
	$database->setQuery( "SELECT m.*,"
					."\n t.name AS `tournamentname`, t.type AS `tournamenttype`,"
					."\n e.name AS `eventname`,"
					."\n c.name AS `categoryname`,"
					."\n IF(m.clan1id='F','".$l->m("default_win")."',IF(t.type='P',CONCAT(u1.name,' (',u1.username,')'),team1.name)) AS `player1_name`,"
					."\n IF(m.clan1id!='F',IF(t.type='P',u1.id,team1.id),'F') AS `player1_id`,"
					."\n IF(m.clan2id='F','".$l->m("default_win")."',IF(t.type='P',CONCAT(u2.name,' (',u2.username,')'),team2.name)) AS `player2_name`,"
					."\n IF(m.clan2id!='F',IF(t.type='P',u2.id,team2.id),'F') AS `player2_id`"
					."\n FROM `#__mls_tournaments_matches` AS `m`"
					."\n INNER JOIN `#__mls_tournaments` AS `t` ON t.id=m.tournamentid"
					."\n INNER JOIN `#__mls_tournaments_categories` AS `c` ON c.id=t.categoryid"
					."\n INNER JOIN `#__mls_events` AS `e` ON e.id=t.eventid"
					."\n LEFT JOIN `#__users` AS `u1` ON u1.id=m.clan1id"
					."\n LEFT JOIN `#__users` AS `u2` ON u2.id=m.clan2id"
					."\n LEFT JOIN `#__mls_teams` AS `team1` ON team1.id=m.clan1id"
					."\n LEFT JOIN `#__mls_teams` AS `team2` ON team2.id=m.clan2id"
					."\n WHERE t.id='".$t->id."' AND m.roundnr='1'"
					."\n GROUP BY m.id"
					."\n ORDER BY m.matchnr");
	$matches = $database->loadObjectList();
	
	if($t->type == "P") {
		$query = "SELECT CONCAT(`name`,' (',`username`,')') FROM `#__users` WHERE `id`='%s'";
	} else {
		$query = "SELECT `name` FROM `#__mls_teams` WHERE `id`='%s'";
	}
	
	if(@$_POST["matches"]) {
		for($i = 0; $i < count($matches); $i++) {
			$match =& $matches[$i];
			$id1 = @$_POST["matches"][$match->id][0];
			$id2 = @$_POST["matches"][$match->id][1];
			
			$match->player1_id = $id1;
			$database->setQuery( sprintf( $query, $id1) );
			$match->player1_name = $id1 == "F" ? $l->m("default_win") : $database->loadResult();
			
			$match->player2_id = $id2;
			$database->setQuery( sprintf( $query, $id2) );
			$match->player2_name = $id2 == "F" ? $l->m("default_win") : $database->loadResult();
		}
	}
	
	$opt = array();
	if(@$_POST["availableTeams"]) {
		foreach(@$_POST["availableTeams"] AS $id) {
			$database->setQuery( sprintf( $query, $id) );
			$name = $id == "F" ? $l->m("default_win") : $database->loadResult();
			$opt[] = mosHTML::makeOption( $id, $name );
		}
	}
	
	$lists["availableTeams"] = mosHTML::selectList( $opt, 'availableTeams[]', ' width="150" id="availableTeams" size="20" style="width: 150;" multiple', 'value', 'text', '0' );
	
	HTML_MLS_tournaments_tournaments::changeMatches( $t, $lists, $matches, $option, $act );
}

function listMLS_tournaments_tournaments($option,$act) {
	global $database, $my, $mainframe, $mosConfig_list_limit;
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
	$limitstart = $mainframe->getUserStateFromRequest( "view_tournaments_{$option}limitstart", 'limitstart', 0 );
	$search = $mainframe->getUserStateFromRequest( "search_tournaments{$option}items", 'search', '' );
	$search = $database->getEscaped( trim( strtolower( $search ) ) );
	$categoryid = $mainframe->getUserStateFromRequest( "filter_categoryid_tournaments{$option}", 'categoryid', 0 );
	$eventid = $mainframe->getUserStateFromRequest( "filter_eventid_tournaments{$option}", 'eventid', 0 );
	
	$where = "";
	$words = explode(" ",$search);
	foreach($words as $word) {
		if($word) {
			$op = $where ? "AND" : "WHERE";
			$where .= " $op (t.name LIKE '%$word%' OR c.name LIKE '%$word%' OR e.name LIKE '%$word%' OR t.type LIKE '%$word%' OR t.mode LIKE '%$word%')";
		}
	}
	$op = $where ? "AND" : "WHERE";
	$where .= $categoryid ? " $op t.categoryid = '$categoryid'" : "";
	$op = $where ? "AND" : "WHERE";
	$where .= $eventid ? " $op t.eventid = '$eventid'" : "";
	
	// get the total number of records
	$database->setQuery( "SELECT t.*,c.name AS `categoryname`, g.name AS `gamename`, e.name AS `eventname`, SUM(IF(p.tournamentid=t.id,1,'NULL')) AS `participants`"
					."\n FROM `#__mls_tournaments` AS `t`"
					."\n LEFT JOIN `#__mls_tournaments_categories` AS `c` ON c.id=t.categoryid"
					."\n LEFT JOIN `#__mls_tournaments_games` AS `g` ON g.id=t.gameid"
					."\n LEFT JOIN `#__mls_events` AS `e` ON e.id=t.eventid"
					."\n LEFT JOIN `#__mls_tournaments_participants` AS `p` ON p.tournamentid=t.id $where"
					."\n GROUP BY t.id"
					."\n ORDER BY t.name ASC");
	$database->query();
	$total = $database->getNumRows();
	
	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	
	// build the html select lists
	$category_select = HTML_MLS_tournaments::showCategorySelect($categoryid,$option,$act);
	$event_select = HTML_MLS_tournaments::showEventSelect($eventid,$option,$act);
	
	$database->setQuery( "SELECT t.*,c.name AS `categoryname`, g.name AS `gamename`, e.name AS `eventname`, SUM(IF(p.tournamentid=t.id,1,NULL)) AS `participants`"
					."\n FROM `#__mls_tournaments` AS `t`"
					."\n LEFT JOIN `#__mls_tournaments_categories` AS `c` ON c.id=t.categoryid"
					."\n LEFT JOIN `#__mls_tournaments_games` AS `g` ON g.id=t.gameid"
					."\n LEFT JOIN `#__mls_events` AS `e` ON e.id=t.eventid"
					."\n LEFT JOIN `#__mls_tournaments_participants` AS `p` ON p.tournamentid=t.id $where"
					."\n GROUP BY t.id"
					."\n ORDER BY t.name ASC"
					."\n LIMIT $pageNav->limitstart, $pageNav->limit");
	$rows = $database->loadObjectList();
	
	HTML_MLS_tournaments_tournaments::listTournaments($rows, $pageNav, $search, $category_select, $event_select, $option, $act);
}

function editMLS_tournaments_tournaments($id,$option,$act) {
	global $database, $my, $mainframe, $l;
	$l->setBlock("general");
	
	$row = new mosMLS_tournaments_tournament( $database );
	
	// load the row from the db table
	$row->load( $id );
	
	if ($id) {
		// do stuff for existing records
		
	} else {
		// do stuff for new records
		$row->registration = 0;
		$row->published = 0;
		$row->started = 0;
		$row->type = "C";
		$row->mode = "D";
		$row->player = 2;
		$row->maxplayer = "16";
		$row->categoryid = $mainframe->getUserState("filter_categoryid_tournaments{$option}");
		$row->eventid = $mainframe->getUserState("filter_eventid_tournaments{$option}");
	}
	
	//load leagues data
	$leaguesdata = new stdClass;
	$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues` WHERE `tournaments`='1' ORDER BY `name` ASC" );
	$leagues = $database->loadObjectList();
	foreach($leagues AS $league) {
		$name = $league->name;
		$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues_".$name."_tournaments` WHERE `parentid`='".$id."'" );
		$database->loadObject( $leaguesdata->$name );
	}
	
	
	
	// build the html select lists
	$lists = array();
	$database->setQuery( "SELECT `id`,`name` FROM `#__mls_tournaments_categories` ORDER BY `name` ASC" );
	$temp = $database->loadObjectList();
	$opt_cat[] = mosHTML::makeOption( '0', $l->m("select_category") );
	foreach($temp as $tmp) {
		$opt_cat[] = mosHTML::makeOption($tmp->id, $tmp->name);
	}
	$lists["categoryid"] = mosHTML::selectList($opt_cat, 'categoryid', ' class="inputbox"', 'value', 'text', $row->categoryid);
	
	$database->setQuery( "SELECT `id`,`name` FROM `#__mls_tournaments_games` ORDER BY `name` ASC" );
	$temp = $database->loadObjectList();
	$opt[] = mosHTML::makeOption( '0', $l->m("select_game") );
	foreach($temp as $tmp) {
		$opt[] = mosHTML::makeOption($tmp->id, $tmp->name);
	}
	$lists["gameid"] = mosHTML::selectList($opt, 'gameid', ' class="inputbox"', 'value', 'text', $row->gameid);
	
	$database->setQuery( "SELECT `id`,`name` FROM `#__mls_events` ORDER BY `name` ASC" );
	$temp = $database->loadObjectList();
	$opt_event[] = mosHTML::makeOption( '0', $l->m("select_event") );
	foreach($temp as $tmp) {
		$opt_event[] = mosHTML::makeOption($tmp->id, $tmp->name);
	}
	$lists["eventid"] = mosHTML::selectList($opt_event, 'eventid', ' class="inputbox"', 'value', 'text', $row->eventid);
	
	$lists["published"] = mosHTML::yesnoRadioList('published', ' class="inputbox"', $row->published);
	$lists["registration"] = mosHTML::yesnoRadioList('registration', ' class="inputbox"', $row->registration);
	$lists["started"] = mosHTML::yesnoRadioList('started', ' class="inputbox"', $row->started);
	
	$mode[] = mosHTML::makeOption( 'S', $l->m("single_elimination","tournaments") );
	$mode[] = mosHTML::makeOption( 'D', $l->m("double_elimination","tournaments") );
	$lists["mode"] = mosHTML::selectList($mode, 'mode', ' class="inputbox"', 'value', 'text', $row->mode);
	
	$type[] = mosHTML::makeOption( 'C', $l->m("clans","tournaments") );
	$type[] = mosHTML::makeOption( 'P', $l->m("singleplayer","tournaments") );
	$lists["type"] = mosHTML::selectList($type, 'type', ' class="inputbox"', 'value', 'text', $row->type);
	
	$maxplayer[] = mosHTML::makeOption( "4","4" );
	$maxplayer[] = mosHTML::makeOption( "8","8" );
	$maxplayer[] = mosHTML::makeOption( "16","16" );
	$maxplayer[] = mosHTML::makeOption( "32","32" );
	$maxplayer[] = mosHTML::makeOption( "64","64" );
	$maxplayer[] = mosHTML::makeOption( "128","128" );
	$maxplayer[] = mosHTML::makeOption( "256","256" );
	$maxplayer[] = mosHTML::makeOption( "512","512" );
	$lists["maxplayer"] = mosHTML::selectList($maxplayer, 'maxplayer', ' class="inputbox"', 'value', 'text', $row->maxplayer);
	
	//leagues
	$database->setQuery( "SELECT * FROM `#__mls_tournaments_leagues` WHERE `tournaments`='1' ORDER BY `name` ASC" );
	$temp = $database->loadObjectList();
	$opt = array();
	$opt[] = mosHTML::makeOption( '', '(none)' );
	foreach($temp as $tmp) {
		$opt[] = mosHTML::makeOption($tmp->name, $tmp->description);
	}
	$lists["league"] = mosHTML::selectList($opt, 'league', ' class="inputbox" size="1" onchange="selectLeague(this.value);"', 'value', 'text', $row->league);
	
	
	HTML_MLS_tournaments_tournaments::editTournament($row, $lists, $leaguesdata, $option, $act);
}

function saveMLS_tournaments_tournaments( $option, $act ) {
	global $database, $my, $mainframe, $l;
	
	
	$row = new mosMLS_tournaments_tournament( $database );
	if (!$row->bind( $_POST )) {
		if($error) echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	if($row->gameid == 0 AND $_POST["newgame_check"] == 1) {
		$database->setQuery( "INSERT INTO `#__mls_tournaments_games` (`name`) VALUES ('".$_POST["newgame"]."')" );
		$database->query();
		$row->gameid = $database->insertid();
	}
	if($row->categoryid == 0 AND $_POST["newcategory_check"] == 1) {
		$database->setQuery( "INSERT INTO `#__mls_tournaments_categories` (`name`) VALUES ('".$_POST["newcategory"]."')" );
		$database->query();
		$row->categoryid = $database->insertid();
	}
	if (!$row->check()) {
		if($error) echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->store()) {
		if($error) echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
	//Save league data
	if($row->league) {
		$class = "MLSTournaments_".$row->league."_tournaments";
		$tournamentleague = new $class( $database );
		$_POST[$row->league]["parentid"] = $row->id;
		
		$tournamentleague->bind( $_POST[$row->league] );
		$tournamentleague->store();
	}
	mosRedirect( "index2.php?option=$option&act=$act" );
}

function removeMLS_tournaments_tournaments( &$cid, $option, $act ) {
	global $database;

	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$database->setQuery( "DELETE FROM `#__mls_tournaments` WHERE `id` IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
		$database->setQuery( "DELETE FROM `#__mls_tournaments_participants` WHERE `tournamentid` IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
		$database->setQuery( "DELETE FROM `#__mls_tournaments_matches` WHERE `tournamentid` IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

	mosRedirect( "index2.php?option=$option&act=$act" );
}


/** Participants */
function listMLS_tournaments_participants($option, $act) {
	global $database, $my, $mainframe, $mosConfig_list_limit;
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', $mosConfig_list_limit );
	$limitstart = $mainframe->getUserStateFromRequest( "view_tournaments_{$option}limitstart", 'limitstart', 0 );
	$search = $mainframe->getUserStateFromRequest( "search_tournaments{$option}items", 'search', '' );
	$search = $database->getEscaped( trim( strtolower( $search ) ) );
	$tournamentid = $mainframe->getUserStateFromRequest( "filter_tournamentid_participants{$option}", 'tournamentid_filter', 0 );
	
	$where = "";
	$words = explode(" ",$search);
	foreach($words as $word) {
		if($word) {
			$op = $where ? "AND" : "WHERE";
			$where .= " $op (t.name LIKE '%$word%' OR c.name LIKE '%$word%' OR e.name LIKE '%$word%' OR u.username LIKE '%$word%' OR u.name LIKE '%$word%' OR team.name LIKE '%$word%')";
		}
	}
	$op = $where ? "AND" : "WHERE";
	$where .= $tournamentid ? " $op p.tournamentid = '$tournamentid'" : "";
	
	// get the total number of records
	$database->setQuery( "SELECT COUNT(p.id)"
					."\n FROM `#__mls_tournaments_participants`AS `p`"
					."\n INNER JOIN `#__mls_tournaments` AS `t` ON t.id=p.tournamentid"
					."\n INNER JOIN `#__mls_tournaments_categories` AS `c` ON c.id=t.categoryid"
					."\n INNER JOIN `#__mls_events` AS `e` ON e.id=t.eventid"
					."\n LEFT JOIN `#__users` AS `u` ON u.id=p.userid"
					."\n LEFT JOIN `#__mls_teams` AS `team` ON team.id=p.teamid $where" );
	$total = $database->loadResult();
	
	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	
	// build the html select lists
	$tournament_select = HTML_MLS_tournaments::showTournamentSelect($tournamentid,$option,$act);
	
	$database->setQuery( "SELECT p.*,t.name AS `tournamentname`,t.type AS `type`, e.name AS `eventname`,c.name AS `categoryname`,"
					."\n IF(t.type='C',team.name,CONCAT(u.name,' (',u.username,')')) AS `participantname`,"
					."\n u.username AS `username`, u.name AS `fullusername`,team.name AS `teamname`"
					."\n FROM `#__mls_tournaments_participants`AS `p`"
					."\n INNER JOIN `#__mls_tournaments` AS `t` ON t.id=p.tournamentid"
					."\n INNER JOIN `#__mls_tournaments_categories` AS `c` ON c.id=t.categoryid"
					."\n INNER JOIN `#__mls_events` AS `e` ON e.id=t.eventid"
					."\n LEFT JOIN `#__users` AS `u` ON u.id=p.userid"
					."\n LEFT JOIN `#__mls_teams` AS `team` ON team.id=p.teamid $where"
					."\n GROUP BY p.id"
					."\n ORDER BY e.name,t.name,u.name,team.name"
					."\n LIMIT $pageNav->limitstart, $pageNav->limit");
	$rows = $database->loadObjectList();
	
	HTML_MLS_tournaments_participants::listParticipants($rows, $pageNav, $search, $tournament_select, $option, $act);
}

function editMLS_tournaments_participants($id,$option,$act) {
	global $database, $my, $mainframe, $l;
	$l->setBlock("general");
	
	$row = new mosMLS_tournaments_participant( $database );
	
	// load the row from the db table
	$row->load( $id );
	
	if ($id) {
		// do stuff for existing records
		
	} else {
		// do stuff for new records
		$row->userid = 0;
		$row->teamid = 0;
		$row->tournamentid = $mainframe->getUserState("filter_tournamentid_participants{$option}");
	}
	
	// build the html select lists
	$lists = array();
	$database->setQuery( "SELECT t.id,t.name,c.name as `categoryname`, e.name AS `eventname`"
					."\n FROM `#__mls_tournaments` AS `t`"
					."\n INNER JOIN `#__mls_tournaments_categories` AS `c` ON c.id=t.categoryid"
					."\n INNER JOIN `#__mls_events` AS `e` ON e.id=t.eventid"
					."\n ORDER BY e.name,c.name,t.name" );
	$temp = $database->loadObjectList();
	$opt_cat[] = mosHTML::makeOption( '0', $l->m("select_tournament") );
	foreach($temp as $tmp) {
		$opt_cat[] = mosHTML::makeOption($tmp->id, $tmp->eventname." &gt;&gt; ".$tmp->categoryname." &gt;&gt; ".$tmp->name);
	}
	$lists["tournamentid"] = mosHTML::selectList($opt_cat, 'tournamentid', ' class="inputbox"', 'value', 'text', $row->tournamentid);
	
	$database->setQuery( "SELECT `id`,`name` FROM `#__mls_teams` ORDER BY `name` ASC" );
	$temp = $database->loadObjectList();
	$opt_teams[] = mosHTML::makeOption( '0', $l->m("select_team") );
	foreach($temp as $tmp) {
		$opt_teams[] = mosHTML::makeOption($tmp->id, $tmp->name);
	}
	$lists["teamid"] = mosHTML::selectList($opt_teams, 'teamid', ' class="inputbox"', 'value', 'text', $row->teamid);
	
	$database->setQuery( "SELECT `id`,`username`,`name` FROM `#__users` ORDER BY `username` ASC" );
	$temp = $database->loadObjectList();
	$opt_users[] = mosHTML::makeOption( '0', $l->m("select_user") );
	foreach($temp as $tmp) {
		$opt_users[] = mosHTML::makeOption($tmp->id, $tmp->name . " (".$tmp->username.")");
	}
	$lists["userid"] = mosHTML::selectList($opt_users, 'userid', ' class="inputbox"', 'value', 'text', $row->userid);
	
	HTML_MLS_tournaments_participants::editParticipants($row, $lists, $option, $act);
}

function saveMLS_tournaments_participants($option,$act) {
	global $database, $my, $mainframe;
	
	$row = new mosMLS_tournaments_participant( $database );
	if (!$row->bind( $_POST )) {
		if($row->_error) echo "<script> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}
	if (!$row->check()) {
		if($row->_error) echo "<script> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}
	if (!$row->store()) {
		if($row->_error) echo "<script> alert('".$row->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}
	mosRedirect( "index2.php?option=$option&act=$act" );
}

function removeMLS_tournaments_participants( &$cid, $option, $act ) {
	global $database;

	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$database->setQuery( "DELETE FROM `#__mls_tournaments_participants` WHERE `id` IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

	mosRedirect( "index2.php?option=$option&act=$act" );
}

/** Brackets */
function listMLS_tournaments_brackets( $option, $act ) {
	global $database, $my, $mainframe, $l;
	$l->setBlock("brackets");
	
	$limit = $mainframe->getUserStateFromRequest( "viewlistlimit", 'limit', 10 );
	$limitstart = $mainframe->getUserStateFromRequest( "view_tournaments_{$option}limitstart", 'limitstart', 0 );
	$search = $mainframe->getUserStateFromRequest( "search_tournaments{$option}items", 'search', '' );
	$search = $database->getEscaped( trim( strtolower( $search ) ) );
	$tournamentid = $mainframe->getUserStateFromRequest( "filter_tournamentid_brackets{$option}", 'tournamentid_filter', 0 );
	$bracket = $mainframe->getUserStateFromRequest( "filter_bracket_brackets{$option}", 'bracket_filter', '0' );
	
	$where = "";
	$words = explode(" ",$search);
	foreach($words as $word) {
		if($word) {
			$op = $where ? "AND" : "WHERE";
			$where .= " $op (t.name LIKE '%$word%' OR c.name LIKE '%$word%' OR e.name LIKE '%$word%' OR u1.username LIKE '%$word%' OR u2.username LIKE '%$word%' OR team2.name LIKE '%$word%'OR team1.name LIKE '%$word%')";
		}
	}
	$op = $where ? "AND" : "WHERE";
	$where .= $tournamentid ? " $op m.tournamentid = '$tournamentid'" : "";
	$op = $where ? "AND" : "WHERE";
	$where .= $bracket ? " $op m.bracket = '$bracket'" : "";
	
	// get the total number of records
	$database->setQuery( "SELECT m.*,"
					."\n t.name AS `tournamentname`, t.type AS `tournamenttype`,"
					."\n e.name AS `eventname`,"
					."\n c.name AS `categoryname`,"
					."\n IF(m.clan1id='F','".$l->m("default_win")."',IF(t.type='P',CONCAT(u1.name,' (',u1.username,')'),team1.name)) AS `player1_name`,"
					."\n m.clan1id AS `player1_id`,"
					."\n IF(m.clan2id='F','".$l->m("default_win")."',IF(t.type='P',CONCAT(u2.name,' (',u2.username,')'),team2.name)) AS `player2_name`,"
					."\n m.clan2id AS `player2_id`"
					."\n FROM `#__mls_tournaments_matches` AS `m`"
					."\n INNER JOIN `#__mls_tournaments` AS `t` ON t.id=m.tournamentid"
					."\n INNER JOIN `#__mls_tournaments_categories` AS `c` ON c.id=t.categoryid"
					."\n INNER JOIN `#__mls_events` AS `e` ON e.id=t.eventid"
					."\n LEFT JOIN `#__users` AS `u1` ON u1.id=m.clan1id"
					."\n LEFT JOIN `#__users` AS `u2` ON u2.id=m.clan2id"
					."\n LEFT JOIN `#__mls_teams` AS `team1` ON team1.id=m.clan1id"
					."\n LEFT JOIN `#__mls_teams` AS `team2` ON team2.id=m.clan2id $where"
					."\n GROUP BY m.id"
					."\n ORDER BY e.name,t.name,m.bracket,m.roundnr,m.matchnr");
	$database->query();
	$total = $database->getNumRows();
	
	require_once( "includes/pageNavigation.php" );
	$pageNav = new mosPageNav( $total, $limitstart, $limit  );
	
	// build the html select lists
	$tournament_select = HTML_MLS_tournaments::showTournamentSelect($tournamentid,$option,$act);
	$bracket_select = HTML_MLS_tournaments::showBracketSelect($bracket,$option,$act);
	
	$database->setQuery( "SELECT m.*,"
					."\n t.name AS `tournamentname`, t.type AS `tournamenttype`,"
					."\n e.name AS `eventname`,"
					."\n c.name AS `categoryname`,"
					."\n IF(m.clan1id='F','".$l->m("default_win")."',IF(t.type='P',CONCAT(u1.name,' (',u1.username,')'),team1.name)) AS `player1_name`,"
					."\n IF(t.type='P',u1.id,team1.id) AS `player1_id`,"
					."\n IF(m.clan2id='F','".$l->m("default_win")."',IF(t.type='P',CONCAT(u2.name,' (',u2.username,')'),team2.name)) AS `player2_name`,"
					."\n IF(t.type='P',u2.id,team2.id) AS `player2_id`"
					."\n FROM `#__mls_tournaments_matches` AS `m`"
					."\n INNER JOIN `#__mls_tournaments` AS `t` ON t.id=m.tournamentid"
					."\n INNER JOIN `#__mls_tournaments_categories` AS `c` ON c.id=t.categoryid"
					."\n INNER JOIN `#__mls_events` AS `e` ON e.id=t.eventid"
					."\n LEFT JOIN `#__users` AS `u1` ON u1.id=m.clan1id"
					."\n LEFT JOIN `#__users` AS `u2` ON u2.id=m.clan2id"
					."\n LEFT JOIN `#__mls_teams` AS `team1` ON team1.id=m.clan1id"
					."\n LEFT JOIN `#__mls_teams` AS `team2` ON team2.id=m.clan2id $where"
					."\n GROUP BY m.id"
					."\n ORDER BY e.name,t.name,m.bracket,m.roundnr,m.matchnr"
					."\n LIMIT $pageNav->limitstart, $pageNav->limit");
	$rows = $database->loadObjectList();
	
	HTML_MLS_tournaments_brackets::listBrackets($rows, $pageNav, $search, $tournament_select, $bracket_select, $option, $act);
}

function removeMLS_tournaments_brackets( &$cid, $option, $act ) {
	global $database;

	if (count( $cid )) {
		$cids = implode( ',', $cid );
		$database->setQuery( "DELETE FROM `#__mls_tournaments_matches` WHERE `id` IN ($cids)" );
		if (!$database->query()) {
			echo "<script> alert('".$database->getErrorMsg()."'); window.history.go(-1); </script>\n";
		}
	}

	mosRedirect( "index2.php?option=$option&act=$act" );
}

function editMLS_tournaments_brackets( $id, $option, $act ) {
	global $database, $mainframe, $l;
	$l->setBlock("brackets");
	$row = new mosMLS_tournaments_match( $database );
	$row->load( $id );
	
	$t = new mosMLS_tournaments_tournament( $database );
	$t->load( $row->tournamentid );
	
	if($row->id) {
		//stuff for editing
	} else {
		//stuff for adding
		$row->tournamentid = $mainframe->getUserState("filter_tournamentid_brackets{$option}");
		$row->bracket = $mainframe->getUserState("filter_bracket_brackets{$option}");
	}
	
	
	//HTML select lists
	$lists = array();
	$lists["clan1_checkin"] = mosHTML::yesnoRadioList('clan1_checkin', ' class="inputbox"', $row->clan1_checkin);
	$lists["clan2_checkin"] = mosHTML::yesnoRadioList('clan2_checkin', ' class="inputbox"', $row->clan2_checkin);
	$lists["clan1_submit"] = mosHTML::yesnoRadioList('clan1_submit', ' class="inputbox"', $row->clan1_submit);
	$lists["clan2_submit"] = mosHTML::yesnoRadioList('clan2_submit', ' class="inputbox"', $row->clan2_submit);
	$lists["result_submit"] = mosHTML::yesnoRadioList('result_submit', ' class="inputbox"', $row->result_submit);
	
	$database->setQuery( "SELECT t.id,t.name,c.name as `categoryname`, e.name AS `eventname`"
					."\n FROM `#__mls_tournaments` AS `t`"
					."\n INNER JOIN `#__mls_tournaments_categories` AS `c` ON c.id=t.categoryid"
					."\n INNER JOIN `#__mls_events` AS `e` ON e.id=t.eventid"
					."\n ORDER BY e.name,c.name,t.name" );
	$temp = $database->loadObjectList();
	$opt_cat[] = mosHTML::makeOption( '0', $l->m("select_tournament","general") );
	foreach($temp as $tmp) {
		$opt_cat[] = mosHTML::makeOption($tmp->id, $tmp->eventname." &gt;&gt; ".$tmp->categoryname." &gt;&gt; ".$tmp->name);
	}
	$lists["tournamentid"] = mosHTML::selectList($opt_cat, 'tournamentid', ' class="inputbox"', 'value', 'text', $row->tournamentid);
	
	$opt = array();
	$opt[] = mosHTML::makeOption('0',$l->m("select_bracket","general"));
	$opt[] = mosHTML::makeOption('w',$l->m("winner"));
	$opt[] = mosHTML::makeOption('l',$l->m("loser"));
	$opt[] = mosHTML::makeOption('c',$l->m("custom"));
	
	$lists["bracket"] = mosHTML::selectList($opt, 'bracket', ' class="inputbox"', 'value', 'text', $row->bracket);
	
	$t = new mosMLS_tournaments_tournament( $database );
	$t->load($row->tournamentid);
	if($t->type == "C") {
		//this is a clans tournament, load clans
		$database->setQuery( "SELECT DISTINCT p.teamid AS `id`,t.name AS `name`"
						."\n FROM `#__mls_tournaments_participants` AS `p`"
						."\n INNER JOIN `#__mls_teams` AS `t` ON t.id=p.teamid"
						."\n ORDER BY t.name ASC" );
		$players = $database->loadObjectList();
		$opt_player[] = mosHTML::makeOption( '0', $l->m("select_team","general") );
	} else {
		//this is a singleplayer tournament, load users
		$database->setQuery( "SELECT DISTINCT p.userid AS `id`,CONCAT(t.name,' (',t.username,')') AS `name`"
						."\n FROM `#__mls_tournaments_participants` AS `p`"
						."\n INNER JOIN `#__users` AS `t` ON t.id=p.userid"
						."\n ORDER BY t.name ASC" );
		$players = $database->loadObjectList();
		$opt_player[] = mosHTML::makeOption( '0', $l->m("select_user","general") );
	}
	$opt_player[] = mosHTML::makeOption( 'F', $l->m("default_win") );
	foreach($players as $p) {
		$opt_player[] = mosHTML::makeOption($p->id, $p->name );
	}
	$lists["clan1id"] = mosHTML::selectList($opt_player, 'clan1id', ' class="inputbox"', 'value', 'text', $row->clan1id);
	$lists["clan2id"] = mosHTML::selectList($opt_player, 'clan2id', ' class="inputbox"', 'value', 'text', $row->clan2id);
	
	$database->setQuery( "SELECT `id`, `name` FROM `#__mls_tournaments_servers` WHERE `gameid`='".$t->gameid."' ORDER BY `name` ASC" );
	$temp = $database->loadObjectList();
	$opt = array();
	$opt[] = mosHTML::makeOption( '0', $l->m("select_server","general") );
	foreach($temp as $tmp) {
		$opt[] = mosHTML::makeOption( $tmp->id, $tmp->name );
	}
	$lists["serverid"] = mosHTML::selectList($opt, 'serverid', ' class="inputbox"', 'value', 'text', $row->serverid);
	HTML_MLS_tournaments_brackets::editBrackets($row, $lists, $option, $act);
}

function saveMLS_tournaments_brackets($option,$act) {
	global $database, $my, $mainframe;
	
	$row = new mosMLS_tournaments_match( $database );
	if (!$row->bind( $_POST )) {
		if($error) echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->check()) {
		if($error) echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	if (!$row->store()) {
		if($error) echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	mosRedirect( "index2.php?option=$option&act=$act" );
}

function submitMLS_tournaments_brackets($id, $option, $act) {
	global $database, $mainframe, $l, $my;
	$l->setBlock("brackets");
	$database->setQuery( "SELECT m.*,"
					."\n t.name AS `tournamentname`, t.type AS `tournamenttype`,"
					."\n e.name AS `eventname`,"
					."\n c.name AS `categoryname`,"
					."\n IF(m.clan1id='F','".$l->m("default_win")."',IF(t.type='P',CONCAT(u1.name,' (',u1.username,')'),team1.name)) AS `player1_name`,"
					."\n IF(t.type='P',u1.id,team1.id) AS `player1_id`,"
					."\n IF(m.clan2id='F','".$l->m("default_win")."',IF(t.type='P',CONCAT(u2.name,' (',u2.username,')'),team2.name)) AS `player2_name`,"
					."\n IF(t.type='P',u2.id,team2.id) AS `player2_id`"
					."\n FROM `#__mls_tournaments_matches` AS `m`"
					."\n INNER JOIN `#__mls_tournaments` AS `t` ON t.id=m.tournamentid"
					."\n INNER JOIN `#__mls_tournaments_categories` AS `c` ON c.id=t.categoryid"
					."\n INNER JOIN `#__mls_events` AS `e` ON e.id=t.eventid"
					."\n LEFT JOIN `#__users` AS `u1` ON u1.id=m.clan1id"
					."\n LEFT JOIN `#__users` AS `u2` ON u2.id=m.clan2id"
					."\n LEFT JOIN `#__mls_teams` AS `team1` ON team1.id=m.clan1id"
					."\n LEFT JOIN `#__mls_teams` AS `team2` ON team2.id=m.clan2id"
					."\n WHERE m.id = '".$id."'" );
	$database->loadObject($row);
	
	HTML_MLS_tournaments_brackets::submitResults($row, $option, $act);
}

function save_resultsMLS_tournaments_brackets( $option, $act ) {
	global $database, $mainframe, $l, $my;
	$l->setBlock("general");
	/** first, load the match and tournament */
	$match = new mosMLS_tournaments_match( $database );
	$match->load( $_POST["id"] );
	if(!$match->submitResults($_POST["id"], $_POST["clan1_result"], $_POST["clan2_result"])) {
		if($match->_error) echo "<script> alert('".$match->getError()."'); window.history.go(-2); </script>\n";
		exit();
	}
	
	$match->makeDefwins();
	mosRedirect( "index2.php?option=$option&act=$act" );
}

?>