<?php
/*
 ########################################################################
#                                                                        #
#           Version 4       /                        /   /               #
#          -----------__---/__---__------__----__---/---/-               #
#           | /| /  /___) /   ) (_ `   /   ) /___) /   /                 #
#          _|/_|/__(___ _(___/_(__)___/___/_(___ _/___/___               #
#                       Free Content / Management System                 #
#                                   /                                    #
#                                                                        #
#                                                                        #
#   Copyright 2005-2006 by webspell.org                                  #
#                                                                        #
#   visit webSPELL.org, webspell.info to get webSPELL for free           #
#   - Script runs under the GNU GENERAL PUBLIC LICENSE                   #
#   - It's NOT allowed to remove this copyright-tag                      #
#   -- http://www.fsf.org/licensing/licenses/gpl.html                    #
#                                                                        #
#   Code based on WebSPELL Clanpackage (Michael Gruber - webspell.at),   #
#   Far Development by Development Team - webspell.org                   #
#                                                                        #
#   visit webspell.org                                                   #
#                                                                        #
 ########################################################################
*/

if($_GET['action']=="new") {
	include("_mysql.php");
	include("_settings.php");
	include("_functions.php");
	
  if(!isanyadmin($userID)) die('no access!');

	$pagebg=PAGEBG;
	$border=BORDER;
	$bghead=BGHEAD;
	$bgcat=BGCAT;
	
	$upID = $_GET['upID'];
	
	if(isclanwaradmin($userID)) {
		$squads=getgamesquads();
		$jumpsquads=str_replace('value="', 'value="index.php?site=clanwars&action=showonly&only=squad&id=', $squads);

		$gamesa=safe_query("SELECT * FROM ".PREFIX."games ORDER BY name");
 		while($ds=mysql_fetch_array($gamesa)) {
		 $games.='<option value="'.$ds[tag].'">'.$ds[name].'</option>';
		}
		
		$gamesquads=safe_query("SELECT * FROM ".PREFIX."squads WHERE gamesquad='1' ORDER BY sort");
		while($ds=mysql_fetch_array($gamesquads)) {
			$hometeam.='<option value="0">'.$ds[name].'</option>';
			$squadmembers=safe_query("SELECT * FROM ".PREFIX."squads_members WHERE squadID='$ds[squadID]' ORDER BY sort");
			while($dm=mysql_fetch_array($squadmembers)) {
				$hometeam.='<option value="'.$dm[userID].'">&nbsp; - '.getnickname($dm[userID]).'</option>';
			}
			$hometeam.='<option value="0">&nbsp;</option>';
		}

		echo'<script src="js/bbcode.js" language="jscript" type="text/javascript"></script>
			 <link href="_stylesheet.css" rel="stylesheet" type="text/css">';
		
		for($i=1; $i<32; $i++) {
		    if($i==date("d", time())) $day.='<option selected>'.$i.'</option>';
			else $day.='<option>'.$i.'</option>';
		}
		for($i=1; $i<13; $i++) {
		    if($i==date("n", time())) $month.='<option value="'.$i.'" selected>'.date("M", time()).'</option>';
			else $month.='<option value="'.$i.'">'.date("M", mktime(0,0,0,$i,1,2000)).'</option>';
		}
		for($i=2000; $i<2010; $i++) {
		    if($i==date("Y", time())) $year.='<option value="'.$i.'" selected>'.date("Y", time()).'</option>';
			else $year.='<option value="'.$i.'">'.$i.'</option>';
		}
				
		$leaguehp="http://";
		$opphp="http://";
		$linkpage="http://";
		
		if($upID) {
			$ergebnis=safe_query("SELECT * FROM ".PREFIX."upcoming WHERE upID='$upID'");
			$ds=mysql_fetch_array($ergebnis);
			$league=$ds[league];
			if($ds[leaguehp] != $leaguehp) $leaguehp=$ds[leaguehp];
			$opponent=$ds[opponent];
			$opptag=$ds[opptag];
			if($ds[opphp] != $opphp) $opphp=$ds[opphp];
			$countries=str_replace(" selected", "", $countries);
			$countries=str_replace('value="'.$ds[oppcountry].'"', 'value="'.$ds[oppcountry].'" selected', $countries);
			
			$squads=str_replace(" selected", "", $squads);
			$squads=str_replace('value="'.$ds[squad].'"', 'value="'.$ds[squad].'" selected', $squads);
			
			$day=str_replace(" selected", "", $day);
			$day=str_replace('<option>'.date("j", $ds[date]).'</option>', '<option selected>'.date("j", $ds[date]).'</option>', $day);
			$month=str_replace(" selected", "", $month);
			$month=str_replace('value="'.date("n", $ds[date]).'"', 'value="'.date("n", $ds[date]).'" selected', $month);
			$year=str_replace(" selected", "", $year);
			$year=str_replace('value="'.date("Y", $ds[date]).'"', 'value="'.date("Y", $ds[date]).'" selected', $year);
		}
	
		$bg1=BG_1;
		eval ("\$clanwar_new = \"".gettemplate("clanwar_new")."\";");
	  echo $clanwar_new;  
	}
	else redirect('index.php?site=clanwars', 'no access!');
}
elseif($_GET['action']=="save") {
	include("_mysql.php");
	include("_settings.php");
	include("_functions.php");
  if(!isanyadmin($userID)) die('no access!');
	
	$pagebg=PAGEBG;
	$border=BORDER;
	$bghead=BGHEAD;
	$bgcat=BGCAT;	

	echo'<script src="js/bbcode.js" language="jscript" type="text/javascript"></script>
		 <link href="_stylesheet.css" rel="stylesheet" type="text/css">';

  $month = $_POST['month'];
  $day = $_POST['day'];
  $year = $_POST['year'];
  $hometeam = $_POST['hometeam'];
  $squad = $_POST['squad'];
  $game = $_POST['game'];
  $league = $_POST['league'];
  $leaguehp = $_POST['leaguehp'];
  $opponent = $_POST['opponent'];
  $opptag = $_POST['opptag'];
  $oppcountry = $_POST['oppcountry'];
  $opphp = $_POST['opphp'];
  $oppteam = $_POST['oppteam'];
  $server = $_POST['server'];
	$hltv = $_POST['hltv'];
  $report = $_POST['report'];
  $comments = $_POST['comments'];
  $linkpage = $_POST['linkpage'];
  $news=$_POST['news'];
	
	// v1.0 -- EXTENDED CLANWAR RESULTS
  $maplist = $_POST['map_name'];
	$homescr = $_POST['map_result_home'];
	$oppscr = $_POST['map_result_opp'];
	
	if(!empty($maplist)) {
		if(is_array($maplist)) {
			$maps = array();
			foreach($maplist as $map) {
				$maps[]=$map;
			}
			$theMaps = implode("||", $maps);
		} else $theMaps='';
	}
	if(!empty($homescr)) {
		if(is_array($homescr)) {
			$results = array();
			foreach($homescr as $result) {
				$results[]=$result;
			}
			$theHomeScore=implode("||", $results);
		} else $theHomeScore='';
		unset($results);
	}
	if(!empty($oppscr)) {
		if(is_array($oppscr)) {
			$results = array();
			foreach($oppscr as $result) {
				$results[]=$result;
			}
			$theOppScore=implode("||", $results);
		} else $theOppScore='';
		unset($results);
	}
	if(is_array($hometeam)) {
		$team=array();
		foreach($hometeam as $player) {
			if(!in_array($player, $team)) $team[]=$player;
		}
		$home_string=implode("|", $team);
	} else $home_string='';
	
	$date=mktime(0,0,0,$month,$day,$year);

	mysql_query("INSERT INTO ".PREFIX."clanwars ( date, squad, game, league, leaguehp, opponent, opptag, oppcountry, opphp, maps, hometeam, oppteam, server, hltv, homescore, oppscore, report, comments, linkpage)
                 VALUES( '$date', '$squad', '$game', '".mysql_escape_string($league)."', '$leaguehp', '".mysql_escape_string($opponent)."', '".mysql_escape_string($opptag)."', '$oppcountry', '$opphp', '".mysql_escape_string($theMaps)."', '$home_string', '$oppteam', '$server', '$hltv', '$theHomeScore', '$theOppScore', '".mysql_escape_string($report)."', '$comments', '$linkpage' ) ");

	$cwID=mysql_insert_id();
	$date=date("d.m.Y", $date);

	// INSERT CW-NEWS
	if($news) {
		safe_query("INSERT INTO ".PREFIX."news (date, poster, saved, cwID) VALUES ('".time()."', '$userID', '0', '$cwID')");
		$newsID=mysql_insert_id();
		
		$newsrubrics=safe_query("SELECT rubricID, rubric FROM ".PREFIX."news_rubrics ORDER BY rubric");
	    while($dr=mysql_fetch_array($newsrubrics)) {
		    $rubrics.='<option value="'.$dr[rubricID].'">'.$dr[rubric].'</option>';
		}

		$lang=safe_query("SELECT lang, language FROM ".PREFIX."news_languages ORDER BY language");
		while($dl=mysql_fetch_array($lang)) {
		    if($dl[lang]=="de") $langs1.='<option value="'.$dl[lang].'" selected>'.$dl[language].'</option>';
			else $langs1.='<option value="'.$dl[lang].'">'.$dl[language].'</option>';
			
			if($dl[lang]=="uk") $langs2.='<option value="'.$dl[lang].'" selected>'.$dl[language].'</option>';
			else $langs2.='<option value="'.$dl[lang].'">'.$dl[language].'</option>';
		}
		
		$squad=getsquadname($squad);
		$link1=$opptag;
		$url1=$opphp;
		$link2=$league;
		$url2=$leaguehp;
		$url3="http://";
		$url4="http://";
		
		$headline1='War '.$squad.' vs. '.$opponent.' '.$result2;
		if($url1!='http://' AND !(empty($url1))) $opponent='[url='.$opphp.'][b]'.$opptag.' / '.$opponent.'[/b][/url]';
		else $opponent='[b]'.$opptag.' / '.$opponent.'[/b]';
		if($url2!='http://' AND !(empty($url2))) $league='[url='.$leaguehp.']'.$league.'[/url]';
		
		// v1.0 -- PREPARE CW-NEWS OUTPUT
		$maps=explode("||", $theMaps);
		$scoreHome=explode("||", $theHomeScore);
		$scoreOpp=explode("||", $theOppScore);
		$homescr=array_sum($scoreHome);
		$oppscr=array_sum($scoreOpp);
		
		if($homescr>$oppscr) {
			$results='[color='.$wincolor.'][b]'.$homescr.':'.$oppscr.'[/b][/color]';
			$result2='won';
		}
		elseif($homescr<$oppscr) {
			$results='[color='.$loosecolor.'][b]'.$homescr.':'.$oppscr.'[/b][/color]';
			$result2='lost';
		}
		else {
			$results='[color='.$drawcolor.'][b]'.$homescr.':'.$oppscr.'[/b][/color]';
			$result2='draw';
		}
		
		// v1.0 -- CREATE CW-NEWS EXTENDED RESULTS
		if(is_array($maps)) {
			$d=0;
			$results_ext='[TOGGLE=Results (extended)]';
			foreach($maps as $map) {
				if($scoreHome[$d] > $scoreOpp[$d]) $score.='<td colspan="2">[color='.$wincolor.'][b]'.$scoreHome[$d].'[/b][/color] : [color='.$loosecolor.'][b]'.$scoreOpp[$d].'[/b][/color]</td>';
				elseif($scoreHome[$d] < $scoreOpp[$d]) $score.='<td colspan="2">[color='.$loosecolor.'][b]'.$scoreHome[$d].'[/b][/color] : [color='.$wincolor.'][b]'.$scoreOpp[$d].'[/b][/color]</td>';
				else $score.='<td colspan="2">[color='.$drawcolor.'][b]'.$scoreHome[$d].'[/b][/color] : [color='.$drawcolor.'][b]'.$scoreOpp[$d].'[/b][/color]</td>';
				$d++;
				eval ("\$news_cw_results = \"".gettemplate("news_cw_results")."\";");
				$results_ext.=$news_cw_results;
				unset($score);
			}
			$results_ext.='[/TOGGLE]';
		}
		
		if(!empty($report)) $more1='[TOGGLE=Report]'.$report.'[/TOGGLE]';
				
		if(is_array($team)) {
			$n=1;
			foreach($team as $id) {
				if(!empty($id)) {
					if($n>1) $home.=', <a href="index.php?site=profile&id='.$id.'">'.getnickname($id).'</a>';
					else $home='<a href="index.php?site=profile&id='.$id.'">'.getnickname($id).'</a>';
					$n++;
				}
			}
		}
			
		$message='Clanwar against [flag]'.$oppcountry.'[/flag] '.$opponent.' on '.$date.'
		
League: '.$league.'
Result: '.$results.'
'.$results_ext.'
'.$myclantag.' Team: '.$home.'
'.$opptag.' Team: '.$oppteam.'

'.$more1.'
<a href="index.php?site=clanwars_details&cwID='.$cwID.'">Clanwardetails</a>';
		
		$bg1=BG_1;
		
		eval ("\$addbbcode = \"".gettemplate("addbbcode")."\";");
		eval ("\$addflags = \"".gettemplate("flags")."\";");
		
		eval ("\$news_post = \"".gettemplate("news_post")."\";");
		echo $news_post;
		
	}
	else echo'<center><br><br><br><br>
			  <b>Clanwar has been saved.</b><br><br>
			  <input type="button" class="button" onClick="MM_goToURL(\'parent\',\'upload.php?cwID='.$cwID.'\');return document.MM_returnValue" value="upload screenshots">
			  <input type="button" class="button" onClick="javascript:self.close()" value="close window"></center>';
}
elseif($_GET['action']=="edit") {
	include("_mysql.php");
	include("_settings.php");
	include("_functions.php");
  if(!isanyadmin($userID)) die('no access!');
  
	$pagebg=PAGEBG;
	$border=BORDER;
	$bghead=BGHEAD;
	$bgcat=BGCAT;
	
	$cwID = $_GET['cwID'];
	
	if(isclanwaradmin($userID)) {
		$squads=getgamesquads();
		$jumpsquads=str_replace('value="', 'value="index.php?site=clanwars&action=showonly&only=squad&id=', $squads);

    $ds=mysql_fetch_array(safe_query("SELECT * FROM ".PREFIX."clanwars WHERE cwID='$cwID'"));

		$gamesa=safe_query("SELECT tag, name FROM ".PREFIX."games ORDER BY name");
 		while($dv=mysql_fetch_array($gamesa)) {
		 $games.='<option value="'.$dv[tag].'">'.$dv[name].'</option>';
		}

		echo'
			<script src="js/bbcode.js" language="jscript" type="text/javascript"></script>
			<link href="_stylesheet.css" rel="stylesheet" type="text/css">';
		
		
		for($i=1; $i<32; $i++) {
			if($i==date("d", $ds[date])) $day.='<option selected>'.$i.'</option>';
			else $day.='<option>'.$i.'</option>';
		}
		for($i=1; $i<13; $i++) {
			if($i==date("n", $ds[date])) $month.='<option value="'.$i.'" selected>'.date("M", $ds[date]).'</option>';
			else $month.='<option value="'.$i.'">'.date("M", mktime(0,0,0,$i,1,2000)).'</option>';
		}
		for($i=2000; $i<2010; $i++) {
			if($i==date("Y", $ds[date])) $year.='<option selected>'.$i.'</option>';
			else $year.='<option>'.$i.'</option>';
		}
		$games=str_replace('value="'.$ds[game].'"', 'value="'.$ds[game].'" selected', $games);
		$squads=getgamesquads();
		$squads=str_replace('value="'.$ds[squadID].'"', 'value="'.$ds[squadID].'" selected', $squads);
		$league=$ds[league];
		$leaguehp=$ds[leaguehp];
		$opponent=$ds[opponent];
		$opptag=$ds[opptag];
		$countries=str_replace('value="at" selected', 'value="at"', $countries);
		$countries=str_replace('value="'.$ds[oppcountry].'"', 'value="'.$ds[oppcountry].'" selected', $countries);
		$opphp=$ds[opphp];
		$oppteam=$ds[oppteam];
		$server=$ds[server];
		$hltv=$ds[hltv];
		$linkpage=$ds[linkpage];
		$report=$ds[report];
  	$linkpage=$ds[linkpage];
					
		// map-output, v1.0
		$map=explode("||", $ds[maps]);
		$theHomeScore=explode("||", $ds[homescore]);
		$theOppScore=explode("||", $ds[oppscore]);
		$i=0;
		for($i=0; $i<count($map); $i++) {
			$maps.='
			<input type="hidden" name="map_id[]" value="'.$i.'">
			<tr>
				<td width="10%">map #'.($i+1).'</td>
				<td width="25%"><input type="text" name="map_name[]" value="'.$map[$i].'" size="35" class="form_off" onFocus="this.className=\'form_on\'" onBlur="this.className=\'form_off\'"></td>
				<td width="20%"><input type="text" name="map_result_home[]" value="'.$theHomeScore[$i].'" size="3" class="form_off" onFocus="this.className=\'form_on\'" onBlur="this.className=\'form_off\'"></td>
				<td width="20%"><input type="text" name="map_result_opp[]" value="'.$theOppScore[$i].'" size="3" class="form_off" onFocus="this.className=\'form_on\'" onBlur="this.className=\'form_off\'"></td>
				<td width="25%"><input type="checkbox" name="delete[]" value="1" class="form_off" onFocus="this.className=\'form_on\'" onBlur="this.className=\'form_off\'"> delete</td>
			</tr>
			';
		}
		
		$gamesquads=safe_query("SELECT * FROM ".PREFIX."squads WHERE gamesquad='1' ORDER BY sort");
		while($dq=mysql_fetch_array($gamesquads)) {
			$hometeam.='<option value="0">'.$dq[name].'</option>';
			$squadmembers=safe_query("SELECT * FROM ".PREFIX."squads_members WHERE squadID='$dq[squadID]' ORDER BY sort");
			while($dm=mysql_fetch_array($squadmembers)) {
				$hometeam.='<option value="'.$dm[userID].'">&nbsp; - '.getnickname($dm[userID]).'</option>';
			}
			$hometeam.='<option value="0">&nbsp;</option>';
		}
		
		if(!empty($ds[hometeam])) {
			$array=explode("|", $ds[hometeam]);
			foreach($array as $id) {
				if(!empty($id)) $hometeam=str_replace('value="'.$id.'"', 'value="'.$id.'" selected', $hometeam);
			}
		}
						
		$comments='<option value="0">disable comments</option><option value="1">enable user comments</option><option value="2">enable visitor comments</option>';								
		$comments=str_replace('value="'.$ds[comments].'"', 'value="'.$ds[comments].'" selected', $comments);
	
		$bg1=BG_1;
		eval ("\$clanwar_edit = \"".gettemplate("clanwar_edit")."\";");
	  echo $clanwar_edit;      
	}
	else redirect('index.php?site=clanwars', 'no access!');
}
elseif($_GET['action']=="saveedit") {
	include("_mysql.php");
	include("_settings.php");
	include("_functions.php");
  if(!isanyadmin($userID)) die('no access!');

  $cwID = $_POST['cwID'];
  $month = $_POST['month'];
  $day = $_POST['day'];
  $year = $_POST['year'];
  $hometeam = $_POST['hometeam'];
  $squad = $_POST['squad'];
  $game = $_POST['game'];
  $league = $_POST['league'];
  $leaguehp = $_POST['leaguehp'];
  $opponent = $_POST['opponent'];
  $opptag = $_POST['opptag'];
  $oppcountry = $_POST['oppcountry'];
  $opphp = $_POST['opphp'];
  $oppteam = $_POST['oppteam'];
  $server = $_POST['server'];
	$hltv = $_POST['hltv'];
  $report = $_POST['report'];
  $comments = $_POST['comments'];
  $linkpage = $_POST['linkpage'];
	$maplist = $_POST['map_name'];
	$homescr = $_POST['map_result_home'];
	$oppscr = $_POST['map_result_opp'];
	$delete = $_POST['delete'];
	
	// v1.0 -- MAP-REMOVAL
	foreach($maplist as $key=>$map) {
		if(!$delete[$key]) {
			$theMaps[]=$map;
			$theHomeScore[]=$homescr[$key];
			$theOppScore[]=$oppscr[$key];
		}		
	}
	$theMaps=implode("||", $theMaps);
	$theHomeScore=implode("||", $theHomeScore);
	$theOppScore=implode("||", $theOppScore);
	
	echo'<script src="js/bbcode.js" language="jscript" type="text/javascript"></script>
		 <link href="_stylesheet.css" rel="stylesheet" type="text/css">';
	
  $date=mktime(0,0,0,$month,$day,$year);
	
	if(is_array($hometeam)) {
		$team=array();
		foreach($hometeam as $player) {
			if(!in_array($player, $team)) $team[]=$player;
		}
		$home_string=implode("|", $team);
	}
	else $home_string='';
	
	safe_query("UPDATE ".PREFIX."clanwars SET date='$date',
                 squad='$squad',
								 game='$game',
								 league='".mysql_escape_string($league)."',
								 leaguehp='$leaguehp',
								 opponent='".mysql_escape_string($opponent)."',
								 opptag='".mysql_escape_string($opptag)."',
								 oppcountry='$oppcountry',
								 opphp='$opphp',
								 maps='".mysql_escape_string($theMaps)."',
								 hometeam='".mysql_escape_string($home_string)."',
								 oppteam='".mysql_escape_string($oppteam)."',
								 server='$server',
								 hltv='$hltv',
								 homescore='$theHomeScore',
								 oppscore='$theOppScore',
								 report='".mysql_escape_string($report)."',
								 comments='$comments',
                 linkpage='$linkpage' WHERE cwID='$cwID'");

	echo'<center><br><br><br><br>
			  <b>Clanwar has been updated.</b><br><br>
			  <input type="button" class="button" onClick="MM_goToURL(\'parent\',\'upload.php?cwID='.$cwID.'\');return document.MM_returnValue" value="upload screenshots"> 
			  <input type="button" class="button" onClick="javascript:self.close()" value="close window"></center>';
}
elseif($_GET['action']=="delete") {
	include("_mysql.php");
	include("_settings.php");
	include("_functions.php");
  if(!isanyadmin($userID)) die('no access!');
  $cwID = $_POST['cwID'];
  if(!$cwID) $cwID = $_GET['cwID'];
	$ergebnis=safe_query("SELECT screens FROM ".PREFIX."clanwars WHERE cwID='$cwID'");
	$ds=mysql_fetch_array($ergebnis);
	$screens=explode("|", $ds[screens]);	
    $filepath = "./images/clanwar-screens/";
	if(is_array($screens)) {
		foreach($screens as $screen) {
			if(!empty($screen)) {
				if(file_exists($filepath.$screen)) @unlink($filepath.$screen);
			}
		}
	}
	safe_query("DELETE FROM ".PREFIX."clanwars WHERE cwID='$cwID'");
	header("Location: index.php?site=clanwars");
}
elseif($_POST['quickactiontype']=="delete") {
	include("_mysql.php");
	include("_settings.php");
	include("_functions.php");
  if(!isanyadmin($userID)) die('no access!');
  $cwID = $_POST['cwID'];
	foreach($cwID as $id) {
		$ergebnis=safe_query("SELECT screens FROM ".PREFIX."clanwars WHERE cwID='$id'");
		$ds=mysql_fetch_array($ergebnis);
		$screens=explode("|", $ds[screens]);	
	    $filepath = "./images/clanwar-screens/";
		if(is_array($screens)) {
			foreach($screens as $screen) {
				if(!empty($screen)) {
					if(file_exists($filepath.$screen)) @unlink($filepath.$screen);
				}
			}
		}
		
		safe_query("DELETE FROM ".PREFIX."clanwars WHERE cwID='$id'");
		safe_query("DELETE FROM ".PREFIX."comments WHERE parentID='$id' AND type='cw'");
	}
	header("Location: index.php?site=clanwars");
}

if($_GET['action']=="stats") {
	eval ("\$title_clanwars = \"".gettemplate("title_clanwars")."\";");
	echo $title_clanwars;
		
	echo'<input type="button" class="button" onClick="MM_goToURL(\'parent\',\'index.php?site=clanwars\');return document.MM_returnValue" value="Show Clanwars">';
	echo'<h2>CLAN-STATS</h2>';
	
	// TOTAL
	
	$dp=safe_query("SELECT * FROM ".PREFIX."clanwars");
	// clanwars gesamt
	$totaltotal=mysql_num_rows($dp);
	
	while($cwdata = mysql_fetch_array($dp)) {
		// total home points
		$totalhomeqry=safe_query("SELECT homescore FROM ".PREFIX."clanwars WHERE cwID='$cwdata[cwID]'");
		while($theHomeData = mysql_fetch_array($totalhomeqry)) {
			$totalHomeScore+=array_sum(explode("||", $theHomeData['homescore']));
			$theHomeScore=array_sum(explode("||", $theHomeData['homescore']));
		}
		// total opponent points
		$totaloppqry=safe_query("SELECT oppscore FROM ".PREFIX."clanwars WHERE cwID='$cwdata[cwID]'");
		while($theOppData = mysql_fetch_array($totaloppqry)) {
			$totalOppScore+=array_sum(explode("||", $theOppData['oppscore']));
			$theOppScore=array_sum(explode("||", $theOppData['oppscore']));
		}
		
		//
		if($allWon=='') $allWon=0;
		if($allLose=='') $allLose=0;
		if($allDraw=='') $allDraw=0;
		
		//
		if($theHomeScore > $theOppScore) $totalwonall++;
		if($theHomeScore < $theOppScore) $totalloseall++;
		if($theHomeScore == $theOppScore) $totaldrawall++;
	}
	$totalhome=$totalHomeScore;
	$totalopp=$totalOppScore;
	
	if(!$totalwonall) $totalwonall=0;
	if(!$totalloseall) $totalloseall=0;
	if(!$totaldrawall) $totaldrawall=0;
	if(!$totalhome) $totalhome=0;
	if(!$totalopp) $totalopp=0;

	$totalwonperc=percent($totalwonall, $totaltotal, 2);
	if($totalwonperc) $totalwon=$totalwonperc.'%<br><img src="images/icons/won.gif" width="30" height="'.round($totalwonperc, 0).'" border="1" alt="won">';
	else $totalwon=0;
	
	$totalloseperc=percent($totalloseall, $totaltotal, 2);
	if($totalloseperc) $totallost=$totalloseperc.'%<br><img src="images/icons/lost.gif" width="30" height="'.round($totalloseperc, 0).'" border="1" alt="lost">';
	else $totallost=0;
	
	$totaldrawperc=percent($totaldrawall, $totaltotal, 2);
	if($totaldrawperc) $totaldraw=$totaldrawperc.'%<br><img src="images/icons/draw.gif" width="30" height="'.round($totaldrawperc, 0).'" border="1" alt="draw">';
	else $totaldraw=0;
	
	$squad='CLAN';
		
	eval ("\$clanwars_stats_total = \"".gettemplate("clanwars_stats_total")."\";");
	echo $clanwars_stats_total;

	// SQUADS
	
	$squads=safe_query("SELECT * FROM ".PREFIX."squads WHERE gamesquad='1' ORDER BY sort");
	if(mysql_num_rows($squads)) {
		while($squaddata=mysql_fetch_array($squads)) {
			$squad=getsquadname($squaddata['squadID']);
			echo '<h2>'.$squad.' - STATS</h2>';
			
			// SQUAD STATISTICS
			
			$squadcws=safe_query("SELECT * FROM ".PREFIX."clanwars WHERE squad='".$squaddata['squadID']."'");
			$total=mysql_num_rows($squadcws);
			$totalperc=percent($total, $totaltotal, 2);
			
			while($squadcwdata=mysql_fetch_array($squadcws)) {
				
				// SQUAD CLANWAR STATISTICS
				
				// total squad homescore
				$sqHomeScoreQry=mysql_fetch_array(safe_query("SELECT homescore FROM ".PREFIX."clanwars WHERE cwID='".$squadcwdata['cwID']."' AND squad='".$squaddata['squadID']."'"));
				$sqHomeScore=array_sum(explode("||", $sqHomeScoreQry['homescore']));
				$totalHomeScoreSQ+=array_sum(explode("||", $sqHomeScoreQry['homescore']));
				// total squad oppscore
				$sqOppScoreQry=mysql_fetch_array(safe_query("SELECT oppscore FROM ".PREFIX."clanwars WHERE cwID='".$squadcwdata['cwID']."' AND squad='".$squaddata['squadID']."'"));
				$sqOppScore=array_sum(explode("||", $sqOppScoreQry['oppscore']));
				$totalOppScoreSQ+=array_sum(explode("||", $sqOppScoreQry['oppscore']));

				//
				if($sqHomeScore > $sqOppScore) $wonall++;
				if($sqHomeScore < $sqOppScore) $loseall++;
				if($sqHomeScore == $sqOppScore) $drawall++;
				//
				unset($sqHomeScore);
				unset($sqOppScore);
			}
			
			// SQUAD STATISTICS - CLANWARS
			
			// total squad clanwars - home points
			$home=$totalHomeScoreSQ;
			if(empty($home)) $home=0;
			$homeperc=percent($home, $totalhome, 2);
			// total squad clanwars - opponent points
			$opp=$totalOppScoreSQ;
			if(empty($opp)) $opp=0;
			$oppperc=percent($opp, $totalopp, 2);
			// total squad clanwars won
			$wonperc=percent($wonall, $totaltotal, 2);
			if($wonperc) $totalwon=$wonperc.'%<br><img src="images/icons/won.gif" width="30" height="'.round($wonperc, 0).'" border="1" alt="won">';
			else $totalwon='0%';
			// total squad clanwars lost
			$loseperc=percent($loseall, $totaltotal, 2);
			if($loseperc) $totallost=$loseperc.'%<br><img src="images/icons/lost.gif" width="30" height="'.round($loseperc, 0).'" border="1" alt="lost">';
			else $totallost='0%';
			// total squad clanwars draw
			$drawperc=percent($drawall, $totaltotal, 2);
			if($drawperc) $totaldraw=$drawperc.'%<br><img src="images/icons/draw.gif" width="30" height="'.round($drawperc, 0).'" border="1" alt="draw">';
			else $totaldraw='0%';
			
			// fill empty vars
			if(empty($totalwon)) $totalwon=0;
			if(empty($totallost)) $totallost=0;
			if(empty($totaldraw)) $totaldraw=0;
			if(empty($wonall)) $wonall=0;
			if(empty($loseall)) $loseall=0;
			if(empty($drawall)) $drawall=0;
			
			// start output for squad details
			eval("\$clanwars_stats = \"".gettemplate("clanwars_stats")."\";");
			echo $clanwars_stats;
			
			unset($opp); unset($home);
			unset($totalwon); unset($totallost); unset($totaldraw);
			unset($totalHomeScoreSQ); unset($totalOppScoreSQ);
			unset($homeperc); unset($oppperc);
		
			// PLAYER STATISTICS
		
			// start output for squad details - players of the squad - head
			eval ("\$clanwars_stats_player_head = \"".gettemplate("clanwars_stats_player_head")."\";");
			echo $clanwars_stats_player_head;
			
			// get playerlist for squad
			$squadmembers=safe_query("SELECT * FROM ".PREFIX."squads_members WHERE squadID='".$squaddata['squadID']."'");
			while($player=mysql_fetch_array($squadmembers)) {
				$playerlist[]=$player['userID'];
			}
			
			// get roster for squad and find matches with playerlist
			$playercws=safe_query("SELECT hometeam FROM ".PREFIX."clanwars WHERE squad='".$squaddata['squadID']."'");
			while($roster=mysql_fetch_array($playercws)) {
				$hometeam.=$roster['hometeam']."|";
			}
						
			// counts clanwars the member has taken part in
			$anz=array();
			if(!empty($hometeam)) {
				$array=explode("|", $hometeam);
				foreach($array as $id) {
					if(!empty($id)) {
						$anz[$id]=$anz[$id]+1;
					}
				}
			}
			// member's details and the output
			if(is_array($playerlist)) {
				$i=1;
				foreach($playerlist as $id) {
					if($i%2) {
						$bg1=BG_1;
						$bg2=BG_2;
					}
					else {
						$bg1=BG_3;
						$bg2=BG_4;
					}
			
					$country='[flag]'.getcountry($id).'[/flag]';
					$country=flags($country);
					$member='<a href="index.php?site=profile&id='.$id.'"><b>'.getnickname($id).'</b></a>';
					$wars=$anz[$id];
					if(empty($wars)) $wars='0';
					$perc=percent($wars, $total, 2);
					if($perc) $percpic='<img src="images/icons/poll_start.gif" width="1" height="5"><img src="images/icons/poll.gif" width="'.round($perc, 0).'" height="5"><img src="images/icons/poll_end.gif" width="1" height="5"> '.$perc.'%';
					else $percpic='<img src="images/icons/poll_start.gif" width="1" height="5"><img src="images/icons/poll_end.gif" widht="1" height="5"> '.$perc.'%';
		
					eval ("\$clanwars_stats_player_content = \"".gettemplate("clanwars_stats_player_content")."\";");
					echo $clanwars_stats_player_content;
					$i++;
				}
			}
			echo'</table>';
			
			unset($wonall);
			unset($loseall);
			unset($drawall);
			unset($playerlist);
			unset($hometeam);
			unset($squadcwdata);
		}
	}
}
elseif($_GET['action']=="showonly") {
  $cwID = $_GET['cwID'];
  $id = $_GET['id'];
  $only = $_GET['only'];
  $sort = $_GET['sort'];
  $type = $_GET['type'];
  $page = $_GET['page'];
	$squads=getgamesquads();
	$jumpsquads=str_replace('value="', 'value="index.php?site=clanwars&action=showonly&only=squad&id=', $squads);
	$jumpmenu='<select name="selectgame" onChange="MM_jumpMenu(\'parent\',this,0)">			   <option value="index.php?site=clanwars">- show all squads -</option>'.$jumpsquads.'
				 </select> <input type="button" name="Button1" value="Go" onClick="MM_jumpMenuGo(\'selectgame\',\'parent\',0)">';		
			 
	eval ("\$title_clanwars = \"".gettemplate("title_clanwars")."\";");
	echo $title_clanwars;
	
	$gesamt = mysql_num_rows(safe_query("SELECT cwID FROM ".PREFIX."clanwars WHERE $only='$id'"));
	$pages=1;
	if(!isset($page)) $page = 1;
	if(!isset($sort)) $sort = "date";
	if(!isset($type)) $type = "DESC";
	
	$max=$maxclanwars;
		
    for ($n=$max; $n<=$gesamt; $n+=$max) {
	    if($gesamt>$n) $pages++;
	}
		 	
	if($pages>1) $page_link = makepagelink("index.php?site=clanwars&action=showonly&id=$id&sort=$sort&type=$type&only=$only", $page, $pages);
	
	if ($page == "1") {
        $ergebnis = safe_query("SELECT * FROM ".PREFIX."clanwars WHERE $only='$id' ORDER BY $sort $type LIMIT 0,$max");
	    if($type=="DESC") $n=$gesamt;
		else $n=1;
	}
	else {
	    $start=$page*$max-$max;
	    $ergebnis = safe_query("SELECT * FROM ".PREFIX."clanwars WHERE $only='$id' ORDER BY $sort $type LIMIT $start,$max");
	    if($type=="DESC") $n = ($gesamt)-$page*$max+$max;
		else $n = ($gesamt+1)-$page*$max+$max;
	}
	
	if($type=="ASC") 
	    $seiten='<a href="index.php?site=clanwars&action=showonly&id='.$id.'&page='.$page.'&sort='.$sort.'&type=DESC&only='.$only.'">Sort:</a> <img src="images/icons/asc.gif" width="9" height="7" border="0"> '.$page_link.'<br><br>';
	else 
	    $seiten='<a href="index.php?site=clanwars&action=showonly&id='.$id.'&page='.$page.'&sort='.$sort.'&type=ASC&only='.$only.'">Sort:</a> <img src="images/icons/desc.gif" width="9" height="7" border="0"> '.$page_link.'<br><br>';
	
	if(isclanwaradmin($userID)) $admin='<input type="button" class="button" onClick="MM_openBrWindow(\'clanwars.php?action=new\',\'Clanwars\',\'toolbar=no,status=no,scrollbars=yes,width=800,height=600\')" value="New Clanwar">';
	$Statistics='<input type="button" class="button" onClick="MM_goToURL(\'parent\',\'index.php?site=clanwars&action=stats\');return document.MM_returnValue" value="Statistics">';
	
	echo'<table width="100%" border="0" cellspacing="0" cellpadding="2">
 			<tr><form name="jump">
   			<td>'.$admin.' '.$Statistics.'</td>
   			<td align="right">'.$jumpmenu.'</td>
			</tr>
			<tr><td>'.$seiten.'</td><td></td></form>
 			</tr>
	</table>';
	
	if($gesamt) {	
		$headdate='<a class="titlelink" href="index.php?site=clanwars&action=showonly&id='.$id.'&only='.$only.'&page='.$page.'&sort=date&type='.$type.'">Date:</a>';
		$headgame='<a class="titlelink" href="index.php?site=clanwars&action=showonly&id='.$id.'&only='.$only.'&page='.$page.'&sort=game&type='.$type.'">G:</a>';
		$headsquad='<a class="titlelink" href="index.php?site=clanwars&action=showonly&id='.$id.'&only='.$only.'&page='.$page.'&sort=squadID&type='.$type.'">Squad:</a>';
		$headcountry='<a class="titlelink" href="index.php?site=clanwars&action=showonly&id='.$id.'&only='.$only.'&page='.$page.'&sort=oppcountry&type='.$type.'">Cnt:</a>';
		$headleague='<a class="titlelink" href="index.php?site=clanwars&action=showonly&id='.$id.'&only='.$only.'&page='.$page.'&sort=league&type='.$type.'">League:</a>';
		
		eval ("\$clanwars_head = \"".gettemplate("clanwars_head")."\";");
	    echo $clanwars_head;
		$n=1;
		if(isclanwaradmin($userID)) echo'<form method="post" name="form" action="clanwars.php">';
		while($ds=mysql_fetch_array($ergebnis)) {
			if($n%2) {
				$bg1=BG_1;
				$bg2=BG_2;
			}
			else {
				$bg1=BG_3;
				$bg2=BG_4;
			}
			$date=date("d.m.y", $ds[date]);
			$league='<a href="'.$ds[leaguehp].'" target="_blank">'.$ds[league].'</a>';
			$oppcountry="[flag]".$ds[oppcountry]."[/flag]";
			$country=flags($oppcountry);
			$opponent='<a href="'.$ds[opphp].'" target="_blank"><b>'.$ds[opptag].'</b></a>';
			$maps=$ds[maps];
			$hometeam=$ds[hometeam];
			$oppteam=$ds[oppteam];
			$server=$ds[server];
			
			$squad='<a href="index.php?site=clanwars&action=showonly&id='.$id.'&page='.$page.'&sort=game&type='.$type.'&only=squad"><b>'.getsquadname($ds[squad]).'</b></a>';
			if(file_exists('images/games/'.$ds[game].'.jpg')) $pic = $ds[game].'.jpg'; else $pic = $ds[game].'.gif';
			$game='<a href="index.php?site=clanwars&action=showonly&id='.$ds[game].'&page='.$page.'&sort=game&type='.$type.'&only=game"><img src="images/games/'.$pic.'" width="13" height="13" border="0"></a>';
			
			$homescr=array_sum(explode("||", $ds[homescore]));
			$oppscr=array_sum(explode("||", $ds[oppscore]));

			if($homescr>$oppscr) $results='<font color="'.$wincolor.'">'.$homescr.':'.$oppscr.'</font>';
			elseif($homescr<$oppscr) $results='<font color="'.$loosecolor.'">'.$homescr.':'.$oppscr.'</font>';
			else $results='<font color="'.$drawcolor.'">'.$homescr.':'.$oppscr.'</font>';
			
			if(getanzcwcomments($ds[cwID])) $details='<a href="index.php?site=clanwars_details&cwID='.$ds[cwID].'"><img src="images/icons/foldericons/newhotfolder.gif" alt="details" border="0"> ('.getanzcwcomments($ds[cwID]).')</a>';
			else $details='<a href="index.php?site=clanwars_details&cwID='.$ds[cwID].'"><img src="images/icons/foldericons/folder.gif" alt="details" border="0"> ('.getanzcwcomments($ds[cwID]).')</a>';
						
			$multiple='';
			$admdel='';
			if(isclanwaradmin($userID)) $multiple='<input class="input" type="checkbox" name="cwID[]" value="'.$ds[cwID].'">';
			
			eval ("\$clanwars_content = \"".gettemplate("clanwars_content")."\";");
	        echo $clanwars_content;
			unset($result);
			$n++;
		}
		if(isclanwaradmin($userID)) $admdel='<table width="100%" border="0" cellspacing="0" cellpadding="4">	
							<tr>
							<td><input class="input" type="checkbox" name="ALL" value="ALL" onClick="SelectAll(this.form);"> select all</td>
							    <td align="right"><select name="quickactiontype">
								<option value="delete">delete selected</option>
								</select> 
							<input type="submit" name="quickaction" value="go"></td>
							</tr>
							</table></form>';
		
		eval ("\$clanwars_foot = \"".gettemplate("clanwars_foot")."\";");
	    echo $clanwars_foot;
	}
	else echo'no entries';
}
elseif(empty($_GET['action'])) {
  $sort = $_GET['sort'];
  $type = $_GET['type'];
  $page = $_GET['page'];
	$squads=getgamesquads();
	$jumpsquads=str_replace('value="', 'value="index.php?site=clanwars&action=showonly&only=squad&id=', $squads);
	$jumpmenu='<select name="selectgame" onChange="MM_jumpMenu(\'parent\',this,0)"><option value="index.php?site=clanwars">- show all squads -</option>'.$jumpsquads.'
				 </select> <input type="button" name="Button1" value="Go" onClick="MM_jumpMenuGo(\'selectgame\',\'parent\',0)">';		
				 
	eval ("\$title_clanwars = \"".gettemplate("title_clanwars")."\";");
	echo $title_clanwars;
	
	$gesamt = mysql_num_rows(safe_query("SELECT cwID FROM ".PREFIX."clanwars"));
	$pages=1;
	if(!isset($page)) $page = 1;
	if(!isset($sort)) $sort = "date";
	if(!isset($type)) $type = "DESC";
	
	$max=$maxclanwars;
		
  for($n=$max; $n<=$gesamt; $n+=$max) {
		if($gesamt>$n) $pages++;
	}
		 	
	if($pages>1) $page_link = makepagelink("index.php?site=clanwars&sort=$sort&type=$type", $page, $pages);
	
	if($page == "1") {
		$ergebnis = safe_query("SELECT * FROM ".PREFIX."clanwars ORDER BY $sort $type LIMIT 0,$max");
	  if($type=="DESC") $n=$gesamt;
		else $n=1;
	}
	else {
		$start=$page*$max-$max;
	  $ergebnis = safe_query("SELECT * FROM ".PREFIX."clanwars ORDER BY $sort $type LIMIT $start,$max");
	  if($type=="DESC") $n = ($gesamt)-$page*$max+$max;
		else $n = ($gesamt+1)-$page*$max+$max;
	}
	
	if($type=="ASC") $seiten='<a href="index.php?site=clanwars&page='.$page.'&sort='.$sort.'&type=DESC">Sort:</a> <img src="images/icons/asc.gif" width="9" height="7" border="0"> '.$page_link.'<br><br>';
	else $seiten='<a href="index.php?site=clanwars&page='.$page.'&sort='.$sort.'&type=ASC">Sort:</a> <img src="images/icons/desc.gif" width="9" height="7" border="0"> '.$page_link.'<br><br>';
	
	if(isclanwaradmin($userID)) $admin='<input type="button" class="button" onClick="MM_openBrWindow(\'clanwars.php?action=new\',\'Clanwars\',\'toolbar=no,status=no,scrollbars=yes,width=800,height=600\')" value="New Clanwar">';
	$statistics='<input type="button" class="button" onClick="MM_goToURL(\'parent\',\'index.php?site=clanwars&action=stats\');return document.MM_returnValue" value="Statistics">';
	
	echo'<table width="100%" border="0" cellspacing="0" cellpadding="2">
 			<tr><form name="jump">
   			<td>'.$admin.' '.$statistics.'</td>
   			<td align="right">'.$jumpmenu.'</td>
			</tr>
			<tr><td>'.$seiten.'</td><td></td></form>
 			</tr>
	</table>';

	if($gesamt) {
		$headdate='<a class="titlelink" href="index.php?site=clanwars&page='.$page.'&sort=date&type='.$type.'">Date:</a>';
		$headgame='<a class="titlelink" href="index.php?site=clanwars&page='.$page.'&sort=squad&type='.$type.'">G:</a>';
		$headsquad='<a class="titlelink" href="index.php?site=clanwars&page='.$page.'&sort=squad&type='.$type.'">Squad:</a>';
		$headcountry='<a class="titlelink" href="index.php?site=clanwars&page='.$page.'&sort=oppcountry&type='.$type.'">Cnt:</a>';
		$headleague='<a class="titlelink" href="index.php?site=clanwars&page='.$page.'&sort=league&type='.$type.'">League:</a>';
		
		eval ("\$clanwars_head = \"".gettemplate("clanwars_head")."\";");
	  echo $clanwars_head;
		
		$n=1;
		if(isclanwaradmin($userID)) echo'<form method="post" name="form" action="clanwars.php">';
		while($ds=mysql_fetch_array($ergebnis)) {
			if($n%2) {
				$bg1=BG_1;
				$bg2=BG_2;
			}
			else {
				$bg1=BG_3;
				$bg2=BG_4;
			}
			$date=date("d.m.y", $ds[date]);
			$squad='<a href="index.php?site=clanwars&action=showonly&id='.$ds[squad].'&page='.$page.'&sort=game&type='.$type.'&only=squad"><b>'.getsquadname($ds[squad]).'</b></a>';
			$league='<a href="'.$ds[leaguehp].'" target="_blank">'.$ds[league].'</a>';
			$oppcountry="[flag]".$ds[oppcountry]."[/flag]";
			$country=flags($oppcountry);
			$opponent='<a href="'.$ds[opphp].'" target="_blank"><b>'.$ds[opptag].'</b></a>';
			$hometeam=$ds[hometeam];
			$oppteam=$ds[oppteam];
			$server=$ds[server];
			if(file_exists('images/games/'.$ds[game].'.jpg')) $pic = $ds[game].'.jpg'; else $pic = $ds[game].'.gif';
			$game='<a href="index.php?site=clanwars&action=showonly&id='.$ds[game].'&page='.$page.'&sort=game&type='.$type.'&only=game"><img src="images/games/'.$pic.'" width="13" height="13" border="0"></a>';

			$homescr=array_sum(explode("||", $ds[homescore]));
			$oppscr=array_sum(explode("||", $ds[oppscore]));

			if($homescr>$oppscr) $results='<font color="'.$wincolor.'">'.$homescr.':'.$oppscr.'</font>';
			elseif($homescr<$oppscr) $results='<font color="'.$loosecolor.'">'.$homescr.':'.$oppscr.'</font>';
			else $results='<font color="'.$drawcolor.'">'.$homescr.':'.$oppscr.'</font>';
			
			if(getanzcwcomments($ds[cwID])) $details='<a href="index.php?site=clanwars_details&cwID='.$ds[cwID].'"><img src="images/icons/foldericons/newhotfolder.gif" alt="details" border="0"> ('.getanzcwcomments($ds[cwID]).')</a>';
			else $details='<a href="index.php?site=clanwars_details&cwID='.$ds[cwID].'"><img src="images/icons/foldericons/folder.gif" alt="details" border="0"> ('.getanzcwcomments($ds[cwID]).')</a>';
						
			$multiple='';
			$admdel='';
			if(isclanwaradmin($userID)) $multiple='<input class="input" type="checkbox" name="cwID[]" value="'.$ds[cwID].'">';
			
			eval ("\$clanwars_content = \"".gettemplate("clanwars_content")."\";");
	        echo $clanwars_content;
			unset($result);
			$n++;
		}
		if(isclanwaradmin($userID)) $admdel='<table width="100%" border="0" cellspacing="0" cellpadding="4">	
							<tr>
							<td><input class="input" type="checkbox" name="ALL" value="ALL" onClick="SelectAll(this.form);"> select all</td>
							    <td align="right"><select name="quickactiontype">
								<option value="delete">delete selected</option>
								</select> 
							<input type="submit" name="quickaction" value="go"></td>
							</tr>
							</table></form>';
		
		eval ("\$clanwars_foot = \"".gettemplate("clanwars_foot")."\";");
	  echo $clanwars_foot;
	}
	else echo'no entries';
}
?>