<?php

						/*************************************\
						
						    Handshakes Professional (3.0)
						            by DZOIC LTD
						       Copyright(c) 2005-2006
						        http://www.dzoic.com
						
						\*************************************/

						///////////////////////////////////////
						
						admin_validate_section("setup",3);
						$action = $GLOBALS["Get"]->val("action");
								
							switch($action){								
										
								case '':									
									manage_geo();
									break;
									
								case 'edit_country':
									geo_country();
									break;
									
								case 'delete_country':
									geo_delete_country();
									break;
									
								case 'save_country':
									geo_save_country();
									break;
									
								case 'edit_states':
									geo_states();
									break;
									
								case 'edit_cities':
									geo_cities();
									break;
									
								case 'edit_codes':
									geo_codes();
									break;
									
								case 'edit_state':
									geo_state();
									break;
									
								case 'save_state':
									geo_save_state();
									break;
									
								case 'delete_state':
									geo_delete_state();
									break;
									
								case 'edit_city':
									geo_city();
									break;
									
								case 'save_city':
									geo_save_city();
									break;
									
								case 'add_city':
									geo_add_city();
									break;
									
								case 'delete_city':
									geo_delete_city();
									break;
									
								case 'edit_code':
									geo_code();
									break;
									
								case 'save_code':
									geo_save_code();
									break;
									
								case 'add_code':
									geo_add_code();
									break;
									
								case 'delete_code':
									geo_delete_code();
									break;
									
								case 'install_db':
									geo_install_db();
									break;
									
								case 'do_install_db':
									geo_do_install_db();
									break;
									
							}//switch
							
						///////////////////////////////////////
						
function manage_geo(){
	
	admin_validate();
	
	$data["section"] = "setup";
	$data["subsection"] = 3;
	$data["title_id"] = "13";	
	$data["countries"] = array();
	
	$sql_query = "SELECT * FROM geo_countries ORDER BY name";
	$result = $GLOBALS["DB"]->result($sql_query);
	foreach($result as $res){
		$country["name"] = $res["name"];
		$country["con_id"] = $res["con_id"];
		$sql_query = "SELECT COUNT(*) FROM geo_codes WHERE con_id=".$res["con_id"]." LIMIT 0,1";
		$country["codes_support"] = $GLOBALS["DB"]->single($sql_query);
		$data["countries"][] = $country;
	}//foreach
	
	$data["files"] = array();
	
	$folder = DOC_ROOT."/import/geo";
	$dir = opendir($folder);
	while($file = readdir($dir)){
		if($file!="." && $file!=".."){
			$import_file["file"] = $file;
			$import_file["size"] = filesize($folder."/".$file);			
			if($import_file["size"] < 1024)
				$import_file["size"].= " bytes";
			elseif($import_file["size"] >= 1024 && $import_file["size"] < 1048576)
				$import_file["size"] = round($import_file["size"]/1024,2)." KB";
			elseif($import_file["size"] >= 1048576)
				$import_file["size"] = round($import_file["size"]/1048576,2)." MB";
			$data["files"][] = $import_file;
		}//if
	}//while
	closedir($dir);
	
	$layout[0] = "geo_list";
	
	admin_output($layout,$data);
	
}//manage_geo

function geo_country(){
	
	admin_validate();
	
	$data["section"] = "setup";
	$data["subsection"] = 3;
	$data["title"] = "Handshakes::Admin Console - Geo-Positioning";	
	
	$data["con_id"] = $GLOBALS["Get"]->type_val("con_id","integer");
	$data["link"] = "index.php?section=geo#".$data["con_id"];
	
	$sql_query = "SELECT * FROM geo_countries WHERE con_id=".$data["con_id"];
	$data["country"] = $GLOBALS["DB"]->row($sql_query);
	
	$sql_query = "SELECT COUNT(*) FROM geo_states WHERE con_id=".$data["con_id"];
	$data["states"] = $GLOBALS["DB"]->single($sql_query);
	$sql_query = "SELECT COUNT(*) FROM geo_cities WHERE con_id=".$data["con_id"];
	$data["cities"] = $GLOBALS["DB"]->single($sql_query);
	$sql_query = "SELECT COUNT(*) FROM geo_codes WHERE con_id=".$data["con_id"];
	$data["codes"] = $GLOBALS["DB"]->single($sql_query);
	
	$layout[0] = "geo_country";
	
	admin_output($layout,$data);
	
}//geo_country

function geo_save_country(){
	
	admin_validate();
	
	$name = $GLOBALS["Get"]->val("name");
	$con_id = $GLOBALS["Get"]->type_val("con_id","integer");
	
	$sql_query = "UPDATE geo_countries SET name=':name:' WHERE con_id=".$con_id;
	$GLOBALS["DB"]->values = array("name" => $name);
	$GLOBALS["DB"]->execute($sql_query);
	
	load_page("index.php?section=geo&action=edit_country&con_id=".$con_id);
	
}//geo_save_country

function geo_delete_country(){
	
	admin_validate();
	
	$con_id = $GLOBALS["Get"]->type_val("con_id","integer");
	
	$sql_query = "DELETE FROM geo_countries WHERE con_id=".$con_id;
	$GLOBALS["DB"]->execute($sql_query);
	$sql_query = "DELETE FROM geo_states WHERE con_id=".$con_id;
	$GLOBALS["DB"]->execute($sql_query);
	$sql_query = "DELETE FROM geo_cities WHERE con_id=".$con_id;
	$GLOBALS["DB"]->execute($sql_query);
	$sql_query = "DELETE FROM geo_codes WHERE con_id=".$con_id;
	$GLOBALS["DB"]->execute($sql_query);
	
	load_page("index.php?section=geo");
	
}//geo_delete_country

function geo_state(){
	
	admin_validate();
	
	$data["section"] = "setup";
	$data["subsection"] = 3;
	$data["title"] = "Handshakes::Admin Console - Geo-Positioning";	
	
	$data["sta_id"] = $GLOBALS["Get"]->type_val("sta_id","integer");	
	
	$sql_query = "SELECT * FROM geo_states WHERE sta_id=".$data["sta_id"];
	$data["state"] = $GLOBALS["DB"]->row($sql_query);
	$data["link"] = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	
	$sql_query = "SELECT name FROM geo_countries WHERE con_id=".$data["state"]["con_id"];
	$data["con_id"] = $data["state"]["con_id"];
	$data["country"] = $GLOBALS["DB"]->single($sql_query);
	
	$layout[0] = "geo_state";
	
	admin_output($layout,$data);
	
}//geo_state

function geo_save_state(){
	
	admin_validate();
	
	$name = $GLOBALS["Get"]->val("name");
	$sta_id = $GLOBALS["Get"]->type_val("sta_id","integer");
	$ret_link = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	
	$sql_query = "UPDATE geo_states SET name=':name:' WHERE sta_id=".$sta_id;
	$GLOBALS["DB"]->values = array("name" => $name);
	$GLOBALS["DB"]->execute($sql_query);
	
	load_page($ret_link);
	
}//geo_save_state

function geo_delete_state(){
	
	admin_validate();
	
	$sta_id = $GLOBALS["Get"]->type_val("sta_id","integer");
	$ret_link = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	
	$sql_query = "DELETE FROM geo_states WHERE sta_id=".$sta_id;
	$GLOBALS["DB"]->execute($sql_query);
	$sql_query = "DELETE FROM geo_cities WHERE sta_id=".$sta_id;
	$GLOBALS["DB"]->execute($sql_query);
	$sql_query = "DELETE FROM geo_codes WHERE sta_id=".$sta_id;
	$GLOBALS["DB"]->execute($sql_query);
	
	load_page($ret_link);
	
}//geo_delete_state

function geo_states(){
	
	admin_validate();
	
	$data["section"] = "setup";
	$data["subsection"] = 3;
	$data["title_id"] = "13";	
	$data["values"]["search"] = $GLOBALS["Get"]->val("search");
	
	$data["con_id"] = $GLOBALS["Get"]->type_val("con_id","integer");
	
	$sql_query = "SELECT name FROM geo_countries WHERE con_id=".$data["con_id"];
	$data["country"] = $GLOBALS["DB"]->single($sql_query);
	
	$p = $GLOBALS["Get"]->val("p");
	$start = $p*30;
	$data["link"] = "index.php?section=geo&action=edit_states&con_id=".$data["con_id"]."&search=".urlencode($data["values"]["search"]);
	
	$sql_query_total  = "SELECT COUNT(*) ";
	$sql_query_result = "SELECT * ";
	
	$sql_query = "FROM geo_states WHERE con_id=".$data["con_id"];
	if($data["values"]["search"])
		$sql_query.= " AND name LIKE '".admin_replace_search_string($data["values"]["search"])."%'";
	$sql_query.= " ORDER BY name";	
	$total = $GLOBALS["DB"]->single($sql_query_total.$sql_query);				
	$sql_query.= " LIMIT ".$start.",30";
	$result = $GLOBALS["DB"]->result($sql_query_result.$sql_query);
	
	$data["pages"] = handle_multipages($p,$total,$data["link"],30);
	
	$data["link"].= "&p=".$p;
	
	$data["states"] = array();
	
	foreach($result as $res){
		$state["name"] = $res["name"];
		$state["sta_id"] = $res["sta_id"];
		$data["states"][] = $state;
	}//foreach
	
	$layout[0] = "geo_states";
	
	admin_output($layout,$data);
	
}//geo_states

function geo_cities(){
	
	admin_validate();
	
	$data["section"] = "setup";
	$data["subsection"] = 3;
	$data["title_id"] = "13";	
	$data["con_id"] = $GLOBALS["Get"]->type_val("con_id","integer");
	
	$vals = array("search","sta_id");
	$data["values"] = $GLOBALS["Get"]->arr($vals,1);
	
	$sql_query = "SELECT name FROM geo_countries WHERE con_id=".$data["con_id"];
	$data["country"] = $GLOBALS["DB"]->single($sql_query);
	
	$sql_query = "SELECT * FROM geo_states WHERE con_id=".$data["con_id"]." ORDER BY name";
	$data["states"][0] = "Please, select...";
	$result = $GLOBALS["DB"]->result($sql_query);
	foreach($result as $res){
		$data["states"][$res["sta_id"]] = $res["name"];
	}//foreach
	
	$p = $GLOBALS["Get"]->val("p");
	$start = $p*30;
	
	$sql_query_total  = "SELECT COUNT(*) ";
	$sql_query_result = "SELECT * ";
	
	$sql_query = "FROM geo_cities WHERE con_id=".$data["con_id"];
	if($data["values"]["search"])
		$sql_query.= " AND name LIKE '".admin_replace_search_string($data["values"]["search"])."%'";
	if($data["values"]["sta_id"])
		$sql_query.= " AND sta_id=".$data["values"]["sta_id"];
	$sql_query.= " ORDER BY name";	
	$total = $GLOBALS["DB"]->single($sql_query_total.$sql_query);				
	$sql_query.= " LIMIT ".$start.",30";
	$result = $GLOBALS["DB"]->result($sql_query_result.$sql_query);
	
	$data["link"] = "index.php?section=geo&action=edit_cities&con_id=".$data["con_id"]."&search=".urlencode($data["values"]["search"])."&sta_id=".$data["values"]["sta_id"];
	$data["pages"] = handle_multipages($p,$total,$data["link"],30);
	$data["link"].= "&p=".$p;
	
	$data["cities"] = array();
	
	foreach($result as $res){
		$city["name"] = $res["name"];
		$city["state"] = $data["states"][$res["sta_id"]];
		$city["cty_id"] = $res["cty_id"];
		$city["latitude"] = $res["latitude"];
		$city["longitude"] = $res["longitude"];
		$data["cities"][] = $city;
	}//foreach
	
	$layout[0] = "geo_cities";
	
	admin_output($layout,$data);
	
}//geo_cities

function geo_city(){
	
	admin_validate();
	
	$data["section"] = "setup";
	$data["subsection"] = 3;
	$data["title"] = "Handshakes::Admin Console - Geo-Positioning";	
	
	$data["cty_id"] = $GLOBALS["Get"]->type_val("cty_id","integer");	
	
	$sql_query = "SELECT * FROM geo_cities WHERE cty_id=".$data["cty_id"];
	$data["city"] = $GLOBALS["DB"]->row($sql_query);
	$data["link"] = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	
	$sql_query = "SELECT name FROM geo_countries WHERE con_id=".$data["city"]["con_id"];
	$data["country"] = $GLOBALS["DB"]->single($sql_query);
	$data["con_id"] = $data["city"]["con_id"];
	
	$sql_query = "SELECT * FROM geo_states WHERE con_id=".$data["con_id"]." ORDER BY name";
	$result = $GLOBALS["DB"]->result($sql_query);
	foreach($result as $res){
		$data["states"][$res["sta_id"]] = $res["name"];
	}//foreach
	
	$layout[0] = "geo_city";
	
	admin_output($layout,$data);
	
}//geo_city

function geo_save_city(){
	
	admin_validate();
	
	$cty_id = $GLOBALS["Get"]->type_val("cty_id","integer");
	$ret_link = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	
	$sql_query = "SELECT * FROM geo_cities WHERE cty_id=".$cty_id;
	$city = $GLOBALS["DB"]->row($sql_query);
	
	$vals = array("name","sta_id","state","latitude","longitude");
	$values = $GLOBALS["Get"]->arr($vals,1);
	
	if($values["state"]){
		$sql_query = "INSERT INTO geo_states (con_id,name) VALUES (".$city["con_id"].",':name:')";
		$GLOBALS["DB"]->values = array("name" => $values["state"]);
		$values["sta_id"] = $GLOBALS["DB"]->insert($sql_query);
	}//if
	
	$sql_query = "UPDATE geo_cities SET name=':name:',sta_id=:sta_id:,latitude=':latitude:',longitude=':longitude:' WHERE cty_id=".$cty_id;
	$GLOBALS["DB"]->values = $values;
	$GLOBALS["DB"]->execute($sql_query);
	
	load_page($ret_link);
	
}//geo_save_city

function geo_add_city(){
	
	admin_validate();
	
	$ret_link = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	
	$vals = array("name","sta_id","state","latitude","longitude","con_id");
	$values = $GLOBALS["Get"]->arr($vals,1);
	
	if($values["state"]){
		$sql_query = "INSERT INTO geo_states (con_id,name) VALUES (".$values["con_id"].",':name:')";
		$GLOBALS["DB"]->values = array("name" => $values["state"]);
		$values["sta_id"] = $GLOBALS["DB"]->insert($sql_query);
	}//if
	
	$sql_query = "INSERT INTO geo_cities (name,con_id,sta_id,latitude,longitude) 
				  VALUES (':name:',:con_id:,:sta_id:,':latitude:',':longitude:')";	
	
	$GLOBALS["DB"]->values = $values;
	$GLOBALS["DB"]->execute($sql_query);
	
	load_page($ret_link);
	
}//geo_add_city

function geo_delete_city(){
	
	admin_validate();
	
	$cty_id = $GLOBALS["Get"]->type_val("cty_id","integer");
	$ret_link = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	
	$sql_query = "DELETE FROM geo_cities WHERE cty_id=".$cty_id;
	$GLOBALS["DB"]->execute($sql_query);
	$sql_query = "DELETE FROM geo_codes WHERE cty_id=".$cty_id;
	$GLOBALS["DB"]->execute($sql_query);
	
	load_page($ret_link);
	
}//geo_delete_city

function geo_codes(){
	
	admin_validate();
	
	$data["section"] = "setup";
	$data["subsection"] = 3;
	$data["title_id"] = "13";	
	$data["con_id"] = $GLOBALS["Get"]->type_val("con_id","integer");
	
	$vals = array("search","state","city");
	$data["values"] = $GLOBALS["Get"]->arr($vals,1);
	
	$sql_query = "SELECT name FROM geo_countries WHERE con_id=".$data["con_id"];
	$data["country"] = $GLOBALS["DB"]->single($sql_query);
	
	$p = $GLOBALS["Get"]->val("p");
	$start = $p*30;
	
	$sql_query_total  = "SELECT COUNT(*) ";
	$sql_query_result = "SELECT * ";
	
	$sql_query = "FROM geo_codes WHERE con_id=".$data["con_id"];
	if($data["values"]["search"])
		$sql_query.= " AND code LIKE '".admin_replace_search_string($data["values"]["search"])."%'";
	if($data["values"]["state"])
		$sql_query.= " AND sta_id=".$data["values"]["state"];
	if($data["values"]["city"])
		$sql_query.= " AND cty_id=".$data["values"]["city"];
	$sql_query.= " ORDER BY code";	
	$total = $GLOBALS["DB"]->single($sql_query_total.$sql_query);				
	$sql_query.= " LIMIT ".$start.",30";
	$result = $GLOBALS["DB"]->result($sql_query_result.$sql_query);
	
	$data["link"] = "index.php?section=geo&action=edit_codes&con_id=".$data["con_id"]."&search=".urlencode($data["values"]["search"])."&state=".$data["values"]["state"]."&city=".$data["values"]["city"];
	$data["pages"] = handle_multipages($p,$total,$data["link"],30);
	$data["link"].= "&p=".$p;
	
	$data["codes"] = array();
	
	foreach($result as $res){
		$code["name"] = $res["code"];
		$code["state"] = extract_state($res["con_id"],$res["sta_id"]);
		$code["city"] = extract_city($res["con_id"],$res["sta_id"],$res["cty_id"]);
		$code["latitude"] = $res["latitude"];
		$code["longitude"] = $res["longitude"];
		$code["sta_id"] = $res["sta_id"];
		$code["cty_id"] = $res["cty_id"];
		$code["code"] = $res["code"];
		$data["codes"][] = $code;
	}//foreach
	
	$layout[0] = "geo_codes";
	
	$data["javascript"] = <<<HTMLTEXT
<script language="JavaScript">
<!--
	function HS_CitiesPopulate(FormHandler,AllowEmpty){
		for(var k = FormHandler.city.options.length-1; k>=0; k--){
			FormHandler.city.options[k] = null;
		}//for
		FormHandler.city.options[0] = new Option("...loading...");
		var Country = $data[con_id];
		var State = FormHandler.state.options[FormHandler.state.selectedIndex].value;
		var xmlHttpReq = false;
    	var self = this;
    	// Mozilla/Safari
    	if (window.XMLHttpRequest) {
        	self.xmlHttpReq = new XMLHttpRequest();
    	}//if
    	// IE
    	else if (window.ActiveXObject) {
        	self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    	}//else if
    	self.xmlHttpReq.open('POST', "../index.php", true);
    	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    	self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4 && self.xmlHttpReq.status == 200) {
	        HS_PullData(self.xmlHttpReq.responseXML,FormHandler.city,'city');
    	}//if
        }//function
    	self.xmlHttpReq.send("handler=geo&action=cities&&country="+Country+"&state="+State+"&allow_empty="+AllowEmpty);
	}//HS_CitiesPopulate
	function HS_PullData(XMLData,FieldHandler,ItemName){
		for(var k = FieldHandler.options.length-1; k>=0; k--){
			FieldHandler.options[k] = null;
		}//for
		var Items = XMLData.getElementsByTagName(ItemName);
    	for(var i=0;i<Items.length;i++){
    		var ItemID = Items[i].firstChild.firstChild.nodeValue;
    		var ItemName = Items[i].firstChild.nextSibling.firstChild.nodeValue;
    		FieldHandler.options[i] = new Option(ItemName,ItemID);
    	}//for
	}//HS_PullData
//-->
</script>
HTMLTEXT;
	
	admin_output($layout,$data);
	
}//geo_codes

function geo_code(){
	
	admin_validate();
	
	$data["section"] = "setup";
	$data["subsection"] = 3;
	$data["title"] = "Handshakes::Admin Console - Geo-Positioning";	
	
	$vals = array("con_id","sta_id","cty_id","code");
	$values = $GLOBALS["Get"]->arr($vals,1);
	
	$sql_query = "SELECT * FROM geo_codes WHERE code='".$values["code"]."' AND con_id=".$values["con_id"]."
				  AND sta_id=".$values["sta_id"]." AND cty_id=".$values["cty_id"];
	$data["code"] = $GLOBALS["DB"]->row($sql_query);
	$data["link"] = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	$data["values"] = $values;
	
	$sql_query = "SELECT name FROM geo_countries WHERE con_id=".$data["code"]["con_id"];
	$data["country"] = $GLOBALS["DB"]->single($sql_query);
	$data["con_id"] = $data["code"]["con_id"];
	
	$data["javascript"] = <<<HTMLTEXT
<script language="JavaScript">
<!--
	function HS_CitiesPopulate(FormHandler,AllowEmpty){
		for(var k = FormHandler.city.options.length-1; k>=0; k--){
			FormHandler.city.options[k] = null;
		}//for
		FormHandler.city.options[0] = new Option("...loading...");
		var Country = $data[con_id];
		var State = FormHandler.state.options[FormHandler.state.selectedIndex].value;
		var xmlHttpReq = false;
    	var self = this;
    	// Mozilla/Safari
    	if (window.XMLHttpRequest) {
        	self.xmlHttpReq = new XMLHttpRequest();
    	}//if
    	// IE
    	else if (window.ActiveXObject) {
        	self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    	}//else if
    	self.xmlHttpReq.open('POST', "../index.php", true);
    	self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    	self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4 && self.xmlHttpReq.status == 200) {
	        HS_PullData(self.xmlHttpReq.responseXML,FormHandler.city,'city');
    	}//if
        }//function
    	self.xmlHttpReq.send("handler=geo&action=cities&&country="+Country+"&state="+State+"&allow_empty="+AllowEmpty);
	}//HS_CitiesPopulate
	function HS_PullData(XMLData,FieldHandler,ItemName){
		for(var k = FieldHandler.options.length-1; k>=0; k--){
			FieldHandler.options[k] = null;
		}//for
		var Items = XMLData.getElementsByTagName(ItemName);
    	for(var i=0;i<Items.length;i++){
    		var ItemID = Items[i].firstChild.firstChild.nodeValue;
    		var ItemName = Items[i].firstChild.nextSibling.firstChild.nodeValue;
    		FieldHandler.options[i] = new Option(ItemName,ItemID);
    	}//for
	}//HS_PullData
//-->
</script>
HTMLTEXT;
	
	$layout[0] = "geo_code";
	
	admin_output($layout,$data);
	
}//geo_code

function geo_save_code(){
	
	admin_validate();
	
	$ret_link = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	
	$vals = array(
		"con_id","sta_id","cty_id","code","code2",
		"state","custom_state","city","custom_city",
		"latitude","longitude"
	);
	$values = $GLOBALS["Get"]->arr($vals,1);
	
	if($values["custom_state"]){
		$sql_query = "INSERT INTO geo_states (con_id,name) VALUES (".$values["con_id"].",':name:')";
		$GLOBALS["DB"]->values = array ("name" => $values["custom_state"]);
		$values["state"] = $GLOBALS["DB"]->insert($sql_query);
	}//if
	
	if($values["custom_city"]){
		$sql_query = "INSERT INTO geo_cities (con_id,sta_id,name,latitude,longitude) 
					  VALUES (".$values["con_id"].",".$values["state"].",':name:',':latitude:',':longitude:')";		
		$GLOBALS["DB"]->values = array ("name" => $values["custom_city"],"latitude" => $values["latitude"],"longitude" => $values["longitude"]);
		$values["city"] = $GLOBALS["DB"]->insert($sql_query);
	}//if
	
	$sql_query = "UPDATE geo_codes SET sta_id=:state:,cty_id=:city:,code=':code2:',
				  latitude=':latitude:',longitude=':longitude:'
				  WHERE con_id=:con_id: AND sta_id=:sta_id: AND cty_id=:cty_id:
				  AND code=':code:'";
	$GLOBALS["DB"]->values = $values;
	$GLOBALS["DB"]->execute($sql_query);
	
	load_page($ret_link);
	
}//geo_save_code

function geo_add_code(){
	
	admin_validate();
	
	$ret_link = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	
	$vals = array(
		"con_id","code","state","custom_state","city","custom_city","latitude","longitude"
	);
	$values = $GLOBALS["Get"]->arr($vals,1);
	
	if($values["custom_state"]){
		$sql_query = "INSERT INTO geo_states (con_id,name) VALUES (".$values["con_id"].",':name:')";
		$GLOBALS["DB"]->values = array ("name" => $values["custom_state"]);
		$values["state"] = $GLOBALS["DB"]->insert($sql_query);
	}//if
	
	if($values["custom_city"]){
		$sql_query = "INSERT INTO geo_cities (con_id,sta_id,name,latitude,longitude) 
					  VALUES (".$values["con_id"].",".$values["state"].",':name:',':latitude:',':longitude:')";		
		$GLOBALS["DB"]->values = array ("name" => $values["custom_city"],"latitude" => $values["latitude"],"longitude" => $values["longitude"]);
		$values["city"] = $GLOBALS["DB"]->insert($sql_query);
	}//if
	
	$sql_query = "INSERT INTO geo_codes (con_id,sta_id,cty_id,code,latitude,longitude)
				  VALUES (:con_id:,:state:,:city:,':code:',':latitude:',':longitude:')";
	
	$GLOBALS["DB"]->values = $values;
	$GLOBALS["DB"]->execute($sql_query);
	
	load_page($ret_link);
	
}//geo_add_code

function geo_delete_code(){
	
	admin_validate();
	
	$code = $GLOBALS["Get"]->type_val("code","integer");
	$ret_link = stripslashes(html_entity_decode($GLOBALS["Get"]->val("ret_link")));
	
	$sql_query = "DELETE FROM geo_codes WHERE code=".$code;
	$GLOBALS["DB"]->execute($sql_query);
	$sql_query = "DELETE FROM geo_codes WHERE code=".$code;
	$GLOBALS["DB"]->execute($sql_query);
	
	load_page($ret_link);
	
}//geo_delete_code

function geo_install_db(){
	
	admin_validate();
	
	$data["section"] = "setup";
	$data["subsection"] = 3;
	$data["title_id"] = "13";	
	$vals = array("file","replace");
	$values = $GLOBALS["Get"]->arr($vals,1);
	
	if(empty($values["file"]) || !file_exists(DOC_ROOT."/import/geo/".$values["file"])){
		$GLOBALS["aerr_id"] = 12;
		manage_geo();
		exit;
	}//if
	
	$data["file"] = $values["file"];
	
	$data["link"] = "index.php?section=geo&action=do_install_db";
	
	while(list($key,$val) = each($values)){
		if(is_array($val)){
			while(list($k,$v) = each($val)){
				$data["link"].= "&".$key."[".$k."]=".urlencode($v);
			}//while
		}//if
		else
			$data["link"].= "&".$key."=".urlencode($val);
	}//while
	
	$data["javascript"] = "
<script language=\"JavaScript\">
	function HS_PullReport( status ){
		MessageHandler = document.getElementById('status');
		MessageHandler.innerHTML = status;
	}//HS_PullReport
	function HS_StartInstallation(){
		InstallHandler = document.getElementById('install_processor');
		InstallHandler.src = \"".$data["link"]."\";
	}//HS_StartInstallation
</script>
";

	$data["onload"] = "HS_StartInstallation();HS_PullReport('Installation in process...');";
	
	$layout[0] = "geo_install";
	
	admin_output($layout,$data);
	
}//geo_install_db

function geo_do_install_db(){
	
	set_time_limit(0);
	
	admin_validate();
	
	Header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    Header("Cache-Control: no-cache, must-revalidate"); 
	Header("Pragma: no-cache");
	
	$vals = array("file","replace");
	$values = $GLOBALS["Get"]->arr($vals,1);
	
	if(empty($values["file"]) || !file_exists(DOC_ROOT."/import/geo/".$values["file"])){
		?><script language="JavaScript">
		<!--
			parent.HS_PullReport("Source file was not found.");
		//-->
		</script><?php
		exit;
	}//if
	
	if($values["replace"] == "complete"){
		$sql_query = "TRUNCATE TABLE `geo_countries`;";
		$GLOBALS["DB"]->execute($sql_query);
		$sql_query = "TRUNCATE TABLE `geo_states`;";
		$GLOBALS["DB"]->execute($sql_query);
		$sql_query = "TRUNCATE TABLE `geo_cities`;";
		$GLOBALS["DB"]->execute($sql_query);
		$sql_query = "TRUNCATE TABLE `geo_codes`;";
		$GLOBALS["DB"]->execute($sql_query);
	}//if
	
	$sql_query = "SELECT MAX(con_id) FROM geo_countries";
	$old_max["con_id"] = $GLOBALS["DB"]->single($sql_query);
	if(!$old_max["con_id"])
		$old_max["con_id"] = 0;
	$sql_query = "SELECT MAX(sta_id) FROM geo_states";
	$old_max["sta_id"] = $GLOBALS["DB"]->single($sql_query);
	if(!$old_max["sta_id"])
		$old_max["sta_id"] = 0;
	$sql_query = "SELECT MAX(cty_id) FROM geo_cities";
	$old_max["cty_id"] = $GLOBALS["DB"]->single($sql_query);
	if(!$old_max["cty_id"])
		$old_max["cty_id"] = 0;
	$sql_query = "SELECT MAX(code_id) FROM geo_codes";
	$old_max["code_id"] = $GLOBALS["DB"]->single($sql_query);
	if(!$old_max["code_id"])
		$old_max["code_id"] = 0;
	
	$new_max["con_id"]  = $old_max["con_id"];
	$new_max["sta_id"]  = $old_max["sta_id"];
	$new_max["cty_id"]  = $old_max["cty_id"];
	$new_max["code_id"] = $old_max["code_id"];
	
	$old_countries = array();	
	$new_countries = array();
	$finished_countries = array();
	$delete_countries = array();
	
	$install_query_start = "INSERT INTO geo_install VALUES ";
	$install_query = "";
	
	//clean up install table
	$sql_query = "TRUNCATE TABLE geo_install";
	$GLOBALS["DB"]->execute($sql_query);
	
	$sql_query = "SELECT * FROM geo_countries";
	$result = $GLOBALS["DB"]->result($sql_query);
	foreach($result as $res){
		$old_countries[$res["con_id"]] = $res["name"];
	}//foreach
	
	$file_handler = fopen(DOC_ROOT."/import/geo/".$values["file"],"r");
	$file_size = filesize(DOC_ROOT."/import/geo/".$values["file"]);
	while($line = @fgets($file_handler, 1024)){
		$items = explode("\t",$line);
		$country   = $items[0];
		$state     = $items[1];
		$city      = $items[2];
		$code      = $items[3];
		$latitude  = $items[4];
		$longitude = $items[5];
		
		if(!$con_id && !in_array($country,$finished_countries)){
			if($values["replace"] == "countries" || !in_array($country,$old_countries)){
				$new_max["con_id"]++;
				$con_id = $new_max["con_id"];
				$new_countries[$con_id] = $country;
				if($values["replace"] == "countries"){
					$old_con_id = array_search($country,$old_countries);
					if($old_con_id)
						$delete_countries[] = $old_con_id;
				}//if
			}//if
			else{
				$con_id = array_search($country,$old_countries);
			}//else
			$sql_query = "SELECT * FROM geo_states WHERE con_id=".$con_id;
			$result = $GLOBALS["DB"]->result($sql_query);
			$states = array();
			foreach($result as $res){
				$states[$res["sta_id"]] = $res["name"];
			}//foreach
			$finished_countries[$con_id] = $country;
		}//if
		
		if($con_id && $finished_countries[$con_id] == $country){
			if($values["replace"] == "states" || !in_array($state,$states)){
				$new_max["sta_id"]++;
				$sta_id = $new_max["sta_id"];
				$states[$sta_id] = $state;
				if($values["replace"] == "states"){
					$old_sta_id = array_search($state,$states);
				}//if
				else
					$old_sta_id = $sta_id;
			}//if
			else{
				$sta_id = array_search($state,$states);
				$old_sta_id = $sta_id;
			}//else
			
			if($sta_id < $new_max["sta_id"]){
				$sql_query = "SELECT new_cty_id FROM geo_install WHERE new_sta_id=".$sta_id." AND city_name='".mysql_escape_string($city)."'";
				$cty_id = $GLOBALS["DB"]->single($sql_query);
			}//if
			else
				$cty_id = 0;
			
			if(!$cty_id){
				if($sta_id <= $old_max["sta_id"]){
					$sql_query = "SELECT cty_id FROM geo_cities WHERE sta_id=".$sta_id." AND name='".mysql_escape_string($city)."'";
					$old_cty_id = $GLOBALS["DB"]->single($sql_query);
				}//if
				else
					$old_cty_id = 0;
					
				if($values["replace"] == "cities" || !$old_cty_id){
					$new_max["cty_id"]++;
					$cty_id = $new_max["cty_id"];
					$old_cty_id = $cty_id;
				}//if
				else
					$cty_id = $old_cty_id;
			}//if
			
			if($code){
				$sql_query = "SELECT code_id FROM geo_codes WHERE code='".mysql_escape_string($code)."' AND con_id=".$con_id;
				$old_code_id = $GLOBALS["DB"]->single($sql_query);
				if($values["replace"] == "codes" || !$old_code_id){
					$new_max["code_id"]++;
					$code_id = $new_max["code_id"];
					$old_code_id = $code_id;
				}//if
				else
					$code_id = $old_code_id;
			}//if
			else{
				$code_id = 0;
				$old_code_id = 0;
			}//else
				
			if (
				$old_sta_id  != $sta_id  || $sta_id  > $old_max["sta_id"] ||
				$old_cty_id  != $cty_id  || $cty_id  > $old_max["cty_id"] ||
				$old_code_id != $code_id || $code_id > $old_max["code_id"]
			){
				$do_entry = 1;  	
			}//if
			else
				$do_entry = 0;
			
			if($do_entry){
				$install_query = "(".$old_sta_id.",".$sta_id.",'".mysql_escape_string($state)."',".$old_cty_id.",".$cty_id.",'".mysql_escape_string($city)."',".$old_code_id.",".$code_id.",'".$code."','".$latitude."','".$longitude."')";
				$GLOBALS["DB"]->execute($install_query_start.$install_query);
			}//if
			
		}//if
		
		$current_position = ftell($file_handler);
		if($current_position == $file_size){
			if(!$con_id)
				break;
			else{
				
				$version = $GLOBALS["DB"]->version();
				if($version >= 4.1){
				
					//clean up states
					$sql_query = "DELETE FROM geo_states WHERE sta_id = (SELECT old_sta_id FROM geo_install WHERE old_sta_id!=new_sta_id)";
					$GLOBALS["DB"]->execute($sql_query);
					$sql_query = "DELETE FROM geo_cities WHERE sta_id = (SELECT old_sta_id FROM geo_install WHERE old_sta_id!=new_sta_id)";
					$GLOBALS["DB"]->execute($sql_query);
					$sql_query = "DELETE FROM geo_codes WHERE sta_id = (SELECT old_sta_id FROM geo_install WHERE old_sta_id!=new_sta_id)";
					$GLOBALS["DB"]->execute($sql_query);
				
					//clean up cities
					$sql_query = "DELETE FROM geo_cities WHERE cty_id = (SELECT old_cty_id FROM geo_install WHERE old_cty_id!=new_cty_id)";
					$GLOBALS["DB"]->execute($sql_query);
					$sql_query = "DELETE FROM geo_codes WHERE cty_id = (SELECT old_cty_id FROM geo_install WHERE old_cty_id!=new_cty_id)";
					$GLOBALS["DB"]->execute($sql_query);
				
					//clean up postal codes
					$sql_query = "DELETE FROM geo_codes WHERE code_id = (SELECT old_code_id FROM geo_install WHERE old_code_id!=new_code_id)";
					$GLOBALS["DB"]->execute($sql_query);
				
					//add new states
					$sql_query = "INSERT INTO geo_states (sta_id,con_id,name) (SELECT DISTINCT new_sta_id,".$con_id.",state_name FROM geo_install WHERE new_sta_id > ".$old_max["sta_id"].")";
					$GLOBALS["DB"]->execute($sql_query);
				
					//add new cities
					$sql_query = "INSERT INTO geo_cities (cty_id,sta_id,con_id,name,latitude,longitude) (SELECT DISTINCT new_cty_id,new_sta_id,".$con_id.",city_name,latitude,longitude FROM geo_install WHERE new_cty_id > ".$old_max["cty_id"].")";
					$GLOBALS["DB"]->execute($sql_query);
				
					//postal codes
					$sql_query = "INSERT INTO geo_codes (code_id,code,cty_id,sta_id,con_id,latitude,longitude) (SELECT DISTINCT new_code_id,code,new_cty_id,new_sta_id,".$con_id.",latitude,longitude FROM geo_install WHERE new_code_id > ".$old_max["code_id"].")";
					$GLOBALS["DB"]->execute($sql_query);
				
					//clean up install table
					$sql_query = "TRUNCATE TABLE geo_install";
					$GLOBALS["DB"]->execute($sql_query);
					
				}//if
				else{
					
					//clean up states
					$sql_query = "SELECT old_sta_id FROM geo_install WHERE old_sta_id!=new_sta_id";
					$res = $GLOBALS["DB"]->execute($sql_query);
					$sql_query        = "";
					$sql_query_states = "DELETE FROM geo_states WHERE sta_id IN (";
					$sql_query_cities = "DELETE FROM geo_cities WHERE sta_id IN (";
					$sql_query_codes  = "DELETE FROM geo_codes  WHERE sta_id IN (";
					while($get = mysql_fetch_assoc($res)){
						$sql_query.= $get["old_sta_id"].",";						
					}//while
					if($sql_query){
						$GLOBALS["DB"]->execute($sql_query_states.$sql_query.")");
						$GLOBALS["DB"]->execute($sql_query_cities.$sql_query.")");
						$GLOBALS["DB"]->execute($sql_query_codes.$sql_query.")");
					}//if
					
					//clean up cities
					$sql_query = "SELECT old_cty_id FROM geo_install WHERE old_cty_id!=new_cty_id";
					$res = $GLOBALS["DB"]->execute($sql_query);
					$sql_query        = "";
					$sql_query_cities = "DELETE FROM geo_cities WHERE cty_id IN (";
					$sql_query_codes  = "DELETE FROM geo_codes  WHERE cty_id IN (";
					while($get = mysql_fetch_assoc($res)){
						$sql_query.= $get["old_cty_id"].",";						
					}//while
					if($sql_query){
						$GLOBALS["DB"]->execute($sql_query_cities.$sql_query.")");
						$GLOBALS["DB"]->execute($sql_query_codes.$sql_query.")");
					}//if
					
					//clean up postal codes
					$sql_query = "SELECT old_code_id FROM geo_install WHERE old_code_id!=new_code_id";
					$res = $GLOBALS["DB"]->execute($sql_query);
					$sql_query        = "";
					$sql_query_codes  = "DELETE FROM geo_codes WHERE code_id IN (";
					while($get = mysql_fetch_assoc($res)){
						$sql_query.= $get["old_code_id"].",";						
					}//while
					if($sql_query){
						$GLOBALS["DB"]->execute($sql_query_codes.$sql_query.")");
					}//if
				
					//add new states
					$sql_query = "SELECT DISTINCT new_sta_id,".$con_id.",state_name FROM geo_install WHERE new_sta_id > ".$old_max["sta_id"];
					$res = $GLOBALS["DB"]->execute($sql_query);
					$sql_query_start = "INSERT INTO geo_states (sta_id,con_id,name) VALUES ";
					$sql_query = "";
					while($get = mysql_fetch_assoc($res)){
						$sql_query.= "(".$get["new_sta_id"].",".$con_id.",'".mysql_escape_string($get["state_name"])."'),";
					}//while
					if($sql_query){
						$sql_query = rtrim($sql_query,",");
						$GLOBALS["DB"]->execute($sql_query_start.$sql_query);
					}//if
					
					//add new cities
					$sql_query = "SELECT DISTINCT new_cty_id,new_sta_id,".$con_id.",city_name,latitude,longitude FROM geo_install WHERE new_cty_id > ".$old_max["cty_id"];
					$res = $GLOBALS["DB"]->execute($sql_query);
					$sql_query_start = "INSERT INTO geo_cities (cty_id,sta_id,con_id,name,latitude,longitude) VALUES ";
					$sql_query = "";
					$rows = 0;
					while($get = mysql_fetch_assoc($res)){
						$sql_query.= "(".$get["new_cty_id"].",".$get["new_sta_id"].",".$con_id.",'".mysql_escape_string($get["city_name"])."',".$get["latitude"].",".$get["longitude"]."),";
						if($rows && $rows%1000 == 0){
							$sql_query = rtrim($sql_query,",");
							$GLOBALS["DB"]->execute($sql_query_start.$sql_query);
							$sql_query = "";
						}//if
						$rows++;
					}//while
					if($sql_query){
						$sql_query = rtrim($sql_query,",");
						$GLOBALS["DB"]->execute($sql_query_start.$sql_query);
					}//if
					
					$sql_query = "SELECT DISTINCT new_code_id,code,new_cty_id,new_sta_id,".$con_id.",latitude,longitude FROM geo_install WHERE new_code_id > ".$old_max["code_id"];
					$res = $GLOBALS["DB"]->execute($sql_query);
					$sql_query_start = "INSERT INTO geo_codes (code_id,code,cty_id,sta_id,con_id,latitude,longitude) VALUES ";
					$sql_query = "";
					$rows = 0;
					while($get = mysql_fetch_assoc($res)){
						$sql_query.= "(".$get["new_code_id"].",'".mysql_escape_string($get["code"])."',".$get["new_cty_id"].",".$get["new_sta_id"].",".$con_id.",".$get["latitude"].",".$get["longitude"]."),";
						if($rows && $rows%1000 == 0){
							$sql_query = rtrim($sql_query,",");
							$GLOBALS["DB"]->execute($sql_query_start.$sql_query);
							$sql_query = "";
						}//if
						$rows++;
					}//while
					if($sql_query){
						$sql_query = rtrim($sql_query,",");
						$GLOBALS["DB"]->execute($sql_query_start.$sql_query);
					}//if
				
					//clean up install table
					$sql_query = "TRUNCATE TABLE geo_install";
					$GLOBALS["DB"]->execute($sql_query);
					
				}//else
				
				$con_id = 0;
				$states = array();
				rewind($file_handler);
			}//else
		}//if
		
	}//while
	fclose($file_handler);
	
	if(count($delete_countries)){
		$sql_query = "DELETE FROM geo_countries WHERE con_id IN (".implode(",",$delete_countries).")";
		$GLOBALS["DB"]->execute($sql_query);
		$sql_query = "DELETE FROM geo_states WHERE con_id IN (".implode(",",$delete_countries).")";
		$GLOBALS["DB"]->execute($sql_query);
		$sql_query = "DELETE FROM geo_cities WHERE con_id IN (".implode(",",$delete_countries).")";
		$GLOBALS["DB"]->execute($sql_query);
		$sql_query = "DELETE FROM geo_codes WHERE con_id IN (".implode(",",$delete_countries).")";
		$GLOBALS["DB"]->execute($sql_query);
	}//if
	
	if(count($new_countries)){
		$sql_query = "INSERT INTO geo_countries (con_id,name) VALUES ";
		while(list($key,$val) = each($new_countries)){
			$sql_query.= "(".$key.",'".mysql_escape_string($val)."'),";
		}//while
		$sql_query = rtrim($sql_query,',');
		$GLOBALS["DB"]->execute($sql_query);
	}//if
	
	?><script language="JavaScript">
	<!--
		parent.HS_PullReport("New Geo-Positioning DB has been successfully installed.");
	//-->
	</script><?php
	exit;
	
}//geo_do_install_db

?>