<?php

/**
* @desc This report lets you make split test of your pages and gives you an overview of wich one works the best.
*/
$reports["_CONTENT_BASED_SPLIT_TEST"] = Array(
	"ClassName" => "ContentBasedSplitTest", 
	"Category" => "_TEST_CENTER",
	"canAggregate" => false,	
	"icon" => "images/icons/32x32/contentbasedsplittest.png",
	"Options" => "daterangeField,profileselector,roadto",
	"Filename" => "content_based_split_test",
	"Distribution" => "Premium",
	"Order" => 1,
	"ReportVersion" => 1.0,
	"MinimumVersion" => 3.0,
	"EmailAlerts" => false,
	"Update" => false
);

class ContentBasedSplitTest extends Report {
	var $define_url;

	function Settings() {
		$this->define_url = "definereport.php?conf={$this->profile->profilename}&labels=_CONTENT_BASED_SPLIT_TEST";
		$this->help = _SPLIT_TEST_RESULTS_HELP;
		$this->displayReportButtons = false;
	}
		
	function DisplayCustomForm(){
		global $db, $session;
		//split test functions
		$this->sptablename = $this->profile->tablename."_splittests";
		$this->sptablename_results = $this->profile->tablename."_splittests_results";
		$this->Create_tables();
		$q = $db->Execute("select id,testname from {$this->sptablename} WHERE status=1");
		
		echo "<div class='form-group'>";
			echo "<label for='testid'>"._CHOOSE_SPLIT_TEST."</label>";
			echo "<select id='testid' class='report_option_field form-control'>";
			
			if($q == false){
				echo "<option value=''>"._NONE."</option>";
			} else {
				while($data = $q->FetchRow()){
					if(isset($this->testid) && $this->testid == $data["id"]){
						$selected = "selected='selected'";
					}else{
						$selected = "";
					}
					echo "<option value='{$data["id"]}' $selected>{$data["testname"]}</option>";
				}
			}
			echo "</select>";
		
			if($session->canEditProfiles()) {
				echo "<a data-title='". _WELCOME_TEST_CENTER ."' href='{$this->define_url}' class='optionlink open_iframe_window'>". _CREATE_EDIT_PHP_SPLIT_TEST ."</a>";
			}		
		echo "</div>";
	}

	function DisplayReport(){
		global $db, $niceto, $nicefrom;
		
		$this->ReportHeader();
		if(empty($this->roadto)){ 
			echoNotice($this->SettingsButton()._CHOOSE_KPI_FROM_SETTINGS); return false; 
		}
		
		$this->sptablename = $this->profile->tablename."_splittests";
		$this->sptablename_results = $this->profile->tablename."_splittests_results";
		if(empty($this->roadto)){ echoNotice($this->SettingsButton()._CHOOSE_KPI_FROM_SETTINGS); return false; }
		$target= $this->roadto;
		
		if(!isset($this->testid)){
			echoNotice($this->SettingsButton()._NO_SPLIT_TEST);
			return false;
		}
		
		//get some info
		$q = $db->Execute("select * from {$this->sptablename} where id={$this->testid}");
		$data=$q->FetchRow();
		$testname=$data['testname'];
		$testurl=$data['testurl'];
		$testdesc=$data['testdesc'];
		$splitperc=$data['splitperc'];
		$created=date("Y-m-d",$data['created']);

		//1. Select uniques from page a
		$q = $db->Execute("select count(distinct visitorid) as users from {$this->sptablename_results} where timestamp >=". $db->quote($this->from) ." and timestamp <=". $db->quote($this->to) ." and testid={$this->testid} and page='A'");
		$pagea=$q->FetchRow() or die ($db->ErrorMsg());

		//2. Select uniques from page b
		$q = $db->Execute("select count(distinct visitorid) as users from {$this->sptablename_results} where timestamp >=". $db->quote($this->from) ." and timestamp <=". $db->quote($this->to) ." and testid={$this->testid} and page='B'");
		$pageb=$q->FetchRow() or die ($db->ErrorMsg());

		if ($pagea[0]==0 && $pageb[0]==0) {
			$this->addlabel = _TEST_RESULT.": $testname";

			$q = $db->Execute("select max(timestamp) from {$this->sptablename_results} where testid={$this->testid}");
			$lasttime=$q->FetchRow() or die ($db->ErrorMsg());

			echo "<b>"._NO_SPLIT_TEST_COLLECTED." '$testname' "._DURING_DATE_RANGE.".</b><br>";
			if ($lasttime[0]!=0) {
				echo ""._LAST_ACTIVITY_ADDED_ON.date("Y-m-d, H:i:s",$lasttime[0])."<br>";   
			}
			echo "<br>"._MAKE_SURE_TEST_CODE_IS_PUBLISHED.".<br><br>";
			echo ""._DESCRIPTION.": $testdesc<br>"._TRAFFIC_SPLIT_PERCENT." $splitperc % &nbsp;&nbsp;&nbsp; "._TEST_CREATED_ON." $created<br>"._REPORT." "._DATE_RANGE.": "._REPORT." $nicefrom "._TO." {$niceto}<br>"._SELECTED." "._TARGET.": $target"; 
			return;   
		}

		# 1. Select Converted uniques from page a
		$q = $db->Execute("select count(distinct sp.visitorid) as users from {$this->sptablename_results} as sp, {$this->profile->tablename} as t, {$this->profile->tablename_urls} as u,{$this->profile->tablename_visitorids} as vi where t.timestamp >=". $db->quote($this->from) ." and t.timestamp <=". $db->quote($this->to) ." and sp.timestamp < t.timestamp and t.visitorid=vi.id and vi.visitorid=sp.visitorid and sp.page='A' and sp.testid={$this->testid} and t.url=u.id and u.url='$target'");
		$converta=$q->FetchRow() or die ($db->ErrorMsg());
		
		# 1. Select Converted uniques from page b
		$q = $db->Execute("select count(distinct sp.visitorid) as users from {$this->sptablename_results} as sp, {$this->profile->tablename} as t, {$this->profile->tablename_urls} as u,{$this->profile->tablename_visitorids} as vi where t.timestamp >=". $db->quote($this->from) ." and t.timestamp <=". $db->quote($this->to) ." and sp.timestamp < t.timestamp and t.visitorid=vi.id and vi.visitorid=sp.visitorid and sp.page='B' and sp.testid={$this->testid}  and t.url=u.id and u.url='$target'");
		$convertb=$q->FetchRow() or die ($db->ErrorMsg());

		
		# calculate the rest
		$cra=@number_format((($converta[0]/$pagea[0])*100),2);
		$crb=@number_format((($convertb[0]/$pageb[0])*100),2);

		$this->addlabel="";
		
		echo "<div style='width:550px;margin: 0 auto;font-size:14px;line-height:20px;padding: 10px 0 10px 0;'>";
		echo "A/B ". _SPLIT_TEST_CONTENT .": <strong>$testname</strong><br />";
		echo _KEY_PERFORMANCE_INDICATOR . ": <strong>{$this->roadto}</strong><br />";
		echo "</div>";		
		
		$this->CompareMeter(_PAGE_VISITORS . ":", $pagea[0], $pageb[0], _PAGE." A ({$pagea[0]})", _PAGE." B ({$pageb[0]})");
		$this->CompareMeter(_TARGET_VISITORS . ":", $converta[0], $convertb[0]);
		
		$this->CompareMeter(_CONVERSION_RATE, $cra , $crb, "{$cra}%", "{$crb}%");
		
		$infoa['target_indirect_total']=$converta[0];
		$infoa['page_total']=$pagea[0];
		$infob['target_indirect_total']=$convertb[0];
		$infob['page_total']=$pageb[0];
		echo "<br>";

		echo "<div class='col-md-12'>";
			$this->DisplayWinner($infoa,$infob,_PAGE);
			echo "<div class='form-group'><span>". _OTHER_SPLIT_INFO ."</span></div>";
		echo "</div>";

		echo "<div class='col-md-6'>
			<div class='form-group'><label>"._BOUNCE_RATE." "._PAGE." A: ". $this->SplitTestBounceRateOfPageVariation("A") ."</label></div>

			<label>"._TIME_SPENT." "._PAGE." A</label>". $this->SplitTestTimeOnPage("A") ."
		</div>";

		echo "<div class='col-md-6'>
			<div class='form-group'><label>"._BOUNCE_RATE." "._PAGE." B: ". $this->SplitTestBounceRateOfPageVariation("B") ."</label></div>
			<label>"._TIME_SPENT." "._PAGE." B</label>". $this->SplitTestTimeOnPage("B") ."
		</div>";
	
		echo "<div style='clear:both;'></div>";		
	}

	function SplitTestTimeOnPage($page) {
		global $db;
		$this->sptablename = $this->profile->tablename."_splittests";
		$this->sptablename_results = $this->profile->tablename."_splittests_results";
		/**
		* @desc This function will calculate grouped averages for time spent on a particular page, 
		* not counting people who bounced (had no further requests)
		* @returns $output that contains a html table
		*/    
		$db->Execute("drop temporary table if exists {$this->profile->tablename}_goodtimes"); $db->Execute("drop table if exists {$this->profile->tablename}_pagetime");
		
		// first find the visitorid and timestamp of the request we're interested in.   
		$query="CREATE TEMPORARY TABLE {$this->profile->tablename}_goodtimes ";
		$query.="SELECT vi.id as visitorid,min(timestamp) as timestamp FROM {$this->sptablename_results} as sp, {$this->profile->tablename_visitorids} as vi ";
		$query.="WHERE testid=". $db->quote($this->testid) ." AND (timestamp >=". $db->quote($this->from) ." and timestamp <=". $db->quote($this->to) .") ";
		$query.="AND page='$page' AND sp.visitorid=vi.visitorid ";
		$query.="GROUP BY visitorid";   
		
		// get the visitorid and timestamp of the request that came after the one we're interested in
		// and create a tempoary table to hold the difference between the two timestamps
		$query2 ="CREATE TABLE {$this->profile->tablename}_pagetime ";  
		$query2.="SELECT a.visitorid, (min(a.timestamp)-b.timestamp) as length from {$this->profile->tablename} as a, {$this->profile->tablename}_goodtimes as b ";
		$query2.="WHERE b.visitorid=a.visitorid and a.timestamp > b.timestamp and a.timestamp <= ". $db->quote($this->to) ." ";
		$query2.="GROUP BY a.visitorid";  
		
		$db->Execute($query);
		$db->Execute($query2);
		
		// get a meaningful breakdown of the time spent
		$range = $db->Execute("select count(*) as visitors from {$this->profile->tablename}_pagetime");
		$range_data = $range->FetchRow();
		$total_visitors=$range_data['visitors'];
		$query = "select \"0 to 10 secs            \", ((count(*)*1.0)/$total_visitors*100),count(*), avg(length)/60, \"1\" as ord from {$this->profile->tablename}_pagetime where length >=0 and length <=10 union ";
		$query.= "select \"10 to 60 secs            \", ((count(*)*1.0)/$total_visitors*100),count(*), avg(length)/60, \"2\" as ord from {$this->profile->tablename}_pagetime where length >=10 and length <=60 union ";
		$query.= "select \"1 to 5 mins            \", ((count(*)*1.0)/$total_visitors*100),count(*), avg(length)/60, \"3\" as ord from {$this->profile->tablename}_pagetime where length >=60 and length <=300 union ";
		$query.= "select \"5 to 15 mins            \", ((count(*)*1.0)/$total_visitors*100),count(*), avg(length)/60, \"4\" as ord from {$this->profile->tablename}_pagetime where length >=300 and length <=900 union ";
		$query.= "select \"15 to 30 mins            \", ((count(*)*1.0)/$total_visitors*100),count(*), avg(length)/60, \"5\" as ord from {$this->profile->tablename}_pagetime where length >=900 and length <=1800 union ";
		$query.= "select \"30 to 1 hr            \", ((count(*)*1.0)/$total_visitors*100),count(*), avg(length)/60, \"6\" as ord from {$this->profile->tablename}_pagetime where length >=1800 and length <=3600 union ";
		$query.= "select \"> 1 hr            \", ((count(*)*1.0)/$total_visitors*100),count(*), avg(length)/60, \"7\" as ord from {$this->profile->tablename}_pagetime where length >=3600";
		$query.= " order by ord";
		
		// get the results form the database
		$db->SetFetchMode(ADODB_FETCH_NUM);
		$result = $db->Execute($query);
		$data = $result->Getarray();
		$db->SetFetchMode(ADODB_FETCH_BOTH);
		
		// clean up temp tables (so we can do this more than once in a single script)
		$db->Execute("drop temporary table {$this->profile->tablename}_goodtimes");
		$db->Execute("drop table {$this->profile->tablename}_pagetime");
		
		//prepare the output
		$output="<table class='table'><tr><td><i>"._TIME_SPENT."</i></td><td><i>"._UNIQUE_VISITORS."</i></td><td><i>"._AVERAGE_DURATION."</i></td></tr>";
		foreach ($data as $thisdatarow) { 
			$output.= "<tr><td>$thisdatarow[0]</td><td title='$thisdatarow[2] Visitors'>".number_format($thisdatarow[1],2)."%</td><td>".number_format($thisdatarow[3],2)." mins</td></tr>";   
		}
		$output.="</table>";    
		return $output;       
		// return $data;       
	}
	function SplitTestBounceRateOfPageVariation($page) {
		global $db;
		$this->sptablename = $this->profile->tablename."_splittests";
		$this->sptablename_results = $this->profile->tablename."_splittests_results";
		// get the visitorid and timestamp of the request we're interested in 
		$db->Execute("CREATE TEMPORARY TABLE {$this->profile->tablename}_goodtimes select vi.id as visitorid,timestamp from {$this->sptablename_results} as sp, {$this->profile->tablename_visitorids} as vi where testid=". $db->quote($this->testid) ." and timestamp >=". $db->quote($this->from) ." and timestamp <=". $db->quote($this->to) ." and page='$page' and sp.visitorid=vi.visitorid");
		
		// first get total number of visitors to page
		$query = "select count(distinct visitorid) from {$this->profile->tablename}_goodtimes";
		$result = $db->Execute($query); 
		$total_visitors = $result->FetchRow();
		$total_visitors = $total_visitors[0];    
		
		// count how many visitors have hits beyond the timestamp we just found
		$query = "select count(distinct b.visitorid) from {$this->profile->tablename} as a, {$this->profile->tablename}_goodtimes as b where b.visitorid=a.visitorid and a.timestamp > b.timestamp and a.timestamp <= ". $db->quote($this->to) ."";
		$result = $db->Execute($query); 
		$stay_visitors = $result->FetchRow();
		$stay_visitors = $stay_visitors[0];
		
		$bounce_visitors = $total_visitors - $stay_visitors;
		$bounce_rate = @($bounce_visitors / $total_visitors * 100);
		
		$db->Execute("drop temporary table {$this->profile->tablename}_goodtimes");  
		return number_format($bounce_rate,0) . "%";       
	}
	
	function Welcome() {
		global $databasedriver;
		if (!IS_PHPDOCK) {
			echo "<a data-title='". _WELCOME_TEST_CENTER ."' href='{$this->define_url}&spt=create' class='btn btn-primary'>". _CREATE_PHP_SPLIT_TEST ."</a>";
		} else {
			echo "<div class='callout callout-info'>"._NO_DESKTOP_VERSION."</div>";
		}
		if ($databasedriver=='sqlite' && !IS_PHPDOCK) {
			echo "<div class='callout callout-danger'><b>"._PLEASE_NOTE_TEST_ONLY_WITH_MYSQL."</b></div>";
		}
	}
	
	function DefineReport(){
		$this->TopPanel();

		$spt = @$_REQUEST["spt"];

		echo "<div class='welcome-split'>";
		switch($spt){
			case "create":
				$this->CreateTest();
				break;
			case "delete":
				$this->DeleteTest();
				break;
			case "showclosed":
				$this->ShowClosed();
				break;
			case "edit":
				$this->EditTest();
				break;
			case "close":
				$this->CloseTest();
				break;
			case "activate":
				$this->ActivateTest();
				break;
			case "define":
				$this->DefineTest();
				break;
			case "savetest":
				$this->SaveTest();
				break;
			case "publish":
				$this->PublishTest();
				break;

			default:
			case "manage":
				$this->ManageTests();
				break;
		}
		echo "</div>";

		echo "<div style='clear:both;'></div>";
	}

	function DefineTest() {		
		$this->testid = $this->SaveTest(); // save basic info from step 1
		if(!$this->testid){
			return false;
		}
		echo "<h3>". _CREATE_TEST ."</h3>
			<span>". _TEST_HTML_COPY ."</span>
				<form name=editor method=post action=''>
				<div class='col-md-6'>
					<div class='form-group'>
						<label>". _SNIPPET ." A</label>
						<textarea class='form-control' name='panea' cols=40 rows=15 wrap=off style='color:darkgray;'></textarea>
					</div>
				</div>
				<div class='col-md-6'>
					<div class='form-group'>
						<label>". _SNIPPET ." B</label>
						<textarea class='form-control' name='paneb' cols=40 rows=15 wrap=off style='color:darkgray;'></textarea>
					</div>
				</div>

				<input type=hidden name=testid value=\"{$this->testid}\"/>
				<input type=hidden name=spt value='publish' />
				<input type=hidden name=conf value=\"{$this->profile->profilename}\"/>

				<div class='col-xs-12'>
					<input class='btn btn-primary' type='submit' value='"._CREATE."'/>
				</div>
			</form>";
	}

	function CreateTest(){
		echo "<div class=\"test-center-create\">
			<h3>"._CREATE_TEST."</h3>
			<ul><li>"._STEP1_TEST . "</li><li>"._STEP2_TEST . "</li><li>"._STEP3_TEST."</li></ul>
			<p>" ._LETS_START_TEST ."</p>
			<form id='TestCenterCreate'>
				<div class='form-group'>
					<label>"._TEST_NAME."</label>
					<input class='form-control' type='text' size='20' name='testname' maxval='50' />
				</div>

				<div class='form-group' title='". _DESCRIBE_YR_TEST ."'>
					<label>"._TEST_DESCRIPT."</label>
					<textarea class='form-control' name='testdesc' cols='30' rows='5' maxval='255'></textarea>
				</div>

				<div class='form-group' title='". _ENTER_PERCENT ."'>
					<label>"._TRAFFIC_SPLIT."%</label>
					<input class='form-control' type='text' size='40' name='splitperc' maxval='50' />
				</div>

				<div class='form-group'>
					<input type=hidden name=spt value=\"define\">
					<input type=hidden name=testid value=\"0\">					
					<input type=hidden name='labels' value=\"{$this->label_constant}\"/>
					<input type=hidden name=conf value=\"{$this->profile->profilename}\">
					<button class='btn btn-primary'>"._CREATE."</button>
				</div>
			</form>
		</div>";
	}

	function DeleteTest() {
		global $db;
		$db->Execute("delete from {$this->profile->tablename}_splittests where id=". $db->quote($this->testid) ."") or die ($db->ErrorMsg());
		$this->ShowClosed();
	}

	function CloseTest() {
		global $db;
		$this->sptablename = $this->profile->tablename."_splittests";
		$this->sptablename_results = $this->profile->tablename."_splittests_results";
		
		$db->Execute("update {$this->sptablename} set status=2 where id=". $db->quote($this->testid) ."");
		
		$this->ManageTests();
	}

	function EditTest() {
		global $db;
		$this->sptablename = $this->profile->tablename."_splittests";
		$this->sptablename_results = $this->profile->tablename."_splittests_results";
		$q = $db->Execute("select * from {$this->sptablename} where id={$this->testid}");
		$data=$q->FetchRow();
		$testname=$data['testname'];

		$testdesc=$data['testdesc'];
		$splitperc=$data['splitperc'];
		$panea=stripslashes($data['pagea']);
		$paneb=stripslashes($data['pageb']);
		$panea=str_replace("&","[#amp#]",$panea); 
		$paneb=str_replace("&","[#amp#]",$paneb);
		$panea=str_replace("</textarea>","</overruletextarea>",$panea);
		$paneb=str_replace("</textarea>","</overruletextarea>",$paneb); 

		echo "<form name='editor'>

			<input type='hidden' name='spt' value='publish'>
			<input type='hidden' name='testid' value='{$this->testid}'>
			<input type='hidden' name='labels' value='{$this->label_constant}'>
			<input type='hidden' name='edit' value='1'>
			<input type='hidden' name='conf' value='{$this->profile->profilename}'>

			<div class='test-center-create'>
				<h3>"._EDIT_SPLIT_TEST."</h3>

				<div class='col-sm-12'>

					<div class='form-group' title='"._TEST_NAME."'>
						<label>"._TEST_NAME."</label>
						<input class='form-control' type='text' size='20' name='testname' maxval='50' value='{$testname}' />
					</div>

					<div class='form-group' title='"._DESCRIBE_YR_TEST."'>
						<label>"._DESCRIPTION."</label>
						<textarea class='form-control' name='testdesc' cols='30' rows='5' maxval='255'>$testdesc</textarea>
					</div>

					<div class='form-group' title='"._ENTER_PERCENT."'>
						<label>Traffic Split %</label>
						<input class='form-control' type='text' size='40' name='splitperc' maxval='50' value='{$splitperc}' />
					</div>
				</div>
				<div class='col-sm-6'>
					<div class='form-group'>
						<label>". _SNIPPET ." A</label>
						<textarea class='form-control' name='panea' cols='45' rows='12' wrap='off' style='color:darkgray;' >". htmlspecialchars($panea) ."</textarea>
					</div>
				</div>

				<div class='col-sm-6'>
					<div class='form-group'>
						<label>". _SNIPPET ." B</label>
						<textarea class='form-control' name='paneb' cols='45' rows='12' wrap='on' style='color:darkgreen;' >{$paneb}</textarea>
					</div>
				</div>
				<div class='col-xs-12'>
					<div class='form-group'>
						<button class='btn btn-primary'>"._SAVE."</button>
					</div>
				</div>
			</div>
		</form>";

	}
	function ActivateTest() {
		global $db,$nosave;
		$this->sptablename = $this->profile->tablename."_splittests";
		$this->sptablename_results = $this->profile->tablename."_splittests_results";

		$db->Execute("update {$this->sptablename} set status=1 where id=". $db->quote($this->testid) ."");
		$nosave=1;
		$this->PublishTest();
	}


	function PublishTest() {
		global $nosave,$silent;
		
		if(isset($this->nosave)){
			$nosave = $this->nosave;
		}

		$w_path = $_SERVER['PHP_SELF'];
		$wpath = dirname($w_path);
		$abcodespace = " src=\\";
		
		if ($nosave!=1) {
			$silent=1;
			$this->SaveTest();
		}

		if($_REQUEST["spt"] == "activate"){
			echo "<h3>"._PUBLISH_SPLIT_TEST_REACTIVATED."</h3>";
		}else{
			echo "<h3>"._PUBLISH_SPLIT_TEST."</h3>";
		}

		echo "<span>". _PUBLISH_TEST_NEXT ."</span><br/><br/>
		<form method=post action='definereport.php?conf={$this->profile->profilename}&labels=_CONTENT_BASED_SPLIT_TEST'>
			<div class='form-group'>
				<textarea wrap=on cols=70 rows=4 name='abcodespace' class='form-control' onClick=\"javascript:this.form.abcodespace.focus();this.form.abcodespace.select();\">{$abcodespace}</textarea>
				<label>". _CLICK_ABOVE_CTRL_C_COPY ."</label>
			</div>
			<input type='hidden' name='conf' value='{$this->profile->profilename}' />
			<input type='hidden' name='labels' value='". _CONTENT_BASED_SPLIT_TEST ."' />
			<input class='btn btn-primary' type='submit' value='Finish'>
		</form>";
	}


	function ShowClosed() {
		global $db;
		$this->sptablename = $this->profile->tablename."_splittests";
		$this->sptablename_results = $this->profile->tablename."_splittests_results";

		$q = $db->Execute("select id,testname from {$this->sptablename} where status = 2");

		echoWarning(_DELETE_TEST_WARNING,"margin-right:10px;");

		echo "<h3>"._CLOSED_TESTS."</h3>";

		echo "<table class='report_table table'>";
			$i=0;
			while ($data = $q->fetchRow()) {
				echo "<tr>";
					echo "<td>{$data['testname']}</td>";
					echo "<td><a class='open_iframe_window' data-title='". _WELCOME_TEST_CENTER ."' href='{$this->define_url}&testid={$data['id']}&spt=edit'>"._EDIT."</a></td>";
					echo "<td><a class='open_iframe_window' data-title='". _WELCOME_TEST_CENTER ."' href='{$this->define_url}&testid={$data['id']}&spt=delete'>"._DELETE."</a></td>";
					echo "<td><a class='open_iframe_window' data-title='". _WELCOME_TEST_CENTER ."' href='{$this->define_url}&testid={$data['id']}&spt=activate'>". _ACTIVATE ."</a></td>";
				echo "</tr>";
				$i++;
			}
			if ($i==0) {
				echo "<tr><td>"._NONE."</td></tr>";
			}		
		echo "</table>";
	}

	function TopPanel() {
		echo "<div class='nav-tabs-custom'>
		    <ul class='nav nav-tabs'>
		        <li ". ( (empty($this->spt) || $this->spt =="manage") ? "class='active'" : "") ."><a href='{$this->define_url}&spt=manage'>". _MANAGE_TESTS ."</a></li> 
		        <li ". ( (@$this->spt =="create") ? "class='active'" : "") ."><a href='{$this->define_url}&spt=create'>". _CREATE_PHP_SPLIT_TEST ."</a></li>      
		        <li ". ( (@$this->spt =="showclosed") ? "class='active'" : "") ."><a href='{$this->define_url}&spt=showclosed'>". _SHOW_CLOSED_TESTS ."</a></li>   
		    </ul>
		</div>";
	}

	function ManageTests() {
		global $db;
		$this->sptablename = $this->profile->tablename."_splittests";
		$this->sptablename_results = $this->profile->tablename."_splittests_results";

		$q = $db->Execute("select * from {$this->sptablename} where status= 1");
		
		$i = 0;
		echo "<table class='table'>";
		if (!$q) {
				echo "<tr><td>". _NO_DATA_TO_DISPLAY ."</td><td></td><td></td><td></td><td></td></tr>";
		} else {
			while ($data = $q->FetchRow()) {
				echo "<tr>
					<td>{$data['testname']}</td>
					<td><a class='open_iframe_window' href='{$this->define_url}&testid={$data['id']}&nosave=1&spt=publish'>"._PUBLISH."</a></td>
					<td><a class='open_iframe_window' href='{$this->define_url}&testid={$data['id']}&nosave=1&spt=edit'>"._EDIT."</a></td>
					<td><a class='open_iframe_window' href='{$this->define_url}&testid={$data['id']}&nosave=1&spt=close'>"._CLOSE."</a></td>
				</tr>";
				$i ++;
			}
		}

		echo "</table>";


		if($i == 0){
			$this->Welcome();
		}
	}

	function Create_tables(){
		global $db, $databasedriver ;
			if (!CheckIfTableExists($this->sptablename)) {
			$db->Execute("CREATE TABLE {$this->sptablename} (".
			"id " . ($databasedriver == "sqlite"? "INTEGER PRIMARY KEY ": "int(11) NOT NULL auto_increment ") . "," .
			"testname varchar(100) NOT NULL default '',
			testdesc text,
			testurl varchar(255) default NULL,
			pagea blob,
			pageb blob,
			splitperc int(3) default '50',
			created int(11) NOT NULL default '0',
			status int(1) default '1' " .
                         ($databasedriver == "sqlite" ? "" : ", PRIMARY KEY  (id)") .
                         ") ENGINE=MyISAM  CHARSET=utf8"
            );
                if ($databasedriver == "mysql") {
                    $db->Execute("ALTER TABLE {$this->sptablename} ADD INDEX {$this->sptablename}_testname (testname)");
                } else {
                    $db->Execute("CREATE INDEX {$this->sptablename}_testname on {$this->sptablename}(testname)");
                }
            }

        $db->Execute(
            "CREATE OR REPLACE TABLE  {$this->sptablename_results} (" .
            "id " . ($databasedriver == "sqlite" ? "INTEGER PRIMARY KEY " : "int(11) NOT NULL auto_increment ") . "," .
            " testid int(10) NOT NULL default '0',
			visitorid varchar(32) NOT NULL default '0',
			timestamp int(11) NOT NULL default '0',
			page varchar(2) NOT NULL default '0' " .
            ($databasedriver == "sqlite" ? "" : ", PRIMARY KEY  (id)") .
            ") ENGINE=MyISAM  CHARSET=utf8"
        );
        if ($databasedriver == "mysql") {
            $db->Execute(
                "ALTER TABLE {$this->sptablename_results} ADD INDEX {$this->sptablename_results}_visitorid (visitorid)"
            );
            $db->Execute(
                "ALTER TABLE {$this->sptablename_results} ADD INDEX {$this->sptablename_results}_timestamp (timestamp)"
            );
				$db->Execute("ALTER TABLE {$this->sptablename_results} ADD INDEX {$this->sptablename_results}_testid (testid)");
				$db->Execute("ALTER TABLE {$this->sptablename_results} ADD INDEX {$this->sptablename_results}_page (page)");
			} else { 
				$db->Execute("CREATE INDEX {$this->sptablename_results}_visitorid on {$this->sptablename_results}(visitorid)");
				$db->Execute("CREATE INDEX {$this->sptablename_results}_timestamp on {$this->sptablename_results}(timestamp)");
				$db->Execute("CREATE INDEX {$this->sptablename_results}_testid on {$this->sptablename_results}(testid)");
				$db->Execute("CREATE INDEX {$this->sptablename_results}_page on {$this->sptablename_results}(page)"); 
			}
    }
	function SaveTest() {
		global $db;
		
		if(empty($_REQUEST["testname"])){
			$_REQUEST["testname"] = "Unnamed Test";
		}
		
		$this->sptablename = $this->profile->tablename."_splittests";
		$this->sptablename_results = $this->profile->tablename."_splittests_results";
		if (empty($this->testid)) {
			// If the tables don't already exists, then create them...
			$this->Create_tables();

			$cd=time();
			
			$q = $db->Execute("SELECT testname FROM {$this->sptablename} WHERE testname = ". $db->Quote($_REQUEST["testname"]));
			while($check = $q->fetchRow()){
				echoWarning("Test name already taken!","margin: 0 0 0 200px;");
				return false;
			}
			
			$db->Execute("insert into {$this->sptablename} (testname, testdesc, splitperc, created) values (".$db->Quote($_REQUEST["testname"]).",".$db->Quote($_REQUEST["testdesc"]).",".$db->Quote($_REQUEST["splitperc"]).",'$cd')");
			$this->testid=$db->Insert_ID();
			return $this->testid;  
		} else {
			$_REQUEST["panea"]= str_replace("[#amp#]","&",$_REQUEST["panea"]);
			$_REQUEST["paneb"]= str_replace("[#amp#]","&",$_REQUEST["paneb"]);
			$_REQUEST["panea"]= str_replace("</overruletextarea>","</textarea>",$_REQUEST["panea"]);
			$_REQUEST["paneb"]= str_replace("</overruletextarea>","</textarea>",$_REQUEST["paneb"]);
			echo "<pre>".$_REQUEST["panea"]."</pre>";
			if (isset($this->edit) && $this->edit==1) {
				$db->Execute("update {$this->sptablename} set testname=".$db->Quote($_REQUEST["testname"]).",testdesc=".$db->Quote($_REQUEST["testdesc"]).",splitperc=".$db->Quote($_REQUEST["splitperc"]).",pagea=".$db->Quote($_REQUEST["panea"]).", pageb=".$db->Quote($_REQUEST["paneb"])." where id=". $db->quote($this->testid) ."") or die ($db->ErrorMsg());
			} else {
				$db->Execute("update {$this->sptablename} set pagea=".$db->Quote($_REQUEST["panea"]).", pageb=".$db->Quote($_REQUEST["paneb"])." where id=". $db->quote($this->testid) ."") or die ($db->ErrorMsg());
			}
			return $this->testid;
		}
	}
	
	function UpdateStats($from = '', $to = '',$print = 2) {
		return false;
	}
}
?>