#!/usr/bin/perl -w
use CGI qw/:all/;
use CGI::Carp qw(fatalsToBrowser);
use DBI;
#my $dbh=DBI->connect('dbi:mysql:parc_demog:localhost:3306','root','root') or die "Unable to connect: $DBI::errstr\n";
my $dbh=DBI->connect('dbi:mysql:parc_demog:localhost','parcdemog','parc9904')or die "Couldn't connect to database: " . DBI->errstr;

@mon=("January","February","March","April","May","June","July","August","September","October","November","December"); 
@mn=("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"); 

my $shID= param('shID');
my $cityName=param('cityName');
my $conCode=param('conCode');
########
my $cont=param('cont');
my $fromLocation=param('fromLocation');
my $strSelLocs=param('strSelLocs');
$isEntered="00";
if ($fromLocation == 1) 
{
$j=0;
$strSelLocs= "l.locCode in ('";
$isEntered="11";
for ($i=1;$i<=$cont ;$i++) 
{
	 $isEntered="22";
	 $rn1 = "r".$i;
	 $sn2 = "s".$i;
	 $tn3 = "t".$i;
	 
	my $lcode =param("$rn1");
	my $lname =param("$sn2");
	my $lcity =param("$tn3"); #uncommented for mail
	
	if($lcode ne '')
	{
		$strSelLocs=$strSelLocs."$lcode','";
		$j=$j+1;
	}
}
$strSelLocs=substr($strSelLocs,0,-2).")";
}
######3
@storeCode;
@storeCount;
$i=0;

###############################

$strsql="select count(*) as total from cf_visitDetail where shID=$shID and hasMailed='T'";
$sthTOT=$dbh->prepare($strsql);
$sthTOT->execute;

while ($TOTCNT=$sthTOT->fetchrow_hashref())
{
	$visitCount = "$TOTCNT->{'total'}";
}

$strsql1="SELECT locCode, count(locCode) as ltotal FROM `cf_visitDetail` WHERE hasMailed = 'T' AND shid = $shID GROUP BY locCode UNION ALL SELECT locCode, '0' FROM `cf_location` WHERE locCode NOT IN (SELECT locCode FROM cf_visitDetail WHERE hasMailed = 'T' AND shid = $shID GROUP BY locCode)";
$sthLTOT=$dbh->prepare($strsql1);
$sthLTOT->execute;

while ($LTOTCNT=$sthLTOT->fetchrow_hashref())
{
	if($i==0)
	{
		$storeCode[$i]= "$LTOTCNT->{'locCode'}";
		$storeCount[$i] = "$LTOTCNT->{'ltotal'}";
	}
	else
	{
		$storeCode[$i]= ";$LTOTCNT->{'locCode'}";
		$storeCount[$i] = ";$LTOTCNT->{'ltotal'}";
	}
	$i=$i+1;
}
###############################
my $arrlen = $i;                         ### Leng
###############################

####
my $planDay=param('planDay');
my $planTime=param('planTime');

####
 $locCode=param('locCode');
 #####

#$conCode=971;

if($cityName eq "")
{
	$cityName="All";
}
if ($locCode eq '')
{
 $locCode= "All";
}

$strCond="";
if ($cityName ne "All")
{
	$strCond="l.cityName='$cityName'";
}

###########################
if ($planDay eq '')
{
 $planDay= "All";
}
if ($planTime eq '')
{
 $planTime= "All";
}

###########################

#########Checking for Location
if ($locCode ne "All")
{
	if ($strCond ne "") 
	{
		$strCond="$strCond and l.locCode='$locCode'";
	}
	else
	{
		$strCond="l.locCode='$locCode'";
	}
}

#####################

if ($planDay ne "All")
{
	if ($strCond ne "") 
	{
		$strCond="$strCond and v.planDay='$planDay'";
	}
	else
	{
		$strCond="v.planDay='$planDay'";
	}
}
if ($planTime ne "All")
{
	if ($strCond ne "") 
	{
		$strCond="$strCond and v.planTime='$planTime'";
	}
	else
	{
		$strCond="v.planTime='$planTime'";
	}
}

#####################

if ($strCond eq "")
{
	$strLOC="SELECT l.locCode as locCode, cityName, locName, typeName, planTime,planCode,planDay,typeCode FROM cf_location l, cf_visitPlan v WHERE v.locCode = l.locCode and l.conCode='$conCode' and hasMailed='F' and $strSelLocs";
}
else
{
	$strLOC="SELECT l.locCode as locCode, cityName, locName, typeName, planTime,planCode,planDay,typeCode FROM cf_location l, cf_visitPlan v WHERE v.locCode = l.locCode and l.conCode='$conCode' and hasMailed='F' and $strCond and $strSelLocs";
}
$sthL=$dbh->prepare($strLOC);
$sthL->execute;
$cont=$sthL->rows;
$strCity="select distinct cityName from cf_location l where conCode=$conCode and $strSelLocs order by cityName ";
$sthC=$dbh->prepare($strCity);
$sthC->execute;

###
$strLok="select distinct locCode,locName from cf_location l where conCode=$conCode  and $strSelLocs order by locCode ";
$sthLo=$dbh->prepare($strLok);
$sthLo->execute;
###

$strDay="select distinct (planDay) from cf_visitPlan v, cf_location l where l.conCode=$conCode and l.locCode=v.locCode and $strSelLocs order by planDay ";
$strPd=$dbh->prepare($strDay);
$strPd->execute;

###
$strTime="select distinct (planTime) from cf_visitPlan v, cf_location l where l.conCode=$conCode and l.locCode=v.locCode and $strSelLocs";
$strPt=$dbh->prepare($strTime);
$strPt->execute;


###

$strHead="select planDesc, planMonth, planYear from cf_visitPlanHead";
$sthHd=$dbh->prepare($strHead);
$sthHd->execute;
while (@planHead=$sthHd->fetchrow_array())
    {
        
        $strHead=$planHead[0];
		$mm=$planHead[1] - 1;
		$yy=$planHead[2];
    }



print <<blk1;
content-type: text/html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>PAN ARAB RESEARCH CENETER - Mystery Shopping $strSelLocs</title>
<link href="visit2.css" rel="stylesheet" type="text/css">
<script language="javaScript" type="text/javascript" src="calendarDayVal.js"></script>
<link href="calendar.css" rel="stylesheet" type="text/css">

<script type="text/javascript">
var totalCount="$visitCount";
var storeCode = new Array();
var storeCount = new Array();
//var obj = new Array(); 
var obj;
//obj = new Object();

var txtid="";
var curval="";
function plcCityName()
{
	frm=document.frmMain;
	frm.cityName.value="$cityName";
	frm.conCode.value="$conCode";	
	frm.locCode.value="$locCode";
	
	frm.planDay.value="$planDay";
	frm.planTime.value="$planTime";

	document.getElementById("msg").style.display="none";
	document.getElementById("tbl").style.display="";
	if("$cont"==0)
	{
		document.getElementById("msg").style.display="";
		document.getElementById("tbl").style.display="none";
	}
}

function dosave()
{
    document.frmMain.method="post";
	
	//document.frmMain.action="http://localhost:8081/CF/visits/visitEnter.pl";
	
    document.frmMain.action="http://www.arabdemog.com/cf/visits/visitEnter.pl"
	document.frmMain.submit();
    return true;
}
function selfpost()
{
	var cityName = document.getElementById('cityName').value;
	var conCode = document.getElementById('conCode').value;
	var locCode = document.getElementById('locCode').value;

	var planDay = document.getElementById('planDay').value;
	var planTime = document.getElementById('planTime').value;
	//var path="http://localhost:8081/CF/visits/visitTest.pl?shID=$shID&cityName="+cityName+"&conCode="+conCode+"&locCode="+locCode+"&planDay="+planDay+"&planTime="+planTime;
	
	var path="http://www.arabdemog.com/cf/visits/visitTest.pl?shID=$shID&cityName="+cityName+"&conCode="+conCode+"&locCode="+locCode+"&planDay="+planDay+"&planTime="+planTime;
	lnk=encodeURI(path);
	document.frmMain.method="post";
    document.frmMain.action=lnk;
	document.frmMain.submit();
    return true;
}
function filljsobj(strcod,strcnt)
{
	var arrcnt = "$arrlen";
	storeCode=strcod.split(";");
	storeCount=strcnt.split(";");
	
}

function dtrem(evt)
{
	var e = event || evt;
	if(e && (e.keyCode == 46 || e.keyCode == 8))    
	{
		return true;
	}
	else
	{ 
		return false;
	}
}

function checkCount(l,t)
{
	var type=t;
	var arraylen=storeCode.length;
	var arrind;
	var stcnt;
	var strr;
	stcode=l.toString();
	for(j=0;j<arraylen;j++)
	{
		strr=storeCode[j];
		strr=strr.trim();
		if(strr==stcode)
		{
			arrind=j;
			stcnt=storeCount[j]
			break;
		}
	}
	if(totalCount<25)
	{
		if(type==1)
		{
			if(stcnt<4)
			{
				storeCount[arrind]=parseInt(storeCount[arrind])+1;
				totalCount = parseInt(totalCount) + 1;
				return true;
			}
			else if(stcnt>=4)
			{
				alert("Sorry! You have reached maximum 4 number of Visit requests for SELECTED HYPER MARKET");
				return false;
			}
		}
		else if(type==2)
		{
			if(stcnt<2)
			{
				storeCount[arrind]=parseInt(storeCount[arrind])+1;
				totalCount = parseInt(totalCount) + 1;
				return true;
			}
			else if(stcnt>=2)
			{
				alert("Sorry! You have reached maximum 2 number of Visit requests for SELECTED CARREFOUR MARKET");
				return false;
			}
		}
	}
	else
	{
		alert("Sorry! You have reached Maximum 25 number of Total Visit requests");
		return false;
	}
	
}
function foci(val)
{
	var txtbx=document.getElementById(val).value
	txtbxlen=txtbx.length;
	//alert(txtbxlen);
	if(txtbx!="" && txtbxlen==10)
	{	
		txtid=val;
		curval=document.getElementById(val).value;
	}
	
}
function deselect(val,loc,typ)
{
	var curid = val;
	var txtval=document.getElementById(val).value;
	var arrlen=storeCode.length;
	lentxtval=txtval.length;
	loccode=loc.toString();
	if(curval=="" && txtid==curid)
	{
		txtid="";
		curval="";
		return;
	}
	else if((curval!="" && txtid!="" && txtid==curid) && (lentxtval>0 && lentxtval!=10))
	{
		alert("Select a Valid Date");
		document.getElementById(val).focus();
		return false;
	}
	else if(curval!="" && txtid==curid && lentxtval==0 )
	{
		for(k=0;k<arrlen;k++)
		{
			strr1=storeCode[k];
			strr1=strr1.trim();
			if(strr1==loccode)
			{
				storeCount[k]=parseInt(storeCount[k])- 1;
				totalCount = parseInt(totalCount) - 1;
			}
		}
		
		txtid="";
		curval="";
	}
	else
	{
		
	}
}

String.prototype.trim = function() { return this.replace(new RegExp(' ', 'g'),'');};
</script>
</head>

<body onload="plcCityName();filljsobj('@storeCode','@storeCount');">
$isEntered $strSelLocs 
<!-- Open Wrapper Div --><div id="wrapper">
				
<!-- Open Header Div --><div id="header">				
<!-- Header Content Here -->
<h1 class="header-title">PAN ARAB RESEARCH CENTER</h1>
<!-- Close Header Div --></div>

<!-- Open Level 2 Navigation Div --><div id="navbar"><h2>Visit Plan - $mon[$mm], $yy</h2></div>
<form method="post" name="frmMain">

<div id="content">

<div id="city"><font size='2'color='#FFFFFF'><p align="right"><b>City&nbsp;:&nbsp;</b> 
<input type="hidden" name="conCode" id="conCode">
<select name="cityName" id="cityName"  style="width:120px;border:1px solid #666666">
                    <option value="All">All</option>
blk1
    while (@City=$sthC->fetchrow_array())
    {
        
        print "<option value=$City[0]>$City[0]</option>";
    }
print <<blk2a;
</select>
&nbsp;<b>Location:</b>
<select name="locCode" id="locCode"  style="vertical-align:middle;width:150px;border:1px solid #666666">
                    <option value="All">All</option>
blk2a
while (@loc=$sthLo->fetchrow_array())
    {
       print "<option value=$loc[0]>$loc[1]</option>";
    }
print <<blk2b;
</select>
&nbsp;<b>Day:</b>
<select name="planDay" id="planDay" style="vertical-align:middle;width:130px;border:1px solid #666666">
                    <option value="All">All</option>
blk2b
while (@pd=$strPd->fetchrow_array())
{
	print "<option value='$pd[0]'>$pd[0]</option>";
}
print <<blk2c;
</select>
&nbsp;<b>Time:</b>
<select name="planTime" id="planTime"  style="vertical-align:middle;width:130px;border:1px solid #666666" >
                    <option value="All">All</option>
blk2c
while (@time=$strPt->fetchrow_array())
    {
		print "<option value='$time[0]'>$time[0]</option>";
    }

print <<blk2;
</select>

<a href="#" style="text-decoration: none;" onclick="selfpost();"><img src="go.png" style='vertical-align:middle;padding-right: 20px;' alt="GO" height="25" border="0" width="25"/> </a>
</p></font></div>
<div id="msg" style="display:none"><font size='3'color='#FFFFFF'><p align="center">No Records to Display</p></font></div>

<font size='2'color='#000000'><b>
<table width="100%" class="Mtable" id="tbl">
<tr>
<td  style="display:none" width="1%">planCode</td>
<td class="Mtd" width="1%" style="display:none"> Code</td><td class="Mtd"width="5%"> City</td><td class="Mtd" width="23%"> Location</td><td class="Mtd" width="17%"> Store Type</td><td class="Mtd" width="15%"> Time</td><td class="Mtd" width="15%"> Day</td><td class="Mtd" width="25%"> Date</td>

<!-- while loop to populate rows -->

blk2
my $i= 0;
while ($visit=$sthL->fetchrow_hashref())
   	{
		$i = $i + 1;
my $n1 = "pa1".$i;
my $n2 = "pb2".$i;
my $n3 = "pc3".$i;
my $n4 = "pd4".$i;
my $n5 = "pe5".$i;
my $n6 = "pf6".$i;
my $n7 = "pg7".$i;
my $n8 = "ph8".$i;


	my $code ="$visit->{'locCode'}";
	my $city ="$visit->{'cityName'}";
	my $location ="$visit->{'locName'}";
	my $type ="$visit->{'typeName'}";
	
	my $planTime ="$visit->{'planTime'}";
	my $planCode ="$visit->{'planCode'}";
	my $planDay ="$visit->{'planDay'}";
	my $typeCode ="$visit->{'typeCode'}";

print <<blk3;

</tr>
<tr>
<td  style="display:none" width="1%"><input type="hidden"  value="$planCode" name="$n7" id="$n7" style="border: 0px;solid #000000;background-color:#5f7287;width:0px;" readonly/></td>
<td class="Mtd" style="display:none"> <input type="text"  value="$code" name="$n1" id="$n1" style="border: 0px;solid #000000;background-color:#5f7287;width:75px;" readonly/> </td>
<td class="Mtd"><input type="text" value="$city" name="$n2" id="$n2"  style="border: 0px;solid #000000;background-color:#5f7287;width:80px;color:#FFFFFF;" readonly /></td>
<td class="Mtd"><input type="text" value="$location" name="$n3" id="$n3"  style="border: 0px;solid #000000;background-color:#5f7287;width:170px;color:#FFFFFF;" readonly /></td>
<td class="Mtd"><input type="text" value="$type" name="$n4" id="$n4"  style="border: 0px;solid #000000;background-color:#5f7287;width:155px;color:#FFFFFF;" readonly /></td>
<td class="Mtd"><input type="text" value="$planTime" name="$n6" id="$n6" style="border: 0px;solid #000000;background-color:#5f7287;width:95px;color:#FFFFFF;" readonly /></td>
<td class="Mtd"><input type="text" value="$planDay" name="$n8" id="$n8" style="border: 0px;solid #000000;background-color:#5f7287;width:95px;color:#FFFFFF;" readonly /></td>
<td class="Mtd"><input type="text" name="$n5" id="$n5" style="width:85px" onkeypress='return dtrem();' onfocus='foci("$n5")' onblur='deselect("$n5","$code","$typeCode")'><a href="JavaScript:void(0)" onClick="setYears('$yy', '$yy'); showCalender(this, '$n5','$n8','$mm','$yy','$code','$typeCode');">
                <img src="calender.png"></a></td>

</tr>

blk3
	
	}
print <<blk4;

<!-- End while loop -->
<tr>
<input type="hidden" value="$cont" name="cont" id="cont">
<input type="hidden" id="fromLocation" name="fromLocation" value="2"/>
<input type="hidden" id="strSelLocs" name="strSelLocs" value="$strSelLocs"/>
<td colspan="6" align="center">&nbsp;</td>
</tr>
<tr>
<td colspan="6" align="center"><input type="button" Value="Save" name="save" onclick="dosave();" /></td>
</tr>
</table>
</b>
</font>

<input type="hidden" id="shID" name="shID" value="$shID"/>

<!-- Close Content Div --></div>


<!-- Open Footer Div --><div id="footer">
<!-- Footer Content Here -->

<p class="footerpmiddle"><br /></p>
<!-- Close Footer Div --></div>	
</form>					
<!-- Close Wrapper Div --></div>							




<!-- Calender Script  --> 

    <table id="calenderTable">
        <tbody id="calenderTableHead">
          <tr>
            <td colspan="4" align="center">
              <select onChange="showCalenderBody(createCalender(document.getElementById('selectYear').value,
               this.selectedIndex, false));" id="selectMonth">
                  <option value="$mm">$mn[$mm]</option>
              </select>
            </td>
            <td colspan="2" align="center">
                <select onChange="showCalenderBody(createCalender(this.value, 
                document.getElementById('selectMonth').selectedIndex, false));" id="selectYear">
                </select>
            </td>
            <td align="center">
                <a href="JavaScript:void(0)" onClick="closeCalender();"><font color="#003333" size="+1">X</font></a>
            </td>
          </tr>
       </tbody>
       <tbody id="calenderTableDays">
         <tr style="">
           <td>Sun</td><td>Mon</td><td>Tue</td><td>Wed</td><td>Thu</td><td>Fri</td><td>Sat</td>
         </tr>
       </tbody>
       <tbody id="calender"></tbody>
    </table>

<!-- End Calender Script  --> 



<!--
<p><img src="img/tleft.gif" width="10" height="10" />
  <img src="img/bright.gif" width="10" height="10" />
  <img src="img/bleft.gif" width="10" height="10" />
  <img src="img/tright.gif" width="10" height="10" /></p>
<p>&nbsp;</p>
<p class="ptop"><img src="img/tleft.gif" width="10" height="10" alt=""></p>
<p class="pmiddle"></p>
<p class="pbottom"><img src="img/bleft.gif" alt="" width="10" height="10"></p> -->
</body>
</html>
blk4
