<?php
include("includes/site_info.php");
include('session_handler.inc');
	
	switch ($_REQUEST["Mode"]) {
	case "getFor"; 
		getFor();
		break;
	case "getForOnly"; 
		getForOnly();
		break;
	case "getsubSelect"; 
		getsubSelect();
		break;
	case "getTellsmore"; 
		getTellsmore();
		break;
	case "getExtraInfo"; 
		getExtraInfo();
		break;
	case "uploadPic"; 
		uploadPic();
		break;
	case "putInfo"; 
		putInfo();
		break;
	case "editInfo"; 
		editInfo();
		break;
	case "storeTitle"; 
		storeTitle();
		break;
	default; 
		echo "";
		break;
	}

function delete_image ($url, $filename, $ext) {
	if (file_exists($url.$filename.".".$ext)) {
    	unlink ($url.$filename.".".$ext);
	} 
	if (file_exists($url.$filename."_med.".$ext)) {
    	unlink ($url.$filename."_med.".$ext);
	}
	if (file_exists($url.$filename."_small.".$ext)) {
    	unlink ($url.$filename."_small.".$ext);
	}
		return;
}

function checkfolder($member_dir) {
	$return = array();
	clearstatcache();

	if (!is_dir($member_dir)) {
		$create_f1 = mkdir($member_dir, 0777, true);
		$chmod_f1 = chmod($member_dir, 0777);
	}

	$fileperms = substr(decoct( fileperms($member_dir) ), 1);
	if ($fileperms != "0777") {
		recursiveDelete($member_dir);
		$create_f2 = mkdir($member_dir, 0777, true);
		$chmod_f2 = chmod($member_dir, 0777);
	}

	if (!$create_f1 || !$create_f2) {
		$return = array_merge_recursive($return,  array( 'error' => 'Failed to create folder'));
	}
	if (!$chmod_f1 || !$chmod_f2) {
		$return = array_merge_recursive($return,  array( 'error' => 'Failed to chmod'));
	}
	return true;
}

function checkindex($source, $destination) {
	$return = array();
	$file = "index.php";

	if(!is_dir("$source/$file")) {
		if (!file_exists("$destination/$file")) {
		$copy_f1 = copy("$source/$file","$destination/$file");
		}
	} else {
		$return = array_merge_recursive($return,  array( 'error' => 'Is a directory, not a file.'));
	}
	if (!$copy_f1) {
		$return = array_merge_recursive($return,  array( 'error' => 'Failed to copy file'));
	}
	return true;
}

function recursiveDelete($str){
        if(is_file($str)){
            return @unlink($str);
        }
        elseif(is_dir($str)){
            $scan = glob(rtrim($str,'/').'/*');
            foreach($scan as $index=>$path){
                recursiveDelete($path);
            }
            return @rmdir($str);
        }
    }

function thumbnail_calcsize($w, $h, $sw, $sh)
{
    if ($sw < $w) {
	$kw  = $sw / $w;
   } else {
	$kw = 1;
	}
	
	if ($sh < $h) {
	$kh = $sh / $h;
	} else {
	$kh = 1;
	}
	
	if ($kw > $kh) {
	$k = $kh;
	} else {
	$k = $kw;
	} 
    return array($w*$k, $h*$k);
}                            

function thumbnail_generator($srcfile, &$params, $ext)
{
    // getting source image size
    @list($w, $h) = getimagesize($srcfile);
    if ($w == false)
        return false;

    // checking params array 
    if (!(is_array($params)&&is_array($params[0])))
        return false;

     // Load
    $ext = strtolower($ext);
   
    if($ext=='jpg' || $ext=='jpeg')
       $src = imagecreatefromjpeg($srcfile);
    if($ext=='gif')
        $src = imagecreatefromgif($srcfile);
    if($ext=='png')
        $src = imagecreatefrompng($srcfile); 
		
		
    list($s1_w, $s1_h) = thumbnail_calcsize($w, $h, $params[0]['size1'], $params[0]['size2']);

    // Create first thumbnail
    // Remember, first thumbnail should be largest thumbnail
    $img_s1 = imagecreatetruecolor($params[0]['size1'], $params[0]['size2']);
    if($ext=="png") {
            imagealphablending($img_s1, false);
            $colorTransparent = imagecolorallocatealpha($img_s1, 0, 0, 0, 127);
            imagefill($img_s1, 0, 0, $colorTransparent);
            imagesavealpha($img_s1, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($src);
            if ($trnprt_indx >= 0) {
                //its transparent
                $trnprt_color = imagecolorsforindex($src, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($img_s1, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($img_s1, 0, 0, $trnprt_indx);
                imagecolortransparent($img_s1, $trnprt_indx);
            }
        }
		$x_mid = $params[0]['size1']/2;  //horizontal middle
    	$y_mid = $params[0]['size2']/2; //vertical middle

	imagecopyresampled($img_s1, $src, ($x_mid-($s1_w/2)), ($y_mid-($s1_h/2)), 0, 0, $s1_w, $s1_h, $w, $h);

    // Other thumbnails are just downscaled copies of the first one
    for($i=1; $i<3; $i++)
    {
    // Create first thumbnail
    // Remember, first thumbnail should be largest thumbnail
    $img_demo = imagecreatetruecolor($s1_w, $s1_h);
    if($ext=="png") {
            imagealphablending($img_demo, false);
            $colorTransparent = imagecolorallocatealpha($img_demo, 0, 0, 0, 127);
            imagefill($img_demo, 0, 0, $colorTransparent);
            imagesavealpha($img_demo, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($src);
            if ($trnprt_indx >= 0) {
                //its transparent
                $trnprt_color = imagecolorsforindex($src, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($img_demo, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($img_demo, 0, 0, $trnprt_indx);
                imagecolortransparent($img_demo, $trnprt_indx);
            }
        }
	imagecopyresampled($img_demo, $src, 0, 0, 0, 0, $s1_w, $s1_h, $w, $h);

		if ($params[$i]['size1'] < $s1_w) {
		$thumbnail_width = $params[$i]['size1'];
		} else {
			$thumbnail_width = $s1_w;
		}
		
		if ($params[$i]['size2'] < $s1_h) {
		$thumbnail_height = $params[$i]['size2'];
		} else {
			$thumbnail_height = $s1_h;
		}

		$ratio_orig = $s1_w/$s1_h;
   
    	if ($thumbnail_width/$thumbnail_height > $ratio_orig) {
       		$new_height = $thumbnail_width/$ratio_orig;
       		$new_width = $thumbnail_width;
		} else {
       		$new_width = $thumbnail_height*$ratio_orig;
			   $new_height = $thumbnail_height;
    	}
		$x_mid = $new_width/2;  //horizontal middle
    	$y_mid = $new_height/2; //vertical middle
   
		$process = imagecreatetruecolor(round($new_width), round($new_height));
	    imagecopyresampled($process, $img_demo, 0, 0, 0, 0, $new_width, $new_height, $s1_w, $s1_h);
        $img_cur = imagecreatetruecolor($thumbnail_width, $thumbnail_height);
        if($ext=="png") {
            imagealphablending($img_cur, false);
            $colorTransparent = imagecolorallocatealpha($img_cur, 0, 0, 0, 127);
            imagefill($img_cur, 0, 0, $colorTransparent);
            imagesavealpha($img_cur, true);
        } elseif($ext=="gif") {
            $trnprt_indx = imagecolortransparent($img_demo);
            if ($trnprt_indx >= 0) {
                //its transparent
                $trnprt_color = imagecolorsforindex($img_demo, $trnprt_indx);
                $trnprt_indx = imagecolorallocate($img_cur, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
                imagefill($img_cur, 0, 0, $trnprt_indx);
                imagecolortransparent($img_cur, $trnprt_indx);
            }
        }
   
		imagecopyresampled($img_cur, $process, 0, 0, ($x_mid-($thumbnail_width/2)), ($y_mid-($thumbnail_height/2)), $thumbnail_width, $thumbnail_height, $thumbnail_width, $thumbnail_height);
		imagedestroy($process);
        
		if($ext=='jpg' || $ext=='jpeg')
		imagejpeg($img_cur, $params[$i]['file'], 90);
		if($ext=='gif')
		imagegif($img_cur, $params[$i]['file']);
		if($ext=='png')
		imagepng($img_cur, $params[$i]['file'], 9);

        imagedestroy($img_cur);
    }

	    imagedestroy($img_demo); // Destroy source image 

    // Saving first thumbnail 
    if($ext=='jpg' || $ext=='jpeg')
	imagejpeg($img_s1, $params[0]['file'], 90);
	if($ext=='gif')
	imagegif($img_s1, $params[0]['file']);
	if($ext=='png')
	imagepng($img_s1, $params[0]['file'], 9);
		
    imagedestroy($img_s1);
    imagedestroy($src); // Destroy source image 
    return true;
}

function getFor() {
if($_REQUEST['catID']){
	$catID=$_REQUEST['catID'];
	$return['status'] = '1';
} else {
	$return['status'] = '0';
	$return['error'] = "Wow! Database Error! Please reload the page and try again!";
	echo json_encode($return);
	exit;
}

if($_REQUEST['forGroup']){
	$forGroup=$_REQUEST['forGroup'];
} else {
	$forGroup=1;
}

$radioFor='';
$subSelect = '<select name="subCat" id="subCat" class="select required" rel="Subcategory"><option value="0">Select a Subcategory</option>';

$sql=mysql_query("select forID, forName from market_category_for where catID=$catID and forGroup=$forGroup order by forID asc");
$radioCount = 0;
while($row=mysql_fetch_array($sql))
{
$radioCount++;
$id=$row['forID'];
$data=$row['forName'];
if ($radioCount == 1) $check = ' checked="checked"'; else $check ='';
$radioFor .= '<label><input type="radio" name="optionFor" id="optionFor" value="'.$id.'" class="radio required"'.$check.' />'.$data.'</label>';
}

$sql2=mysql_query("select dataID, dataName from market_category_data where catID=$catID and parent=0 order by dataName asc");
$count = 0;
while($row2=mysql_fetch_array($sql2))
{
$count++;
$id=$row2['dataID'];
$data=$row2['dataName'];
$subSelect .= '<option value="'.$id.'">'.$data.'</option>';
}

$subSelect .= '</select>';

/*if ($dataID > 0) {
$sql3=mysql_query("select dataID, dataName from market_category_data where parent=$dataID order by dataName asc");
$total = mysql_num_rows($sql3);
if ($total > 0) {

$subSelectsub = '<select name="subCatsub" id="subCatsub" class="select">';
while($row3=mysql_fetch_array($sql3))
{
$id=$row3['dataID'];
$data=$row3['dataName'];
$subSelectsub .= '<option value="'.$id.'">'.$data.'</option>';
}
$subSelectsub .= '</select>';

} else {
$subSelectsub = '';
}
}
*/
$return['radioFor'] = $radioFor;
$return['subSelect'] = $subSelect;
//$return['subSelectsub'] = $subSelectsub;

echo json_encode($return);
exit;
}


function getForOnly() {
if($_REQUEST['catID']){
	$catID=$_REQUEST['catID'];
	$return['status'] = '1';
} else {
	$return['status'] = '0';
	$return['error'] = "Wow! Database Error! Please reload the page and try again!";
	echo json_encode($return);
	exit;
}

if($_REQUEST['forGroup']){
	$forGroup=$_REQUEST['forGroup'];
} else {
	$forGroup=1;
}

$radioFor='';

$sql=mysql_query("select forID, forName from market_category_for where catID=$catID and forGroup=$forGroup order by forID asc");
while($row=mysql_fetch_array($sql))
{
$id=$row['forID'];
$data=$row['forName'];
$radioFor .= '<label><input type="radio" name="optionFor" id="optionFor" value="'.$id.'" class="radio required" />'.$data.'</label><br/>';
}

$return['radioFor'] = $radioFor;

echo json_encode($return);
exit;
}


function getsubSelect() {
if($_REQUEST['dataID']){
	$dataID=$_REQUEST['dataID'];
	$return['status'] = '1';
} elseif($_REQUEST['dataID']==0) {
	$return['status'] = '1';
	$return['subSelect'] = '';
	echo json_encode($return);
	exit;
} else {
	$return['status'] = '0';
	$return['error'] = "Wow! Database Error! Please reload the page and try again!";
	echo json_encode($return);
	exit;
}


$sql=mysql_query("select dataID, dataName from market_category_data where parent=$dataID order by dataName asc");
$total = mysql_num_rows($sql);
if ($total > 0) {

$subSelect = '<select name="subCatsub" id="subCatsub" class="select">';
while($row=mysql_fetch_array($sql))
{
$id=$row['dataID'];
$data=$row['dataName'];
$subSelect .= '<option value="'.$id.'">'.$data.'</option>';
}
$subSelect .= '</select>';

} else {
$subSelect = '';
}

$return['subSelect'] = $subSelect;

echo json_encode($return);
exit;
}


function getTellsmore () {
if($_REQUEST['optionForID']){
	$optionForID=$_REQUEST['optionForID'];
} else {
	echo "Wow! Database Error! Please reload the page and try again!";
	exit;
}
	switch ($optionForID) {
	case 1; 
	?>

<p>
	<label for="price" class="label">Price: </label>
	<input name="price" type="text" id="price" maxlength="100" class="price" /><span class="inputPrice">US$</span>
</p>
<?php
		break;
	case ($optionForID <= 4); 
		break;
	case ($optionForID <= 6); 
	?>
<p>
	<label for="description" class="label">Extra Info</label>
	<input name="tellmore" type="text" readonly class="input" id="tellmore" value="Tells more" maxlength="255" />
</p>
<?php
		break;
	case 7; 
		break;
	case 10; 
	?>
<p>
	<label for="price" class="label">Price: </label>
	<input name="price" type="text" id="price" maxlength="100" class="price" /><span class="inputPrice">US$</span>
</p>
<?php
		break;
	case 11; 
	?>
<p>
	<label for="description" class="label">Extra Info</label>
	<input name="tellmore" type="text" readonly class="input" id="tellmore" value="Tells more" maxlength="255" />
</p>
<?php
		break;
	case 12; 
		break;
	case 13; 
	?>
<p>
	<label for="price" class="label">Price: </label>
	<input name="price" type="text" id="price" maxlength="100" class="price" /><span class="inputPrice">US$</span>
</p>
<?php
		break;
	case 14; 
		break;
	case ($optionForID <= 16); 
	?>
<p>
	<label for="description" class="label">Extra Info</label>
	<input name="tellmore" type="text" readonly class="input" id="tellmore" value="Tells more" maxlength="255" />
</p>
<?php
		break;
	case 17; 
		break;
	case ($optionForID <= 19); 
	?>
<p>
	<label for="description" class="label">Extra Info</label>
	<input name="tellmore" type="text" readonly class="input" id="tellmore" value="Tells more" maxlength="255" />
</p>
<?php
		break;
	case ($optionForID <= 20); 
		break;
	}

	exit;
}


function getExtraInfo () {
if($_REQUEST['forID']){
	$forID=$_REQUEST['forID'];
} else {
	echo "Wow! Database Error! Please reload the page and try again!";
	exit;
}

	switch ($forID) {
	case ($forID <= 4); 
		break;
	case 5; 
	?>
<p>
	<label for="price" class="label">Price: </label>
	<input name="price" type="text" id="price" maxlength="100" class="price" /><span class="inputPrice">US$</span>
</p>
<p>
	<label class="label" for="Vmake">Make: </label>
	<input name="Vmake" type="text" class="input" id="Vmake" maxlength="200" />
</p>
<p>
	<label class="label" for="Vmodel">Model: </label>
	<input name="Vmodel" type="text" class="input" id="Vmodel" maxlength="200" />
</p>
<p>
	<label class="label" for="Vtransmission">Transmission: </label>
	<select name="Vtransmission" class="selectMain" id="Vtransmission">
		<option value="Auto">Auto</option>
		<option value="Manual">Manual</option>
		<option value="Semi-Auto">Semi-Auto</option>
	</select>
</p>
<p>
	<label class="label" for="Vcondition">Condition: </label>
	<select name="Vcondition" class="selectMain" id="Vcondition">
		<option value="Certified PreOwned">Certified PreOwned</option>
		<option value="New">New</option>
		<option value="Used">Used</option>
	</select>
</p>
<p>
	<label class="label" for="Vcapacity">Engine Capacity: </label>
	<input name="Vcapacity" type="text" id="Vcapacity" class="input" />
	cc </p>
<p>
	<label class="label" for="Vyear">Year: </label>
	<input name="Vyear" type="text" class="sub year" id="Vyear" value="yyyy" maxlength="4" />
</p>
<p>
	<label class="label" for="Vmileage">Mileage: </label>
	<input name="Vmileage" type="text" class="input" id="Vmileage" maxlength="100" />
	miles </p>
<p>
	<label class="label" for="Vseller">Seller Type: </label>
	<select name="Vseller" class="selectMain" id="Vseller">
		<option value="Dealer">Dealer</option>
		<option value="Private Party">Private Party</option>
	</select>
</p>
<?php
		break;
	case 6; 
	?>
<p>
	<label for="price" class="label">Price: </label>
	<input name="price" type="text" id="price" maxlength="100" class="price" /><span class="inputPrice">US$</span>
</p>
<p>
	<label class="label" for="Vmake">Make: </label>
	<input name="Vmake" type="text" id="Vmake" class="input" />
</p>
<p>
	<label class="label" for="Vmodel">Model: </label>
	<input name="Vmodel" type="text" id="Vmodel" class="input" />
</p>
<p>
	<label class="label" for="Vtransmission">Transmission: </label>
	<select name="Vtransmission" class="selectMain" id="Vtransmission">
		<option value="Auto">Auto</option>
		<option value="Manual">Manual</option>
		<option value="Semi-Auto">Semi-Auto</option>
	</select>
</p>
<p>
	<label class="label" for="Vcondition">Condition: </label>
	<select name="Vcondition" class="selectMain" id="Vcondition">
		<option value="Certified PreOwned">Certified PreOwned</option>
		<option value="New">New</option>
		<option value="Used">Used</option>
	</select>
</p>
<p>
	<label class="label" for="Vcapacity">Engine Capacity: </label>
	<input name="Vcapacity" type="text" id="Vcapacity" class="input" />
	cc </p>
<?php
		break;
	case 7; 
		break;
	case 8; 
	?>
<p>
	<label for="price" class="label">Price: </label>
	<input name="price" type="text" id="price" maxlength="100" class="price" /><span class="inputPrice">US$</span>
</p>
<p>
	<label class="label" for="Pbedroom">Bedrooms: </label>
	<input name="Pbedroom" type="text" class="input" id="Pbedroom" maxlength="3" />
</p>
<p>
	<label class="label" for="Pbathroom">Bathrooms: </label>
	<input name="Pbathroom" type="text" class="input" id="Pbathroom" maxlength="3" />
</p>
<p>
	<label class="label" for="Pyear">Year Built: </label>
	<input name="Pyear" type="text" class="sub" id="Pyear" value="yyyy" maxlength="4" />
</p>
<p>
	<label class="label" for="Ptenure">Tenure: </label>
	<select name="Ptenure" class="selectMain" id="Ptenure">
		<option value="Free hold">Freehold</option>
		<option value="Lease hold">Leasehold</option>
		<option value="99 years">99 years</option>
	</select>
</p>
<p>
	<label class="label" for="Psqfeet">Sq. Feet: </label>
	<input name="Psqfeet" type="text" class="input" id="Psqfeet" maxlength="255" />
</p>
<p>
	<label class="label" for="Pseller">For Sale by: </label>
	<select name="Pseller" class="selectMain" id="Pseller">
		<option value="Owner">Owner</option>
		<option value="Agent/Broker">Agent/Broker</option>
		<option value="Developer">Developer</option>
	</select>
</p>
<?php
		break;
	case 9; 
	?>
<p>
	<label for="price" class="label">Price: </label>
	<input name="price" type="text" id="price" maxlength="100" class="price" /><span class="inputPrice">US$</span>
</p>
<p>
	<label class="label" for="Pbedroom">Bedrooms: </label>
	<input name="Pbedroom" type="text" class="input" id="Pbedroom" maxlength="3" />
</p>
<p>
	<label class="label" for="Pbathroom">Bathrooms: </label>
	<input name="Pbathroom" type="text" class="input" id="Pbathroom" maxlength="3" />
</p>
<p>
	<label class="label" for="Psqfeet">Sq. Feet: </label>
	<input name="Psqfeet" type="text" class="input" id="Psqfeet" maxlength="255" />
</p>
<p>
	<label class="label" for="Ppet">Pet Allowed: </label>
	<select name="Ppet" class="selectMain" id="Ppet">
		<option value="Dogs OK">Dogs OK</option>
		<option value="Cats OK">Cats OK</option>
		<option value="Dogs OK/Cats OK">Dogs OK/Cats OK</option>
		<option value="No Pets">No Pets</option>
	</select>
</p>
<?php
		break;
	case 10; 
		break;
	case 11; 
	?>
<p>
	<label class="label" for="Jcompany">Company: </label>
	<input name="Jcompany" type="text" class="input" id="Jcompany" />
</p>
<p>
	<label class="label" for="Jtype">Job Type: </label>
	<select name="Jtype" class="selectMain" id="Jtype">
		<option value="Contractor">Contractor</option>
		<option value="Employee">Employee</option>
		<option value="Gig">Gig</option>
		<option value="Intern">Intern</option>
		<option value="Volunteer">Volunteer</option>
		<option value="Full-time">Full-time</option>
		<option value="Part-time">Part-time</option>
	</select>
</p>
<?php
		break;
	case 12; 
		break;
	case 13; 
		break;
	case 14; 
		break;
	case ($forID <= 16); 
	?>
<?php if ($forID == 15) {?>
<p>
	<label for="price" class="label">Price: </label>
	<input name="price" type="text" id="price" maxlength="100" class="price" /><span class="inputPrice">US$</span>
</p>
<?php } ?>
<div class="datetimepicker">
	<p>
		<label class="label" for="Tdate">Event Date: </label>
		<input name="Tdate" type="text" class="input" id="Tdate" readonly="readonly" />
	<p>
	<p>
		<label class="label" for="Ttime">Event Time: </label>
		<input name="Ttime" type="text" class="input" id="Ttime" readonly="readonly" />
	</p>
	<pre>
																		$('#Tdate').datetimepicker({
																			altField: "#Ttime",
																			dateFormat: "yy-mm-dd",
																			ampm: true
																		});
																		</pre>
	</p>
</div>
<label class="label" for="Tticket"># Tickets: </label>
<input name="Tticket" type="text" class="input" id="Tticket" maxlength="11" />
</p>
<?php
		break;
	case 17; 
		break;
	case ($forID <= 19); 
	?>
<?php if ($forID == 18) {?>
<p>
	<label for="price" class="label">Price: </label>
	<input name="price" type="text" id="price" maxlength="100" class="price" /><span class="inputPrice">US$</span>
</p>
<?php } ?>
<p>
	<label class="label" for="Ebreed">Breed: </label>
	<input name="Ebreed" type="text" class="input" id="Ebreed" maxlength="255" />
</p>
<p>
	<label class="label" for="Esex">Sex: </label>
	<select name="Esex" class="selectMain" id="Esex">
		<option value=""></option>
		<option value="Male">Male</option>
		<option value="Female">Female</option>
	</select>
</p>
<p>
	<label class="label" for="Eage">Age: </label>
	<select name="Eage" class="selectMain" id="Eage">
		<option value="Adult">Adult</option>
		<option value="Baby">Baby</option>
		<option value="Senior">Senior</option>
		<option value="Young">Young</option>
	</select>
</p>
<?php
		break;
	case ($forID <= 20); 
		break;
	}

	exit;
}


function uploadPic () {
	global $CONST_LINK_ROOT, $SITE_MAIN_WWW_ROOT;
	
	$return = array('status' => '0');

	$WUserID = $_REQUEST['userid'];
	$WUsername = mysql_fetch_object(mysql_query("SELECT mem_username FROM members WHERE mem_userid=$WUserID"));
	$main_dir = "/home/wauhaha/public_html/members";
	$member_dir = "/home/wauhaha/public_html/members/".$WUsername->mem_username;
	$uploaddir = "/home/wauhaha/public_html/members/".$WUsername->mem_username."/marketer/"; // Directory for file storing

	checkfolder($member_dir);
	checkfolder($uploaddir);
	checkindex($main_dir,$member_dir);
	checkindex($main_dir,$uploaddir);

    $fieldname = $_REQUEST['fieldname'];
	 $name = $_FILES[$fieldname];

		if ( $name['size'] > 4 * 1024 * 1024)
		{
			$error= $name['name'] . ' is too large. Please upload only files smaller than 4Mb!';
			$return = array_merge_recursive($return,  array( 'error' => $error));
		}
		if (!($size = @getimagesize($name['tmp_name']) ) )
		{
			$error='Please upload only images, no other files are supported.';
			$return = array_merge_recursive($return,  array( 'error' => $error));
		}
		if (!in_array($size[2], array(1, 2, 3) ) )
		{
			$error='Please upload only images of type JPEG, GIF or PNG.';
			$return = array_merge_recursive($return,  array( 'error' => $error));
		}

		if ($error) {
			$return['status'] = '0';
			echo json_encode($return);
			die;
		} else {
			$filename = basename($name['name']);

        // Upload file or return error message information
        if(!move_uploaded_file($name['tmp_name'], $uploaddir.$filename))
		{
			$error  = "Could not upload file " .$name['tmp_name'];
			$return = array_merge_recursive($return,  array( 'error' => $error));
		}

		$a_filename = preg_split("/\./",$filename);
		$ext = end($a_filename);
		$newname = md5('wauhaha'.array_shift($a_filename));
		
		// Setting params array for thumbnail_generator 
		$params = array(array('size1' => 600,
									'size2' => 450,
                          'file' => $uploaddir.$newname.".".$ext),
						  array('size1' => 170,
								  'size2' => 170,
                          'file' => $uploaddir.$newname.'_med.'.$ext),
						  array('size1' => 100,
								  'size2' => 100,
                          'file' => $uploaddir.$newname.'_small.'.$ext)
								  );

    	if (thumbnail_generator($uploaddir.$filename, $params, $ext) == false){
			$return = array_merge_recursive($return,  array( 'error' => "Error processing uploaded file {$filename}"));
			echo json_encode($return);
			exit;
		}

			unlink ($uploaddir.$filename);

			$return['status'] ='1';
			$return['thumb'] = $SITE_MAIN_WWW_ROOT."/members/".$WUsername->mem_username."/marketer/".$newname.'_small.'.$ext;
			$return['med'] = $SITE_MAIN_WWW_ROOT."/members/".$WUsername->mem_username."/marketer/".$newname.'_med.'.$ext;
			$return['ori'] = $SITE_MAIN_WWW_ROOT."/members/".$WUsername->mem_username."/marketer/".$newname.'.'.$ext;
		}
		
			echo json_encode($return);
			exit;
}


function putInfo () {
	global $CONST_LINK_ROOT, $SITE_MAIN_WWW_ROOT;

	$_REQUEST['status' ] ='0';
	$return = array('status' => '0');
//	print_r($_REQUEST);

	$WUserID = $_REQUEST['userid'];
	$mainCat = $_REQUEST['mainCat'];
	$optionFor = $_REQUEST['optionFor'];
	$title = htmlspecialchars($_REQUEST['title'], ENT_QUOTES);
//	$why = htmlspecialchars($_REQUEST['why'], ENT_QUOTES);
	$location = htmlspecialchars($_REQUEST['location'], ENT_QUOTES);
	$Country = $_REQUEST['Country'];
	$description = htmlentities($_REQUEST['description'], ENT_QUOTES);
	$price = htmlspecialchars($_REQUEST['price'], ENT_QUOTES);
	$price2 = htmlspecialchars($_REQUEST['price2'], ENT_QUOTES);
	$delivery = htmlspecialchars($_REQUEST['delivery'], ENT_QUOTES);
	$keyword = htmlspecialchars($_REQUEST['keyword'], ENT_QUOTES);
	$tags = htmlspecialchars($_REQUEST['tags'], ENT_QUOTES);
	$commision = htmlspecialchars($_REQUEST['commision'], ENT_QUOTES);
	$subCat = $_REQUEST['subCat'];
	$subCatsub = $_REQUEST['subCatsub'];

	$imagefield = array();
	$imagefield["image1"] = htmlspecialchars(stripslashes($_REQUEST['imagefield1']), ENT_QUOTES);
	$imagefield["image2"] = htmlspecialchars(stripslashes($_REQUEST['imagefield2']), ENT_QUOTES);
	$imagefield["image3"] = htmlspecialchars(stripslashes($_REQUEST['imagefield3']), ENT_QUOTES);

	$imagefieldthumb["image1"] = htmlspecialchars(stripslashes($_REQUEST['imagefield1ori']), ENT_QUOTES);
	$imagefieldthumb["image2"] = htmlspecialchars(stripslashes($_REQUEST['imagefield2ori']), ENT_QUOTES);
	$imagefieldthumb["image3"] = htmlspecialchars(stripslashes($_REQUEST['imagefield3ori']), ENT_QUOTES);

	$imagefieldmed["image1"] = htmlspecialchars(stripslashes($_REQUEST['imagefield1med']), ENT_QUOTES);
	$imagefieldmed["image2"] = htmlspecialchars(stripslashes($_REQUEST['imagefield2med']), ENT_QUOTES);
	$imagefieldmed["image3"] = htmlspecialchars(stripslashes($_REQUEST['imagefield3med']), ENT_QUOTES);

	$sql="Insert into market_Post set mem_userid='$WUserID', mainCat='$mainCat', optionFor='$optionFor', title='$title', location='$location', Country='$Country', description='$description', price='$price', price2='$price2', delivery='$delivery', keyword='$keyword', tags='$tags', commision='$commision', subCat='$subCat', subCatsub='$subCatsub', postDate=now(), expDate=ADDDATE(now(), INTERVAL 3 MONTH)";
	$squery=mysql_query($sql);
	$postID=mysql_insert_id();
	
	if (count($imagefield)> 0) {
	foreach($imagefield as $field=>$data){
		if (!$data) continue;
		foreach($imagefieldmed as $field2=>$data2){
			if (!$data2) continue;
			if ($field==$field2) {
				foreach($imagefieldthumb as $field1=>$data1){
				if (!$data1) continue;
				if ($field2==$field1) {
				$sql_Image="Insert into market_PostPhoto set postID='$postID', photoURL='".$data1."', photoThumb='".$data."', photoMed='".$data2."', mem_userid='$WUserID'";
				$sql_Image_query=mysql_query($sql_Image);
				}
				}
		}
		}
	}
	}
	
	foreach($_POST as $field=>$data){
		$type = substr($field, 0, 1);
		if ($type=='V') {
			$PostVehicle[] = $field."='".$data."'";
		}
		if ($type=='P') {
			$PostProperty[] = $field."='".$data."'";
		}
		if ($type=='J') {
			$PostJob[] = $field."='".$data."'";
		}
		if ($type=='T') {
			$PostTicket[] = $field."='".$data."'";
		}
		if ($type=='E') {
			$PostPet[] = "P".$field."='".$data."'";
		}
	}

	if (!empty($PostVehicle)){
		$query = implode(", ", $PostVehicle);
		$sql_PostVehicle="Insert into market_PostVehicle set postID='$postID', mem_userid='$WUserID', ".$query;
		$sql_PostVehicle_query=mysql_query($sql_PostVehicle) or die (mysql_error());
	}

	if (!empty($PostProperty)){
		$query = implode(", ", $PostProperty);
		$sql_PostProperty="Insert into market_PostProperty set postID='$postID', mem_userid='$WUserID', ".$query;
		$sql_PostProperty_query=mysql_query($sql_PostProperty) or die (mysql_error());
	}

	if (!empty($PostJob)){
		$query = implode(", ", $PostJob);
		$sql_PostJob="Insert into market_PostJob set postID='$postID', mem_userid='$WUserID', ".$query;
		$sql_PostJob_query=mysql_query($sql_PostJob) or die (mysql_error());
	}

	if (!empty($PostTicket)){
		$query = implode(", ", $PostTicket);
		$sql_PostTicket="Insert into market_PostTicket set postID='$postID', mem_userid='$WUserID', ".$query;
		$sql_PostTicket_query=mysql_query($sql_PostTicket) or die (mysql_error());
	}

	if (!empty($PostPet)){
		$query = implode(", ", $PostPet);
		$sql_PostPet="Insert into market_PostPet set postID='$postID', mem_userid='$WUserID', ".$query;
		$sql_PostPet_query=mysql_query($sql_PostPet) or die (mysql_error());
	}

if (!$squery) {
	$return['error'] = 'Database Error!';
} else {
	$return['status'] ='1';
	$return['success'] = 'Item inserted successfully!';
	$return['postID'] = $postID;
}
$_SESSION["postTitle"] = "";
echo json_encode($return);
exit;
}


function editInfo () {
	global $CONST_LINK_ROOT, $SITE_MAIN_WWW_ROOT;

	$_REQUEST['status' ] ='0';
	$return = array('status' => '0');
//	print_r($_REQUEST);

	$WUserID = $_REQUEST['userid'];
	$postID = $_REQUEST['postID'];
	$title = htmlspecialchars($_REQUEST['title'], ENT_QUOTES);
	$why = htmlspecialchars($_REQUEST['why'], ENT_QUOTES);
	$location = htmlspecialchars($_REQUEST['location'], ENT_QUOTES);
	$Country = $_REQUEST['Country'];
	$description = htmlentities($_REQUEST['description'], ENT_QUOTES);
	$price = htmlspecialchars($_REQUEST['price'], ENT_QUOTES);
	$price2 = htmlspecialchars($_REQUEST['price2'], ENT_QUOTES);
	$delivery = htmlspecialchars($_REQUEST['delivery'], ENT_QUOTES);
	$keyword = htmlspecialchars($_REQUEST['keyword'], ENT_QUOTES);
	$tags = htmlspecialchars($_REQUEST['tags'], ENT_QUOTES);
	$commision = htmlspecialchars($_REQUEST['commision'], ENT_QUOTES);
	$subCat = $_REQUEST['subCat'];
	$subCatsub = $_REQUEST['subCatsub'];

	$imagefield = array();
	$imagefield["image1"] = htmlspecialchars(stripslashes($_REQUEST['imagefield1']), ENT_QUOTES);
	$imagefield["image2"] = htmlspecialchars(stripslashes($_REQUEST['imagefield2']), ENT_QUOTES);
	$imagefield["image3"] = htmlspecialchars(stripslashes($_REQUEST['imagefield3']), ENT_QUOTES);

	$imagefieldthumb["image1"] = htmlspecialchars(stripslashes($_REQUEST['imagefield1ori']), ENT_QUOTES);
	$imagefieldthumb["image2"] = htmlspecialchars(stripslashes($_REQUEST['imagefield2ori']), ENT_QUOTES);
	$imagefieldthumb["image3"] = htmlspecialchars(stripslashes($_REQUEST['imagefield3ori']), ENT_QUOTES);

	$imagefieldmed["image1"] = htmlspecialchars(stripslashes($_REQUEST['imagefield1med']), ENT_QUOTES);
	$imagefieldmed["image2"] = htmlspecialchars(stripslashes($_REQUEST['imagefield2med']), ENT_QUOTES);
	$imagefieldmed["image3"] = htmlspecialchars(stripslashes($_REQUEST['imagefield3med']), ENT_QUOTES);

$active_query=mysql_query("SELECT postID FROM market_Post where mem_userid=$WUserID and postID=$postID limit 1") or die(mysql_error());
$activeTotal = mysql_num_rows($active_query);
if($activeTotal>0) {
	$sql="UPDATE market_Post set title='$title', location='$location', Country='$Country', description='$description', price='$price', price2='$price2', delivery='$delivery', keyword='$keyword', tags='$tags', commision='$commision', subCat='$subCat', subCatsub='$subCatsub', modDate=now() where mem_userid='$WUserID' and postID='$postID'";
	$squery=mysql_query($sql);
	
   $query1="Delete from market_PostPhoto where mem_userid=$WUserID and postID=$postID";
   $result1=mysql_query($query1) or die(mysql_error());

	if (count($imagefield)> 0) {
	foreach($imagefield as $field=>$data){
		if (!$data) continue;
		foreach($imagefieldmed as $field2=>$data2){
			if (!$data2) continue;
			if ($field==$field2) {
				foreach($imagefieldthumb as $field1=>$data1){
				if (!$data1) continue;
				if ($field==$field1) {
				$sql_Image="Insert into market_PostPhoto set postID='$postID', photoURL='".$data1."', photoThumb='".$data."', photoMed='".$data2."', mem_userid='$WUserID'";
				$sql_Image_query=mysql_query($sql_Image);
				}
				}
		}
		}
	}
	}
	
	foreach($_POST as $field=>$data){
		$type = substr($field, 0, 1);
		if ($type=='V') {
			$PostVehicle[] = $field."='".$data."'";
		}
		if ($type=='P') {
			$PostProperty[] = $field."='".$data."'";
		}
		if ($type=='J') {
			$PostJob[] = $field."='".$data."'";
		}
		if ($type=='T') {
			$PostTicket[] = $field."='".$data."'";
		}
		if ($type=='E') {
			$PostPet[] = "P".$field."='".$data."'";
		}
	}

	if (!empty($PostVehicle)){
		$query = implode(", ", $PostVehicle);
		$sql_PostVehicle="REPLACE INTO market_PostVehicle set postID='$postID', mem_userid='$WUserID', ".$query;
		$sql_PostVehicle_query=mysql_query($sql_PostVehicle) or die (mysql_error());
	}

	if (!empty($PostProperty)){
		$query = implode(", ", $PostProperty);
		$sql_PostProperty="REPLACE INTO market_PostProperty set postID='$postID', mem_userid='$WUserID', ".$query;
		$sql_PostProperty_query=mysql_query($sql_PostProperty) or die (mysql_error());
	}

	if (!empty($PostJob)){
		$query = implode(", ", $PostJob);
		$sql_PostJob="REPLACE INTO market_PostJob set postID='$postID', mem_userid='$WUserID', ".$query;
		$sql_PostJob_query=mysql_query($sql_PostJob) or die (mysql_error());
	}

	if (!empty($PostTicket)){
		$query = implode(", ", $PostTicket);
		$sql_PostTicket="REPLACE INTO market_PostTicket set postID='$postID', mem_userid='$WUserID', ".$query;
		$sql_PostTicket_query=mysql_query($sql_PostTicket) or die (mysql_error());
	}

	if (!empty($PostPet)){
		$query = implode(", ", $PostPet);
		$sql_PostPet="REPLACE INTO market_PostPet set postID='$postID', mem_userid='$WUserID', ".$query;
		$sql_PostPet_query=mysql_query($sql_PostPet) or die (mysql_error());
	}

if (!$squery) {
	$return['error'] = 'Database Error!';
} else {
	$return['status'] ='1';
	$return['success'] = 'Item updated successfully!';
	$return['postID'] = $postID;
}

} else {
	$return['error'] = 'Database Error!';
die;
}
echo json_encode($return);
exit;
}


function storeTitle () {
	$title = $_REQUEST['title' ];
	$return = array('status' => '0');
	
	if (!empty($title)) {
		$return['status'] ='1';
		$_SESSION["postTitle"] = $title;
	}

echo json_encode($return);
exit;
}
?>
