<?php
/******************************************************************************************************/
// Get Districts
$d = array();
$districts = array();
$q = "select * from cyprus_districts order by district asc;";
$r = @mysql_query($q);
if($r && mysql_num_rows($r) > 0) {
	while ($row = mysql_fetch_assoc($r)) {
		$d [] = array_map('stripslashes', $row);
		$districts [$row['dcode']] = stripslashes($row['district']);
	}
}


// Get Locations
$a = array();
$locations = array();
$q = "select * from cyprus_locations order by location asc;";
$r = @mysql_query($q);
if($r && mysql_num_rows($r) > 0) {
	while ($row = mysql_fetch_assoc($r)) {
		$dcode = $row['dcode'];
		$lcode = $row['lcode'];
		
		if(isset($locations[$dcode])) {
			$locations[$dcode][$lcode] = stripslashes($row['location']);
		}
		else {
			$locations[$dcode] = array();
			$locations[$dcode][$lcode] = stripslashes($row['location']);
		}
		
	}
}
/******************************************************************************************************/
//echo '<pre>', var_export($_FILES, true), '</pre>';
//echo '<pre>', var_export($_POST, true), '</pre>';
$advert_fields = array("adv_code", "cust_code", "member_id", "website", "domainname", "redirect_domain", "redirect_url",  "WebSiteTitle", "title_en", "title_tr", "short_title_en", "description_en", "ContactPerson", "Directors", "YearOfEstablishment", "NumberOfEmployees", "MemberOf", "open_window", "advertisment", "active", "added_on", "register", "views", "clicks", "clicks_on_www", "meta_description");
$advert_location_fields = array("advertisment_id", "member_id", "adv_code", "cust_code", "location_title", "street", "street_no", "building_name", "floor", "flat", "city", "postalcode", "area", "district", "dcode", "lcode", "country", "pobox", "pobox_postalcode", "contact_name", "contact_title", "tel1", "tel2", "mobile1", "mobile2", "fax", "email", "main_location", "active", "created", "created_by", "updated", "updated_by");

$advert_mandatory = array(
		"adv_code" => "Advert UID", 
		"cust_code" => "Customer UID", 
		"website" => "Website URL", 
		//"WebSiteTitle" => "Website Title", 
		//"title_en" => "Advert Title", 
		//"title_tr" => "Friendly URL", 
		"short_title_en" => "Display Name", 
		"description_en" => "Description", 
		"ContactPerson" => "Contact Person", 
		//"Directors" => "Directors", 
		//"YearOfEstablishment" => "Year Of Establishment", 
		//"NumberOfEmployees" => "Number Of Employees", 
		//"MemberOf" => "Member Of",
        "meta_description" => "Short Description",
		"open_window" => "Advert Opens in", 
		//"advertisment" => "Advert Logo", 
		//"active" => "Advert Status", 
		//"added_on" => "Registration Date", 
		//"register" => "Registration Source", 
		//"views" => "Views", 
		//"clicks" => "Clicks", 
		//"clicks_on_www" => "Clicks On WWW"
);

$advert_unique = array(
		"short_title_en" => "Display Name", 
		"website" => "Website URL",
		//"domainname" => "Website URL Domain",
		//"redirect_domain" => "Website URL Redirect Domain"
);


$location_mandatory = array(
		"location_title" => "Location Title", 
		"street" => "Street Name", 
		//"street_no" => "Street Number", 
		//"building_name" => "Building Name", 
		//"floor" => "Floor", 
		//"flat" => "Flat", 
		//"city" => "Town/Village", 
		"dcode"	=> "District",
		"lcode"	=> "Location",
		"postalcode" => "Postal Code", 
		//"area" => "Area", 
		//"district" => "District", 
		"country" => "Country", 
		//"pobox" => "P.O. Box", 
		//"pobox_postalcode" => "P.O. Box Postal Code", 
		"contact_name" => "Contact Name", 
		//"contact_title" => "Contact Title", 
		"tel1" => "Fixed Phone 1", 
		//"tel2" => "Fixed Phone 2", 
		//"mobile1" => "Mobile Phone 1", 
		//"mobile2" => "Mobile Phone 2", 
		//"fax" => "Fax", 
		"email" => "Email", 
		"main_location" => "Is Main Location", 
		//"active" => "Location Status", 
		//"created", "created_by", "updated", "updated_by"
);

$location_unique = array(
		"tel1" => "Fixed Phone 1", 
		"tel2" => "Fixed Phone 2", 
		"mobile1" => "Mobile Phone 1", 
		"mobile2" => "Mobile Phone 2", 
		"fax" => "Fax", 
		"email" => "Email"
);

//echo '<br/>$_POST[\'action_trigger\'] = ', $_POST['action_trigger'];

if(isset($_POST['chcAction'])) {
	$advert_action_type = $_POST['chcAction'];
	
	// Validate the WebSite URL *******************************************************************/
	
	$website_url = $_POST['website'];
	
	$h = new httpParser($website_url);
	$h->request_headers();
	$final_url = "";

	$ret_data = array();
	$ret_data ['raw'] = $h->raw_headers;
	$ret_data ['status'] = $h->final_status;
	$ret_data['advert_url'] = "";
	$ret_data['domainname'] = "";
	$ret_data['redirect_domain'] = "";
	$ret_data['redirect_url'] = "";
	
	//echo '<div class="error"><pre>', print_r($h->all_headers), '</pre></div>';
	
	if($h->final_status == "VALID") {
		if($h->num_redirect > 0) {
			//echo '<pre>', var_export($h, true), '</pre>';
			$rq_one = $h->all_headers[0];
			//echo '<pre>', var_export($rq_one, true), '</pre>';
			$rq_last = $h->all_headers[$h->num_redirect];
			//echo '<pre>', var_export($rq_last, true), '</pre>';
			if($rq_one['subdomain'] == "" || $rq_one['subdomain'] == "www") {
				$rq_one['host'] = "www." . str_replace("www.", "", $rq_one['host']);
			}
			
			if($rq_last['subdomain'] == "" || $rq_last['subdomain'] == "www") {
				$rq_last['host'] = "www." . str_replace("www.", "", $rq_last['host']);
			}
			
			if(str_ireplace("www.", "", $rq_one['host']) != str_ireplace("www.", "", $rq_last['host'])) {
				$final_url .= $rq_last['host'];
				if($rq_last['path'] != "") {
					$final_url .= "/" . $rq_last['path'];
				}
				if($rq_last['query'] != "") {
					$final_url .= "?" . $rq_last['query'];
				}
				$final_url = "http://" . str_replace("//", "/", $final_url);
				$ret_data['advert_url'] = "http://" . str_replace("//", "/", $rq_one['host'] . ($rq_one['path'] != "" ? "/" . $rq_one['path'] : "") . ($rq_one['query'] != "" ? "?" . $rq_one['query'] : ""));
				$ret_data['domainname'] = $rq_one['host'];
				$ret_data['redirect_domain'] = $rq_last['host'];
				$ret_data['redirect_url'] = $final_url;
				
			}
			elseif ($rq_one['path'] != $rq_last['path']) {
				$final_url .= $rq_last['host'];
				if($rq_last['path'] != "") {
					$final_url .= "/" . $rq_last['path'];
				}
				if($rq_last['query'] != "") {
					$final_url .= "?" . $rq_last['query'];
				}
				$final_url = "http://" . str_replace("//", "/", $final_url);
				$ret_data['advert_url'] = $final_url;
				$ret_data['domainname'] = $rq_one['host'];
				$ret_data['redirect_domain'] = "";
				$ret_data['redirect_url'] = "";
				
			}
			else {
				if(str_ireplace("www.", "", $rq_one['host']) == str_ireplace("www.", "", $rq_last['host'])) {
					$final_url .= $rq_last['host'];
					if($rq_last['path'] != "") {
						$final_url .= "/" . $rq_last['path'];
					}
					if($rq_last['query'] != "") {
						$final_url .= "?" . $rq_last['query'];
					}
					$final_url = "http://" . str_replace("//", "/", $final_url);
					$ret_data['advert_url'] = $final_url;
					$ret_data['domainname'] = $rq_one['host'];
					$ret_data['redirect_domain'] = "";
					$ret_data['redirect_url'] = "";
					
					//echo '<pre>', var_export($ret_data, true), '</pre>';
					
				}
			}
		}	
		else {
			$rq_one = $h->all_headers[0];
			
			//echo '<pre>', var_export($rq_one, true), '</pre>';
			
			
			if($rq_one['subdomain'] == "" || $rq_one['subdomain'] == "www") {
				$rq_one['host'] = "www." . str_replace("www.", "", $rq_one['host']);
			}
			
			$final_url .= $rq_one['host'];
			if($rq_one['path'] != "") {
				$final_url .=  "/" . $rq_one['path'];
			}
			if($rq_one['query'] != "") {
				$final_url .=  "?" . $rq_one['query'];
			}
			$final_url = "http://" . str_replace("//", "/", $final_url);
			$ret_data['advert_url'] = $final_url;
			$ret_data['domainname'] = $rq_one['host'];
			$ret_data['redirect_domain'] = "";
			$ret_data['redirect_url'] = "";
		}
	}
	elseif($h->final_status == "INVALID") {
		$ret_data['err'] = $h->final_message;
		$ret_data ['advert_url'] = $_POST['website'];
		$ret_data ['domainname'] = "";
		$ret_data ['redirect_domain'] = "";
		$ret_data ['redirect_url'] = "";
		$err .= "<br/><strong>Website URL</strong> -- INVALID Free Listing Website URL: " . $h->final_message;
	}
	elseif($h->final_status == "TEMPORARY") {
		$ret_data['err'] = $h->final_message;
		$rq_one = $h->all_headers[0];
		$final_url .= $rq_one['host'];
		if($rq_one['path'] != "") {
			$final_url .=  "/" . $rq_one['path'];
		}
		if($rq_one['query'] != "") {
			$final_url .=  "?" . $rq_one['query'];
		}
		$final_url = "http://" . str_replace("//", "/", $final_url);
		$ret_data['advert_url'] = $final_url;
		$ret_data['domainname'] = $rq_one['host'];
		$ret_data['redirect_domain'] = "";
		$ret_data['redirect_url'] = "";
	}
	else {
		$err .= "<br/>INVALID Advert URL ";
	}
	
	if($ret_data['domainname'] != "") {
		$rdomain = mysql_real_escape_string(str_ireplace('www.', '', $ret_data['domainname']));
		$q = "select * from domaincategories where domainname like '%$rdomain%'";
		$r = @mysql_query($q);
		if($r && mysql_num_rows($r) > 0) {
			$err .= "<br/>The website belongs to Cyprunet. Please use your own website in the Website URL field.";
		}
	}
	
	
	//echo '<pre>',print_r($ret_data), '</pre>';
	$_POST['website'] = $ret_data['advert_url'];
	$_POST['website'] = str_replace("/./", "/", $_POST['website']);
	$_POST['domainname'] = $ret_data['domainname'];
	$_POST['redirect_domain'] = $ret_data['redirect_domain'];
	
	//echo '<pre>', var_export($_POST, true), '</pre>';
	
	// END - Validate WebSite URL *****************************************************************/
	
	if($advert_action_type == "add" || $advert_action_type == "edit" && $err == "") {
		
		foreach ($_POST as $key=>$val) {
			${$key} = is_array($_POST[$key]) ? $_POST[$key] : stripslashes(trim($_POST[$key]));
		}
		
		//echo '<br/>$website = ' . $website;
		
		
		if(isset($_POST['dcode']) && trim($_POST['dcode']) != "") {
			$district = $districts[$_POST['dcode']];
			
			if(isset($_POST['lcode']) && trim($_POST['lcode']) != "") {
				$city = $locations[$_POST['dcode']][$_POST['lcode']];
			}
		}
		
		
		$must_uplod = false;
		if(!isset($_FILES['logo_image']) || $_FILES['logo_image']['size'] <= 0) {
			if(isset($_POST['no_logo'])) {
				$err .= "<br>Uploading a Logo Image is required.";
			}
			
		}
		else {
			if($_FILES['logo_image']['size']>0) {
				$must_uplod = true;
			}
		}
		
		// Make the friendly_url **************************************************************/
		if(!isset($title_tr) || $title_tr == "") {
			$title_tr = makeFriendlyUrl($short_title_en);
		}
		if($advert_action_type == "add") {
			$q = "select * from advertisment where title_tr='$title_tr';";
		}
		if($advert_action_type == "edit") {
			$q = "select * from advertisment where title_tr='$title_tr' and advertisment_id!='$advertisment_id';";
		}
		$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
		if($r && mysql_num_rows($r)>0) {
			$title_tr .= "_" . date("is");
		}
		// END - Make the friendly_url **************************************************************/
		
		
		// Check for manadatory Fields
		foreach ($advert_mandatory as $fld=>$label) {
			if(!isset($_POST[$fld]) || trim($_POST[$fld]) == "") {
				$err .= "<br/><strong>$label</strong> is a mandatory field.";
			}
		}
		
		if($advert_action_type == "add" || $advert_action_type == "edit") {
			foreach ($location_mandatory as $fld=>$label) {
				if(!isset($_POST[$fld]) || trim($_POST[$fld]) == "") {
					$err .= "<br/><strong>$label</strong> is a mandatory field.";
				}
			}
		}
		
		if($err == "") {
			
			$change_owner = false;
			
			if(isset($_POST['new_member_id']) && intval($_POST['new_member_id']) > 0) {
				$qnm = "select * from members where member_id='{$_POST['new_member_id']}';";
				//echo "<br/>$qnm";
				$rnm = mysql_query($qnm) or die("<strong>$qnm</strong>".mysql_error());
				if($rnm && mysql_num_rows($rnm)>0) {
					$rownm = mysql_fetch_assoc($rnm);
					
					$new_member_id = $rownm['member_id'];
					$new_cust_code = $rownm['cust_code'];
					
					$member_id = $new_member_id;
					$cust_code = $new_cust_code;
					
					$change_owner = true;
				}
			}

			
			// Check for unique values
			
			// Step 1 - Decide to not check unicity inside the goup companies
			$sisters = array();
			$q = "select * from members where cust_code='$cust_code';";
			$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
			if($r && mysql_num_rows($r)>0) {
				$row = mysql_fetch_assoc($r);
				$intranet_code = $row['intranet_code'];
				$parent_intranet_code = $row['parent_intranet_code'];
				
				if($parent_intranet_code != "") {
					$qsis = "select * from members where intranet_code='$parent_intranet_code' OR parent_intranet_code='$parent_intranet_code';";
				}
				elseif($intranet_code != "") {
					$qsis = "select * from members where intranet_code='$intranet_code' OR parent_intranet_code='$intranet_code' OR parent_intranet_code='$parent_intranet_code';";
				}
				
				if(isset($qsis)) {
					$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
					if($r && mysql_num_rows($r)>0) {
						while ($row = mysql_fetch_assoc($r)) {
							$sisters [] = $row['member_id'];
						}
					}
				}
			}
			
			$sisters_mids = "";
			if(count($sisters) > 0) {
				$sisters_mids = implode(",", $sisters);
			}
			
			// Validate Advert Unique Fields
			foreach ($advert_unique as $fld=>$label) {
				if($advert_action_type == "add") {
					if(${$fld} != "") {
						if($sisters_mids != "") {
							$q = "select * from advertisment where $fld='".${$fld}."' and member_id not in ($sisters_mids)";
							if($fld == "domainname") {
								$q = "select * from advertisment where ($fld='".${$fld}."' OR website like '%$domainname%') and member_id not in ($sisters_mids)";
							}
						}
						else {
							$q = "select * from advertisment where $fld='".${$fld}."'";
							if($fld == "domainname") {
								$q = "select * from advertisment where ($fld='".${$fld}."' OR website like '%$domainname%');";
							}
						}
						
						//echo "<br/>" . $q;
						$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
						if($r && mysql_num_rows($r) > 0) {
							$err .= "<br/><strong>$label</strong> must be unique but the entered one was already found in our database.";
						}
					}
				}
				if($advert_action_type == "edit") {
					if(${$fld} != "") {
						if($sisters_mids != "") {
							$q = "select * from advertisment where $fld='".${$fld}."' and advertisment_id<>'$advertisment_id' and member_id not in ($sisters_mids);";
						}
						else {
							$q = "select * from advertisment where $fld='".${$fld}."' and advertisment_id<>'$advertisment_id';";
						}
						$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
						if($r && mysql_num_rows($r) > 0) {
							echo '<br>' . $q;
							$err .= "<br/><strong>$label</strong> must be unique but the entered one already exists in our database.";
						}
					}
				}
			}
			
			// Validate Location Unique Fields
			if($advert_action_type == "add" || $advert_action_type == "edit") {
				foreach ($location_unique as $fld=>$label) {
					if(${$fld} != "") {
						if($sisters_mids != "") {
							$q = "select * from advertisment_locations where $fld='".${$fld}."' and member_id not in ($sisters_mids)";
						}
						else {
							$q = "select * from advertisment_locations where $fld='".${$fld}."' and member_id!='$member_id'";
						}
						
						//echo "<br/>" . $q;
						$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
						if($r && mysql_num_rows($r) > 0) {
							$err .= "<br/><strong>$label</strong> must be unique but the entered one already exists in our database.";
						}
					}
				}
			}
			
		}
		
		
		// Add New Advert To the database
		if($advert_action_type == "add" && $err == "") {
		
					
		
			$adv_flds = array();
			$adv_vals = array();
			$q = "";
			foreach ($advert_fields as $fld) {
				if(isset(${$fld})) {
					$adv_flds [] = "`$fld`";
					
					if($fld == "added_on") {
						$added_on = date("Y-m-d", time());
					}
					
					$adv_vals [] = "'" . mysql_real_escape_string(${$fld}) . "'";
				}
			}
			
			//echo '<pre>', print_r($adv_flds), '</pre>';
			//echo '<pre>', print_r($adv_vals), '</pre>';
			
			if(count($adv_flds) > 0) {
				$adv_flds_str = implode(", ", $adv_flds);
				$adv_vals_str = implode(", ", $adv_vals);
				
				$q .= "insert into advertisment ($adv_flds_str) values ($adv_vals_str);";
				//echo '<div class="note"><strong>INSERT ADVERT QUERY:</strong><br/>', $q, '</div>';
				$r = @mysql_query($q);
				if($r && mysql_affected_rows() == 1) {
					$advertisment_id = mysql_insert_id();
					$adv_code = trim($adv_code);
					$cust_code = trim($cust_code);
					$member_id = intval($member_id);
					
					$loc_flds = array();
					$loc_vals = array();
					
					// Add Additional Fields
					$created = $updated = date("Y-m-d H:i:s", time());
					$created_by = $updated_by = $_SESSION['member_id'];
					$active = 1;
					$main_location = 1;
					$q = "";
					foreach ($advert_location_fields as $fld) {
						if(isset(${$fld})) {
							$loc_flds [] = "`$fld`";
							$loc_vals [] = "'" . mysql_real_escape_string(${$fld}) . "'";
						}
					}
					
					//echo '<pre>', print_r($loc_flds), '</pre>';
					//echo '<pre>', print_r($loc_vals), '</pre>';
					
					$keep_advert = false;
					
					if(count($loc_flds) > 0) {
						$loc_flds_str = implode(", ", $loc_flds);
						$loc_vals_str = implode(", ", $loc_vals);
						
						$q .= "insert into advertisment_locations ($loc_flds_str) values ($loc_vals_str);";
						//echo '<div class="note"><strong>INSERT LOCATION QUERY:</strong><br/>', $q, '</div>';
						$r = @mysql_query($q);
						if($r && mysql_affected_rows() == 1) {
							$msg .= "<br/>The Advert was successfully saved!";
							$keep_advert = true;
							
							// Create also the first main trading name;
							$q = "INSERT INTO advertisment_tradenames (`advertisment_id`, `member_id`, `adv_code`, `cust_code`, `tradename`, `friendly_url`, `main_tradename`, `active`, `created`, `created_by`, `updated`, `updated_by`)
								values ('$advertisment_id', '$member_id', '$adv_code', '$cust_code', '$short_title_en', '$title_tr', '1', '1', '".date("Y-m-d H:i:s", time())."', '".$_SESSION['member_id']."', '".date("Y-m-d H:i:s", time())."', '".$_SESSION['member_id']."');";
							$r = @mysql_query($q);
							if($r && mysql_affected_rows() == 1) {
								$msg .= "<br/>A Display Name was also saved for this advert!";
							}
							else {
								$err .= "<br/>The Display Name was not saved. Please create one manually in the Tradin Names section!";
							}
							
							$_REQUEST['advertisment_id'] = $advertisment_id;
							
							
						}
					}
					if(!$keep_advert) {
						$err .= "<br/>Error inserting advert location in the database:";
						$err .= "<br/>" . "<strong>$q</strong>".mysql_error();
						$q = "delete from advertisment where advertisment_id='$new_advertisment_id';";
						$r = @mysql_query($q) or die("<strong>$q</strong>".mysql_error());
					}
					
				}
				else {
					$err .= "<br/>Error inserting advert in the database:";
					$err .= "<br/>" . "<strong>$q</strong>".mysql_error();
				}
			}
			else {
				$err .= "<br/>Not enough data to save this record!";
			}
		}
		
		
		// Edit Existing Advert
		if($advert_action_type == "edit" && $err == "") {
			
			$adv_flds = array();
			$adv_vals = array();
			$q = "";
			foreach ($advert_fields as $fld) {
				if(isset(${$fld})) {
					$adv_flds [] = "`$fld`='" . mysql_real_escape_string(${$fld}) . "'";
				}
			}
			
			//echo '<pre>', print_r($adv_flds), '</pre>';
			//echo '<pre>', print_r($adv_vals), '</pre>';
			
			if(count($adv_flds) > 0) {
				$adv_flds_str = implode(", ", $adv_flds);
				
				$q .= "UPDATE advertisment SET $adv_flds_str WHERE advertisment_id='$advertisment_id';";
				//echo '<div class="note"><strong>UPDATE ADVERT QUERY:</strong><br/>', $q, '</div>';
				$r = @mysql_query($q);
				if($r && mysql_affected_rows() != -1) {
					$msg .= '<br/>The Free Listing was successfully updated!';
					
					if(isset($_POST['location_id'])) {
						$location_id = $_POST['location_id'];
						$loc_flds = array();
						$loc_vals = array();
						
						// Add Additional Fields
						$updated = date("Y-m-d H:i:s", time());
						$updated_by = $_SESSION['member_id'];
						$q = "";
						foreach ($advert_location_fields as $fld) {
							if(isset(${$fld})) {
								$loc_flds [] = "`$fld`='" . mysql_real_escape_string(${$fld}) . "'" ;
							}
						}
						
						if(count($loc_flds) > 0) {
							$loc_flds_str = implode(", ", $loc_flds);
							
							$q .= "UPDATE advertisment_locations SET $loc_flds_str  WHERE location_id='$location_id' and advertisment_id='$advertisment_id';";
							//echo '<div class="note"><strong>UPDATE LOCATION QUERY:</strong><br/>', $q, '</div>';
							$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
							if($r && mysql_affected_rows() != -1) {
								$_REQUEST['location_id'] = $location_id;
								$msg .= "<br/>The Location was successfully updated!";
								
								if($main_location == 1) {
									$q = "UPDATE advertisment_locations SET main_location='0' where advertisment_id='$advertisment_id' AND location_id!='$location_id';";
									$r = @mysql_query($q);
								}
	
							}
						}
						else {
							$err .= "<br/>Not enough data to save this record!";
						}
					}
					else {
						$loc_flds = array();
						$loc_vals = array();
						
						// Add Additional Fields
						$created = $updated = date("Y-m-d H:i:s", time());
						$created_by = $updated_by = $_SESSION['member_id'];
						$active = 1;
						$main_location = 1;
						$q = "";
						foreach ($advert_location_fields as $fld) {
							if(isset(${$fld})) {
								$loc_flds [] = "`$fld`";
								$loc_vals [] = "'" . mysql_real_escape_string(${$fld}) . "'";
							}
						}
						
						if(count($loc_flds) > 0) {
							$loc_flds_str = implode(", ", $loc_flds);
							$loc_vals_str = implode(", ", $loc_vals);
							
							$q .= "insert into advertisment_locations ($loc_flds_str) values ($loc_vals_str);";
							//echo '<div class="note"><strong>INSERT LOCATION QUERY:</strong><br/>', $q, '</div>';
							$r = @mysql_query($q);
							if($r && mysql_affected_rows() == 1) {
								$msg .= "<br/>A Location was also saved!";								
							}
						}
					}
					
					if($change_owner) {
						
						$_POST['member_id'] = $new_member_id;
						$_POST['cust_code'] = $new_cust_code;
						$member_id = $new_member_id;
						$cust_code = $new_cust_code;
						
						$_POST['new_member_id'] = "";
						
						// In case we have changed the owner, reflect this on locations also
						$q = "update advertisment_locations set adv_code='$adv_code', cust_code='$cust_code', member_id='$member_id' where advertisment_id='$advertisment_id';";
						$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
						if($r && mysql_affected_rows() > 0) {
							$msg .= "<br/>" . mysql_affected_rows() . " locations were also updated!";
						}
						
						// In case we have changed the owner, reflect this on tradenames also
						$q = "update advertisment_tradenames set adv_code='$adv_code', cust_code='$cust_code', member_id='$member_id' where advertisment_id='$advertisment_id';";
						$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
						if($r && mysql_affected_rows() > 0) {
							$msg .= "<br/>" . mysql_affected_rows() . " tradenames were also updated!";
						}
					}
					
					$q = "select * from advertisment_tradenames where advertisment_id='$advertisment_id' and tradename='$short_title_en';";
					$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
					if($r && mysql_num_rows($r) >0) {
						
					}
					else {
						// Create also the first main trading name;
						$q = "INSERT INTO advertisment_tradenames (`advertisment_id`, `member_id`, `adv_code`, `cust_code`, `tradename`, `friendly_url`, `main_tradename`, `active`, `created`, `created_by`, `updated`, `updated_by`)
							values ('$advertisment_id', '$member_id', '$adv_code', '$cust_code', '$short_title_en', '$title_tr', '1', '1', '".date("Y-m-d H:i:s", time())."', '".$_SESSION['member_id']."', '".date("Y-m-d H:i:s", time())."', '".$_SESSION['member_id']."');";
						$r = @mysql_query($q);
						if($r && mysql_affected_rows() == 1) {
							$msg .= "<br/>A Display Name was also saved for this advert!";
						}
						else {
							$err .= "<br/>The Display Name was not saved. Please create one manually in the Tradin Names section!";
						}
					}
					
					// If the Advert is inactive ... check active domain bindings
					
				}
				else {
					$err .= '<br/>The Free Listing was NOT updated!';
					$err .= '<br/><strong>'.$q.'</strong>' . mysql_error();
				}
			}
			else {
				$err .= "<br/>Not enough data to save this record!";
			}
		}
		
		if($err == "" && isset($advertisment_id) && $advertisment_id > 0) {
			if($must_uplod == true) {
				$u = new upload($_FILES['logo_image']);
				if($u->uploaded) {
					
					if($u->file_is_image) {
						$im_x = $u->image_src_x;
						$im_y = $u->image_src_y;
						$im_ext = $u->file_src_name_ext;
						
						if($im_x != 85) {
							$err .= "<br/>The uploaded image Width is ". $im_x. ' causing final logo image to be resized.';
						}
						
						if($im_y != 74) {
							$err .= "<br/>The uploaded image Height is ". $im_y. ' causing final logo image to be resized.';
						}
						
						$u->file_new_name_body   	= date("YmdHis") . '_' . $advertisment_id;
						if($im_x != 85 || $im_y != 74) {
							$u->image_resize         	= true;
							$u->image_x              	= 85;
							$u->image_y        			= 74;
						}
						$u->process(dirname(__FILE__) . '/../../images/advertisments/');
						if ($u->processed) {
							//echo 'image resized';
							
							$final_logo_file_name = $u->file_dst_name;
							$u->clean();
							
							$final_logo = new upload(dirname(__FILE__) . "/../../images/advertisments/" . $final_logo_file_name);
							$final_logo_size = $final_logo->file_src_size;
							
							
							$q = "update advertisment set advertisment='$final_logo_file_name' where advertisment_id='$advertisment_id';";
							//echo '<br/>', $q;
							$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
							if($r && mysql_affected_rows() == 1) {
								$msg .= "<br/>The Logo Image has been successfully uploaded!";
								
								$advert_has_logo = true;
								$advert_logo = $final_logo_file_name;
								
								$q = "insert into advertisment_logos (advertisment_id, adv_code, file_name, size, uploaded, uploaded_by) 
									values ('$advertisment_id', '$adv_code', '$final_logo_file_name', '$final_logo_size', NOW(), '".$_SESSION['member_id']."');";
								$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
								//echo '<br/>', $q;
								// Backup the old_logo
								if($old_logo != "") {
									$logo_backup = new upload(dirname(__FILE__) . "/../../images/advertisments/" . $old_logo);
									$old_logo_size = $logo_backup->file_src_size;
									$old_logo_name = $old_logo;
									
								$q = "select * from advertisment_logos where advertisment_id='$advertisment_id' and file_name='$old_logo_name'";
								//echo '<br/>', $q;
								$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
								if($r && mysql_num_rows($r) > 0) {
									// Ok - Exists
								}
								else {
									$q = "insert into advertisment_logos (advertisment_id, adv_code, file_name, size, uploaded, uploaded_by) 
										values ('$advertisment_id', '$adv_code', '$old_logo_name', '$old_logo_size', NOW(), '".$_SESSION['member_id']."');";
									}
									//echo '<br/>', $q;
									$r = mysql_query($q) or die("<strong>$q</strong>".mysql_error());
								}
							}
							
							
						} 
						else {
							$err .= "<br/>Error processing uploaded file:<br/>" . $u->error;
						}
					}
					else {
						$err .= "<br/>The uploaded file was not a supported image.";
					}
				}
				else {
					$err .= "<br/>The file was not uploaded. Unknown reason!";
				}
			}
		}
		
		
	}
	
	
}

?>