//== Global variables
var DEBUG = false;

//== for Google Map
//var GMAP_KEY = "ABQIAAAAjXpDBgfclOFKFE5nXHgRoBT_yE3How_wEZNLId3euXyDtaKJaRTtaE6PR1a577Y-8s_QebTDb1g6cg";
var GMAP_KEY = "ABQIAAAAkY02EOicrs7_m1uAP-MzchQGKEFCPh4D_p6rdp__jBi2Vk_-5RQQ1F6ksYyJb1QQcXbRYuLuVn4dDQ";
var gMap;
var gBounds;
var mouseLatLng;
var wheelZooming = false;
var markers = new Array();
var locations = new Array();

var selectionParam = "";	//== TODO: URL parameter to decides what locations to show 

//== define the regions for display
var gRegions = [ {id: "regionEurope", region: "NORTH & SOUTH EUROPE", continents: ["WE"], countries: [""], countriesHtml: "",
					countryList: ["AUSTRIA","BELGIUM","DENMARK","FINLAND","FRANCE","GERMANY","ITALY","NETHERLANDS","NORWAY","PORTUGAL","SPAIN","SWEDEN","SWITZERLAND","UNITED KINGDOM"]}, 
                {id: "regionAsia", region: "CENTRAL & EAST EUROPE", continents: ["ASPAC"], countries: [""], countriesHtml: "",
					countryList: ["CROATIA","CZECH REPUBLIC","POLAND","ROMANIA","RUSSIAN FEDERATION","SERBIA","SLOVAKIA","UKRAINE"]}, 
                {id: "regionNA", region: "NORTH & SOUTH AMERICA", continents: ["NAFTA"], countries: [""], countriesHtml: "", 
					countryList: ["ARGENTINA", "BRAZIL","CANADA","CHILE","COLOMBIA","GUATEMALA","MEXICO","PERU","UNITED STATES"]}, 
                {id: "regionSA", region: "MIDDLE EAST <br>& AFRICA", continents: ["SAM"], countries: [""], countriesHtml: "",
                countryList: ["EGYPT", "SOUTH AFRICA", "TURKEY", "UNITED ARAB EMIRATES"]}, 
                {id: "regionOther", region: "ASIA <br>& PACIFIC", continents: ["EEROW"], countries: [""], countriesHtml: "",
                	countryList: ["AUSTRALIA", "INDIA", "JAPAN", "MALAYSIA", "NEW ZEALAND", "PEOPLES REPUBLIC OF CHINA", "REPUBLIC OF KOREA", "SINGAPORE", "THAILAND"]} 
               ];

var countryCodes = [
	{name:"AFGHANISTAN", code2:"AF", code3:"AFG"},
	{name:"ALBANIA", code2:"AL", code3:"ALB"},
	{name:"ALGERIA", code2:"DZ", code3:"DZA"},
	{name:"AMERICAN SAMOA", code2:"AS", code3:"ASM"},
	{name:"ANDORRA", code2:"AD", code3:"AND"},
	{name:"ANGOLA", code2:"AO", code3:"AGO"},
	{name:"ANGUILLA", code2:"AI", code3:"AIA"},
	{name:"ANTARCTICA", code2:"AQ", code3:"ATA"},
	{name:"ANTIGUA AND BARBUDA", code2:"AG", code3:"ATG"},
	{name:"ARGENTINA", code2:"AR", code3:"ARG"},
	{name:"ARMENIA", code2:"AM", code3:"ARM"},
	{name:"ARUBA", code2:"AW", code3:"ABW"},
	{name:"AUSTRALIA", code2:"AU", code3:"AUS"},
	{name:"AUSTRIA", code2:"AT", code3:"AUT"},
	{name:"AZERBAIJAN", code2:"AZ", code3:"AZE"},
	{name:"BAHAMAS", code2:"BS", code3:"BHS"},
	{name:"BAHRAIN", code2:"BH", code3:"BHR"},
	{name:"BANGLADESH", code2:"BD", code3:"BGD"},
	{name:"BARBADOS", code2:"BB", code3:"BRB"},
	{name:"BELARUS", code2:"BY", code3:"BLR"},
	{name:"BELGIUM", code2:"BE", code3:"BEL"},
	{name:"BELIZE", code2:"BZ", code3:"BLZ"},
	{name:"BENIN", code2:"BJ", code3:"BEN"},
	{name:"BERMUDA", code2:"BM", code3:"BMU"},
	{name:"BHUTAN", code2:"BT", code3:"BTN"},
	{name:"BOLIVIA", code2:"BO", code3:"BOL"},
	{name:"BOSNIA AND HERZEGOWINA", code2:"BA", code3:"BIH"},
	{name:"BOTSWANA", code2:"BW", code3:"BWA"},
	{name:"BOUVET ISLAND", code2:"BV", code3:"BVT"},
	{name:"BRAZIL", code2:"BR", code3:"BRA"},
	{name:"BRITISH INDIAN OCEAN TERRITORY", code2:"IO", code3:"IOT"},
	{name:"BRUNEI DARUSSALAM", code2:"BN", code3:"BRN"},
	{name:"BULGARIA", code2:"BG", code3:"BGR"},
	{name:"BURKINA FASO", code2:"BF", code3:"BFA"},
	{name:"BURUNDI", code2:"BI", code3:"BDI"},
	{name:"CAMBODIA", code2:"KH", code3:"KHM"},
	{name:"CAMEROON", code2:"CM", code3:"CMR"},
	{name:"CANADA", code2:"CA", code3:"CAN"},
	{name:"CAPE VERDE", code2:"CV", code3:"CPV"},
	{name:"CAYMAN ISLANDS", code2:"KY", code3:"CYM"},
	{name:"CENTRAL AFRICAN REPUBLIC", code2:"CF", code3:"CAF"},
	{name:"CHAD", code2:"TD", code3:"TCD"},
	{name:"CHILE", code2:"CL", code3:"CHL"},
	{name:"CHINA", code2:"CN", code3:"CHN"},
	{name:"P.R. CHINA", code2:"CN", code3:"CHN"},
	{name:"PEOPLES REPUBLIC OF CHINA", code2:"CN", code3:"CHN"},
	{name:"CHRISTMAS ISLAND", code2:"CX", code3:"CXR"},
	{name:"COCOS (KEELING) ISLANDS", code2:"CC", code3:"CCK"},
	{name:"COLOMBIA", code2:"CO", code3:"COL"},
	{name:"COMOROS", code2:"KM", code3:"COM"},
	{name:"CONGO", code2:"CG", code3:"COG"},
	{name:"CONGO, THE DRC", code2:"CD", code3:"COD"},
	{name:"COOK ISLANDS", code2:"CK", code3:"COK"},
	{name:"COSTA RICA", code2:"CR", code3:"CRI"},
	{name:"COTE D'IVOIRE", code2:"CI", code3:"CIV"},
	{name:"CROATIA", code2:"HR", code3:"HRV"},
	{name:"CUBA", code2:"CU", code3:"CUB"},
	{name:"CYPRUS", code2:"CY", code3:"CYP"},
	{name:"CZECH REPUBLIC", code2:"CZ", code3:"CZE"},
	{name:"DENMARK", code2:"DK", code3:"DNK"},
	{name:"DJIBOUTI", code2:"DJ", code3:"DJI"},
	{name:"DOMINICA", code2:"DM", code3:"DMA"},
	{name:"DOMINICAN REPUBLIC", code2:"DO", code3:"DOM"},
	{name:"EAST TIMOR", code2:"TP", code3:"TMP"},
	{name:"ECUADOR", code2:"EC", code3:"ECU"},
	{name:"EGYPT", code2:"EG", code3:"EGY"},
	{name:"EL SALVADOR", code2:"SV", code3:"SLV"},
	{name:"EQUATORIAL GUINEA", code2:"GQ", code3:"GNQ"},
	{name:"ERITREA", code2:"ER", code3:"ERI"},
	{name:"ESTONIA", code2:"EE", code3:"EST"},
	{name:"ETHIOPIA", code2:"ET", code3:"ETH"},
	{name:"FALKLAND ISLANDS (MALVINAS)", code2:"FK", code3:"FLK"},
	{name:"FAROE ISLANDS", code2:"FO", code3:"FRO"},
	{name:"FIJI", code2:"FJ", code3:"FJI"},
	{name:"FINLAND", code2:"FI", code3:"FIN"},
	{name:"FRANCE", code2:"FR", code3:"FRA"},
	{name:"FRANCE, METROPOLITAN", code2:"FX", code3:"FXX"},
	{name:"FRENCH GUIANA", code2:"GF", code3:"GUF"},
	{name:"FRENCH POLYNESIA", code2:"PF", code3:"PYF"},
	{name:"FRENCH SOUTHERN TERRITORIES", code2:"TF", code3:"ATF"},
	{name:"GABON", code2:"GA", code3:"GAB"},
	{name:"GAMBIA", code2:"GM", code3:"GMB"},
	{name:"GEORGIA", code2:"GE", code3:"GEO"},
	{name:"GERMANY", code2:"DE", code3:"DEU"},
	{name:"GHANA", code2:"GH", code3:"GHA"},
	{name:"GIBRALTAR", code2:"GI", code3:"GIB"},
	{name:"GREECE", code2:"GR", code3:"GRC"},
	{name:"GREENLAND", code2:"GL", code3:"GRL"},
	{name:"GRENADA", code2:"GD", code3:"GRD"},
	{name:"GUADELOUPE", code2:"GP", code3:"GLP"},
	{name:"GUAM", code2:"GU", code3:"GUM"},
	{name:"GUATEMALA", code2:"GT", code3:"GTM"},
	{name:"GUINEA", code2:"GN", code3:"GIN"},
	{name:"GUINEA-BISSAU", code2:"GW", code3:"GNB"},
	{name:"GUYANA", code2:"GY", code3:"GUY"},
	{name:"HAITI", code2:"HT", code3:"HTI"},
	{name:"HEARD AND MC DONALD ISLANDS", code2:"HM", code3:"HMD"},
	{name:"HOLY SEE (VATICAN CITY STATE)", code2:"VA", code3:"VAT"},
	{name:"HONDURAS", code2:"HN", code3:"HND"},
	{name:"HONG KONG", code2:"HK", code3:"HKG"},
	{name:"HUNGARY", code2:"HU", code3:"HUN"},
	{name:"ICELAND", code2:"IS", code3:"ISL"},
	{name:"INDIA", code2:"IN", code3:"IND"},
	{name:"INDONESIA", code2:"ID", code3:"IDN"},
	{name:"IRAN (ISLAMIC REPUBLIC OF)", code2:"IR", code3:"IRN"},
	{name:"IRAQ", code2:"IQ", code3:"IRQ"},
	{name:"IRELAND", code2:"IE", code3:"IRL"},
	{name:"ISRAEL", code2:"IL", code3:"ISR"},
	{name:"ITALY", code2:"IT", code3:"ITA"},
	{name:"JAMAICA", code2:"JM", code3:"JAM"},
	{name:"JAPAN", code2:"JP", code3:"JPN"},
	{name:"JORDAN", code2:"JO", code3:"JOR"},
	{name:"KAZAKHSTAN", code2:"KZ", code3:"KAZ"},
	{name:"KENYA", code2:"KE", code3:"KEN"},
	{name:"KIRIBATI", code2:"KI", code3:"KIR"},
	{name:"KOREA, D.P.R.O.", code2:"KP", code3:"PRK"},
	{name:"KOREA, REPUBLIC OF", code2:"KR", code3:"KOR"},
	{name:"REPUBLIC OF KOREA", code2:"KR", code3:"KOR"},
	{name:"KUWAIT", code2:"KW", code3:"KWT"},
	{name:"KYRGYZSTAN", code2:"KG", code3:"KGZ"},
	{name:"LAOS", code2:"LA", code3:"LAO"},
	{name:"LATVIA", code2:"LV", code3:"LVA"},
	{name:"LEBANON", code2:"LB", code3:"LBN"},
	{name:"LESOTHO", code2:"LS", code3:"LSO"},
	{name:"LIBERIA", code2:"LR", code3:"LBR"},
	{name:"LIBYAN ARAB JAMAHIRIYA", code2:"LY", code3:"LBY"},
	{name:"LIECHTENSTEIN", code2:"LI", code3:"LIE"},
	{name:"LITHUANIA", code2:"LT", code3:"LTU"},
	{name:"LUXEMBOURG", code2:"LU", code3:"LUX"},
	{name:"MACAU", code2:"MO", code3:"MAC"},
	{name:"MACEDONIA", code2:"MK", code3:"MKD"},
	{name:"MADAGASCAR", code2:"MG", code3:"MDG"},
	{name:"MALAWI", code2:"MW", code3:"MWI"},
	{name:"MALAYSIA", code2:"MY", code3:"MYS"},
	{name:"MALDIVES", code2:"MV", code3:"MDV"},
	{name:"MALI", code2:"ML", code3:"MLI"},
	{name:"MALTA", code2:"MT", code3:"MLT"},
	{name:"MARSHALL ISLANDS", code2:"MH", code3:"MHL"},
	{name:"MARTINIQUE", code2:"MQ", code3:"MTQ"},
	{name:"MAURITANIA", code2:"MR", code3:"MRT"},
	{name:"MAURITIUS", code2:"MU", code3:"MUS"},
	{name:"MAYOTTE", code2:"YT", code3:"MYT"},
	{name:"MEXICO", code2:"MX", code3:"MEX"},
	{name:"MICRONESIA, FEDERATED STATES OF", code2:"FM", code3:"FSM"},
	{name:"MOLDOVA, REPUBLIC OF", code2:"MD", code3:"MDA"},
	{name:"MONACO", code2:"MC", code3:"MCO"},
	{name:"MONGOLIA", code2:"MN", code3:"MNG"},
	{name:"MONTSERRAT", code2:"MS", code3:"MSR"},
	{name:"MOROCCO", code2:"MA", code3:"MAR"},
	{name:"MOZAMBIQUE", code2:"MZ", code3:"MOZ"},
	{name:"MYANMAR (Burma)", code2:"MM", code3:"MMR"},
	{name:"NAMIBIA", code2:"NA", code3:"NAM"},
	{name:"NAURU", code2:"NR", code3:"NRU"},
	{name:"NEPAL", code2:"NP", code3:"NPL"},
	{name:"NETHERLANDS", code2:"NL", code3:"NLD"},
	{name:"NETHERLANDS ANTILLES", code2:"AN", code3:"ANT"},
	{name:"NEW CALEDONIA", code2:"NC", code3:"NCL"},
	{name:"NEW ZEALAND", code2:"NZ", code3:"NZL"},
	{name:"NICARAGUA", code2:"NI", code3:"NIC"},
	{name:"NIGER", code2:"NE", code3:"NER"},
	{name:"NIGERIA", code2:"NG", code3:"NGA"},
	{name:"NIUE", code2:"NU", code3:"NIU"},
	{name:"NORFOLK ISLAND", code2:"NF", code3:"NFK"},
	{name:"NORTHERN MARIANA ISLANDS", code2:"MP", code3:"MNP"},
	{name:"NORWAY", code2:"NO", code3:"NOR"},
	{name:"OMAN", code2:"OM", code3:"OMN"},
	{name:"PAKISTAN", code2:"PK", code3:"PAK"},
	{name:"PALAU", code2:"PW", code3:"PLW"},
	{name:"PANAMA", code2:"PA", code3:"PAN"},
	{name:"PAPUA NEW GUINEA", code2:"PG", code3:"PNG"},
	{name:"PARAGUAY", code2:"PY", code3:"PRY"},
	{name:"PERU", code2:"PE", code3:"PER"},
	{name:"PHILIPPINES", code2:"PH", code3:"PHL"},
	{name:"PITCAIRN", code2:"PN", code3:"PCN"},
	{name:"POLAND", code2:"PL", code3:"POL"},
	{name:"PORTUGAL", code2:"PT", code3:"PRT"},
	{name:"PUERTO RICO", code2:"PR", code3:"PRI"},
	{name:"QATAR", code2:"QA", code3:"QAT"},
	{name:"REUNION", code2:"RE", code3:"REU"},
	{name:"ROMANIA", code2:"RO", code3:"ROM"},
	{name:"RUSSIAN FEDERATION", code2:"RU", code3:"RUS"},
	{name:"RWANDA", code2:"RW", code3:"RWA"},
	{name:"SAINT KITTS AND NEVIS", code2:"KN", code3:"KNA"},
	{name:"SAINT LUCIA", code2:"LC", code3:"LCA"},
	{name:"SAINT VINCENT AND THE GRENADINES", code2:"VC", code3:"VCT"},
	{name:"SAMOA", code2:"WS", code3:"WSM"},
	{name:"SAN MARINO", code2:"SM", code3:"SMR"},
	{name:"SAO TOME AND PRINCIPE", code2:"ST", code3:"STP"},
	{name:"SAUDI ARABIA", code2:"SA", code3:"SAU"},
	{name:"SENEGAL", code2:"SN", code3:"SEN"},
	{name:"SEYCHELLES", code2:"SC", code3:"SYC"},
	{name:"SIERRA LEONE", code2:"SL", code3:"SLE"},
	{name:"SINGAPORE", code2:"SG", code3:"SGP"},
	{name:"SLOVAKIA", code2:"SK", code3:"SVK"},
	{name:"Slovak Republic", code2:"SK", code3:"SVK"},
	{name:"SLOVENIA", code2:"SI", code3:"SVN"},
	{name:"SOLOMON ISLANDS", code2:"SB", code3:"SLB"},
	{name:"SOMALIA", code2:"SO", code3:"SOM"},
	{name:"SOUTH AFRICA", code2:"ZA", code3:"ZAF"},
	{name:"SOUTH GEORGIA AND SOUTH S.S.", code2:"GS", code3:"SGS"},
	{name:"SPAIN", code2:"ES", code3:"ESP"},
	{name:"SRI LANKA", code2:"LK", code3:"LKA"},
	{name:"ST. HELENA", code2:"SH", code3:"SHN"},
	{name:"ST. PIERRE AND MIQUELON", code2:"PM", code3:"SPM"},
	{name:"SUDAN", code2:"SD", code3:"SDN"},
	{name:"SURINAME", code2:"SR", code3:"SUR"},
	{name:"SVALBARD AND JAN MAYEN ISLANDS", code2:"SJ", code3:"SJM"},
	{name:"SWAZILAND", code2:"SZ", code3:"SWZ"},
	{name:"SWEDEN", code2:"SE", code3:"SWE"},
	{name:"SWITZERLAND", code2:"CH", code3:"CHE"},
	{name:"SYRIAN ARAB REPUBLIC", code2:"SY", code3:"SYR"},
	{name:"TAIWAN, PROVINCE OF CHINA", code2:"TW", code3:"TWN"},
	{name:"TAJIKISTAN", code2:"TJ", code3:"TJK"},
	{name:"TANZANIA, UNITED REPUBLIC OF", code2:"TZ", code3:"TZA"},
	{name:"THAILAND", code2:"TH", code3:"THA"},
	{name:"TOGO", code2:"TG", code3:"TGO"},
	{name:"TOKELAU", code2:"TK", code3:"TKL"},
	{name:"TONGA", code2:"TO", code3:"TON"},
	{name:"TRINIDAD AND TOBAGO", code2:"TT", code3:"TTO"},
	{name:"TUNISIA", code2:"TN", code3:"TUN"},
	{name:"TURKEY", code2:"TR", code3:"TUR"},
	{name:"TURKMENISTAN", code2:"TM", code3:"TKM"},
	{name:"TURKS AND CAICOS ISLANDS", code2:"TC", code3:"TCA"},
	{name:"TUVALU", code2:"TV", code3:"TUV"},
	{name:"UGANDA", code2:"UG", code3:"UGA"},
	{name:"UKRAINE", code2:"UA", code3:"UKR"},
	{name:"UNITED ARAB EMIRATES", code2:"AE", code3:"ARE"},
	{name:"UNITED KINGDOM", code2:"GB", code3:"GBR"},
	{name:"UNITED STATES", code2:"US", code3:"USA"},
	{name:"USA", code2:"US", code3:"USA"},
	{name:"U.S. MINOR ISLANDS", code2:"UM", code3:"UMI"},
	{name:"URUGUAY", code2:"UY", code3:"URY"},
	{name:"UZBEKISTAN", code2:"UZ", code3:"UZB"},
	{name:"VANUATU", code2:"VU", code3:"VUT"},
	{name:"VENEZUELA", code2:"VE", code3:"VEN"},
	{name:"VIET NAM", code2:"VN", code3:"VNM"},
	{name:"VIRGIN ISLANDS (BRITISH)", code2:"VG", code3:"VGB"},
	{name:"VIRGIN ISLANDS (U.S.)", code2:"VI", code3:"VIR"},
	{name:"WALLIS AND FUTUNA ISLANDS", code2:"WF", code3:"WLF"},
	{name:"WESTERN SAHARA", code2:"EH", code3:"ESH"},
	{name:"YEMEN", code2:"YE", code3:"YEM"},
	{name:"Yugoslavia", code2:"YU", code3:"YUG"},
	{name:"Serbia and Montenegro", code2:"YU", code3:"YUG"},				
	{name:"ZAMBIA", code2:"ZM", code3:"ZMB"},
	{name:"ZIMBABWE ", code2:"ZW", code3:"ZWE "}				
];

var timzonesList = [
//== timezone name, offset, day light saving
["Europe/Andorra", 1, 1],
["Asia/Dubai", 4, 0],
["Asia/Kabul", 4.5, 0],
["America/Antigua", -4, 0],
["America/Anguilla", -4, 0],
["Europe/Tirane", 1, 1],
["Asia/Yerevan", 4, 1],
["America/Curacao", -4, 0],
["Africa/Luanda", 1, 0],
["Antarctica/McMurdo", 12, 1],
["Antarctica/South_Pole", 12, 1],
["Antarctica/Rothera", -3, 1],
["Antarctica/Palmer", -4, 1],
["Antarctica/Mawson", 6, 1],
["Antarctica/Davis", 7, 1],
["Antarctica/Casey", 8, 1],
["Antarctica/DumontDUrville", 10, 1],
["Antarctica/Syowa", 3, 1],
["America/Buenos_Aires", -3, 1],
["America/Cordoba", -3, 1],
["America/Salta", -3, 1],
["America/Jujuy", -3, 1],
["America/Tucuman", -3, 1],
["America/Catamarca", -3, 1],
["America/La_Rioja", -3, 1],
["America/San_Juan", -3, 1],
["America/Mendoza", -3, 1],
["America/San_Luis", -4, 1],
["America/Rio_Gallegos", -3, 1],
["America/Ushuaia", -3, 1],
["Pacific/Pago_Pago", -11, 0],
["Europe/Vienna", 1, 1],
["Australia/Lord_Howe", 10.5, 1],
["Australia/Hobart", 10, 1],
["Australia/Currie", 10, 1],
["Australia/Melbourne", 10, 1],
["Australia/Sydney", 10, 1],
["Australia/Broken_Hill", 9.5, 1],
["Australia/Brisbane", 10, 1],
["Australia/Lindeman", 10, 1],
["Australia/Adelaide", 9.5, 1],
["Australia/Darwin", 9.5, 1],
["Australia/Perth", 8, 1],
["Australia/Eucla", 8.75, 1],
["America/Aruba", -4, 0],
["Europe/Mariehamn", 2, 1],
["Asia/Baku", 4, 1],
["Europe/Sarajevo", 1, 1],
["America/Barbados", -4, 0],
["Asia/Dhaka", 6, 0],
["Europe/Brussels", 1, 1],
["Africa/Ouagadougou", 0, 0],
["Europe/Sofia", 2, 1],
["Asia/Bahrain", 3, 0],
["Africa/Bujumbura", 2, 0],
["Africa/Porto-Novo", 1, 0],
["America/St_Barthelemy", -4, 0],
["Atlantic/Bermuda", -4, 0],
["Asia/Brunei", 8, 0],
["America/La_Paz", -4, 0],
["America/Noronha", -2, 1],
["America/Belem", -3, 1],
["America/Fortaleza", -3, 1],
["America/Recife", -3, 1],
["America/Araguaina", -3, 1],
["America/Maceio", -3, 1],
["America/Bahia", -3, 1],
["America/Sao_Paulo", -3, 1],
["America/Campo_Grande", -4, 1],
["America/Cuiaba", -4, 1],
["America/Santarem", -3, 1],
["America/Porto_Velho", -4, 1],
["America/Boa_Vista", -4, 1],
["America/Manaus", -4, 1],
["America/Eirunepe", -4, 1],
["America/Rio_Branco", -4, 1],
["America/Nassau", -4, 1],
["Asia/Thimphu", 6, 0],
["Africa/Gaborone", 2, 0],
["Europe/Minsk", 2, 1],
["America/Belize", -6, 0],
["America/St_Johns", -3.5, 1],
["America/Halifax", -4, 1],
["America/Glace_Bay", -4, 1],
["America/Moncton", -4, 1],
["America/Goose_Bay", -4, 1],
["America/Blanc-Sablon", -4, 1],
["America/Montreal", -5, 1],
["America/Toronto", -5, 1],
["America/Nipigon", -5, 1],
["America/Thunder_Bay", -5, 1],
["America/Iqaluit", -5, 1],
["America/Pangnirtung", -5, 1],
["America/Resolute", -5, 1],
["America/Atikokan", -5, 1],
["America/Rankin_Inlet", -6, 1],
["America/Winnipeg", -6, 1],
["America/Rainy_River", -6, 1],
["America/Regina", -6, 1],
["America/Swift_Current", -6, 1],
["America/Edmonton", -7, 1],
["America/Cambridge_Bay", -7, 1],
["America/Yellowknife", -7, 1],
["America/Inuvik", -7, 1],
["America/Dawson_Creek", -7, 1],
["America/Vancouver", -8, 1],
["America/Whitehorse", -8, 1],
["America/Dawson", -8, 1],
["Indian/Cocos", 6.5, 0],
["Africa/Kinshasa", 1, 1],
["Africa/Lubumbashi", 2, 1],
["Africa/Bangui", 1, 0],
["Africa/Brazzaville", 1, 0],
["Europe/Zurich", 1, 1],
["Africa/Abidjan", 0, 0],
["Pacific/Rarotonga", -10, 0],
["America/Santiago", -4, 1],
["Pacific/Easter", -6, 1],
["Africa/Douala", 1, 0],
["Asia/Shanghai", 8, 1],
["Asia/Harbin", 8, 1],
["Asia/Chongqing", 8, 1],
["Asia/Urumqi", 8, 1],
["Asia/Kashgar", 8, 1],
["America/Bogota", -5, 0],
["America/Costa_Rica", -6, 0],
["America/Havana", -5, 1],
["Atlantic/Cape_Verde", -1, 0],
["Indian/Christmas", 7, 0],
["Asia/Nicosia", 2, 1],
["Europe/Prague", 1, 1],
["Europe/Berlin", 1, 1],
["Africa/Djibouti", 3, 0],
["Europe/Copenhagen", 1, 1],
["America/Dominica", -4, 0],
["America/Santo_Domingo", -4, 0],
["Africa/Algiers", 1, 0],
["America/Guayaquil", -5, 1],
["Pacific/Galapagos", -6, 1],
["Europe/Tallinn", 2, 1],
["Africa/Cairo", 2, 0],
["Africa/El_Aaiun", 0, 0],
["Africa/Asmara", 3, 0],
["Europe/Madrid", 1, 1],
["Africa/Ceuta", 1, 1],
["Atlantic/Canary", 0, 1],
["Africa/Addis_Ababa", 3, 0],
["Europe/Helsinki", 2, 1],
["Pacific/Fiji", 12, 0],
["Atlantic/Stanley", -4, 1],
["Pacific/Truk", 10, 1],
["Pacific/Ponape", 11, 1],
["Pacific/Kosrae", 11, 1],
["Atlantic/Faroe", 0, 1],
["Europe/Paris", 1, 1],
["Africa/Libreville", 1, 0],
["Europe/London", 0, 1],
["America/Grenada", -4, 0],
["Asia/Tbilisi", 4, 0],
["America/Cayenne", -3, 0],
["Europe/Guernsey", 0, 1],
["Africa/Accra", 0, 0],
["Europe/Gibraltar", 1, 1],
["America/Godthab", -3, 1],
["America/Danmarkshavn", 0, 1],
["America/Scoresbysund", -1, 1],
["America/Thule", -4, 1],
["Africa/Banjul", 0, 0],
["Africa/Conakry", 0, 0],
["America/Guadeloupe", -4, 0],
["Africa/Malabo", 1, 0],
["Europe/Athens", 2, 1],
["Atlantic/South_Georgia", -2, 0],
["America/Guatemala", -6, 0],
["Pacific/Guam", 10, 0],
["Africa/Bissau", 0, 0],
["America/Guyana", -4, 0],
["Asia/Hong_Kong", 8, 1],
["America/Tegucigalpa", -6, 0],
["Europe/Zagreb", 1, 1],
["America/Port-au-Prince", -5, 0],
["Europe/Budapest", 1, 1],
["Asia/Jakarta", 7, 1],
["Asia/Pontianak", 7, 1],
["Asia/Makassar", 8, 1],
["Asia/Jayapura", 9, 1],
["Europe/Dublin", 0, 1],
["Asia/Jerusalem", 2, 1],
["Europe/Isle_of_Man", 0, 1],
["Asia/Kolkata", 5.5, 1],
["Indian/Chagos", 6, 0],
["Asia/Baghdad", 3, 0],
["Asia/Tehran", 3.5, 1],
["Atlantic/Reykjavik", 0, 0],
["Europe/Rome", 1, 1],
["Europe/Jersey", 0, 1],
["America/Jamaica", -5, 0],
["Asia/Amman", 2, 1],
["Asia/Tokyo", 9, 0],
["Africa/Nairobi", 3, 0],
["Asia/Bishkek", 6, 0],
["Asia/Phnom_Penh", 7, 0],
["Pacific/Tarawa", 12, 1],
["Pacific/Enderbury", 13, 1],
["Pacific/Kiritimati", 14, 1],
["Indian/Comoro", 3, 0],
["America/St_Kitts", -4, 0],
["Asia/Pyongyang", 9, 0],
["Asia/Seoul", 9, 0],
["Asia/Kuwait", 3, 0],
["America/Cayman", -5, 0],
["Asia/Almaty", 6, 1],
["Asia/Qyzylorda", 6, 1],
["Asia/Aqtobe", 5, 1],
["Asia/Aqtau", 5, 1],
["Asia/Oral", 5, 1],
["Asia/Vientiane", 7, 0],
["Asia/Beirut", 2, 1],
["America/St_Lucia", -4, 0],
["Europe/Vaduz", 1, 1],
["Asia/Colombo", 5.5, 0],
["Africa/Monrovia", 0, 0],
["Africa/Maseru", 2, 0],
["Europe/Vilnius", 2, 1],
["Europe/Luxembourg", 1, 1],
["Europe/Riga", 2, 1],
["Africa/Tripoli", 2, 0],
["Africa/Casablanca", 0, 0],
["Europe/Monaco", 1, 1],
["Europe/Chisinau", 2, 1],
["Europe/Podgorica", 1, 1],
["America/Marigot", -4, 0],
["Indian/Antananarivo", 3, 0],
["Pacific/Majuro", 12, 1],
["Pacific/Kwajalein", 12, 1],
["Europe/Skopje", 1, 1],
["Africa/Bamako", 0, 0],
["Asia/Rangoon", 6.5, 0],
["Asia/Ulaanbaatar", 8, 1],
["Asia/Hovd", 7, 1],
["Asia/Choibalsan", 8, 1],
["Asia/Macau", 8, 0],
["Pacific/Saipan", 10, 0],
["America/Martinique", -4, 0],
["Africa/Nouakchott", 0, 0],
["America/Montserrat", -4, 0],
["Europe/Malta", 1, 1],
["Indian/Mauritius", 4, 0],
["Indian/Maldives", 5, 0],
["Africa/Blantyre", 2, 0],
["America/Mexico_City", -6, 1],
["America/Cancun", -6, 1],
["America/Merida", -6, 1],
["America/Monterrey", -6, 1],
["America/Mazatlan", -7, 1],
["America/Chihuahua", -7, 1],
["America/Hermosillo", -7, 1],
["America/Tijuana", -8, 1],
["Asia/Kuala_Lumpur", 8, 1],
["Asia/Kuching", 8, 1],
["Africa/Maputo", 2, 0],
["Africa/Windhoek", 1, 1],
["Pacific/Noumea", 11, 0],
["Africa/Niamey", 1, 0],
["Pacific/Norfolk", 11.5, 0],
["Africa/Lagos", 1, 0],
["America/Managua", -6, 0],
["Europe/Amsterdam", 1, 0],
["Europe/Oslo", 1, 1],
["Asia/Katmandu", 5.75, 0],
["Pacific/Nauru", 12, 0],
["Pacific/Niue", -11, 0],
["Pacific/Auckland", 12, 1],
["Pacific/Chatham", 12.75, 1],
["Asia/Muscat", 4, 0],
["America/Panama", -5, 0],
["America/Lima", -5, 0],
["Pacific/Tahiti", -10, 1],
["Pacific/Marquesas", 9.5, 1],
["Pacific/Gambier", -9, 1],
["Pacific/Port_Moresby", 10, 0],
["Asia/Manila", 8, 0],
["Asia/Karachi", 6, 0],
["Europe/Warsaw", 1, 1],
["America/Miquelon", -3, 1],
["Pacific/Pitcairn", -8, 0],
["America/Puerto_Rico", -4, 0],
["Asia/Gaza", 2, 1],
["Europe/Lisbon", 0, 1],
["Atlantic/Madeira", 0, 1],
["Atlantic/Azores", -1, 1],
["Pacific/Palau", 9, 0],
["America/Asuncion", -4, 1],
["Asia/Qatar", 3, 0],
["Indian/Reunion", 4, 0],
["Europe/Bucharest", 2, 1],
["Europe/Belgrade", 1, 1],
["Europe/Kaliningrad", 2, 1],
["Europe/Moscow", 3, 1],
["Europe/Volgograd", 3, 1],
["Europe/Samara", 4, 1],
["Asia/Yekaterinburg", 5, 1],
["Asia/Omsk", 6, 1],
["Asia/Novosibirsk", 6, 1],
["Asia/Krasnoyarsk", 7, 1],
["Asia/Irkutsk", 8, 1],
["Asia/Yakutsk", 9, 1],
["Asia/Vladivostok", 10, 1],
["Asia/Sakhalin", 10, 1],
["Asia/Magadan", 11, 1],
["Asia/Kamchatka", 12, 1],
["Asia/Anadyr", 12, 1],
["Africa/Kigali", 2, 0],
["Asia/Riyadh", 3, 0],
["Pacific/Guadalcanal", 11, 0],
["Indian/Mahe", 4, 0],
["Africa/Khartoum", 3, 0],
["Europe/Stockholm", 1, 1],
["Asia/Singapore", 8, 0],
["Atlantic/St_Helena", 0, 0],
["Europe/Ljubljana", 1, 1],
["Arctic/Longyearbyen", 1, 1],
["Europe/Bratislava", 1, 1],
["Africa/Freetown", 0, 0],
["Europe/San_Marino", 1, 1],
["Africa/Dakar", 0, 0],
["Africa/Mogadishu", 3, 0],
["America/Paramaribo", -3, 0],
["Africa/Sao_Tome", 0, 0],
["America/El_Salvador", -6, 0],
["Asia/Damascus", 2, 1],
["Africa/Mbabane", 2, 0],
["America/Grand_Turk", -5, 1],
["Africa/Ndjamena", 1, 0],
["Indian/Kerguelen", 5, 0],
["Africa/Lome", 0, 0],
["Asia/Bangkok", 7, 0],
["Asia/Dushanbe", 5, 0],
["Pacific/Fakaofo", -10, 0],
["Asia/Dili", 9, 0],
["Asia/Ashgabat", 5, 0],
["Africa/Tunis", 1, 1],
["Pacific/Tongatapu", 13, 0],
["Europe/Istanbul", 2, 1],
["America/Port_of_Spain", -4, 0],
["Pacific/Funafuti", 12, 0],
["Asia/Taipei", 8, 0],
["Africa/Dar_es_Salaam", 3, 0],
["Europe/Kiev", 2, 1],
["Europe/Uzhgorod", 2, 1],
["Europe/Zaporozhye", 2, 1],
["Europe/Simferopol", 2, 1],
["Africa/Kampala", 3, 0],
["Pacific/Johnston", -10, 1],
["Pacific/Midway", -11, 1],
["Pacific/Wake", 12, 1],
["America/New_York", -5, 1],
["America/Detroit", -5, 1],
["America/Kentucky/Louisville", -5, 1],
["America/Kentucky/Monticello", -5, 1],
["America/Indiana/Indianapolis", -5, 1],
["America/Indiana/Vincennes", -5, 1],
["America/Indiana/Winamac", -5, 1],
["America/Indiana/Marengo", -5, 1],
["America/Indiana/Petersburg", -5, 1],
["America/Indiana/Vevay", -5, 1],
["America/Chicago", -6, 1],
["America/Indiana/Tell_City", -6, 1],
["America/Indiana/Knox", -6, 1],
["America/Menominee", -6, 1],
["America/North_Dakota/Center", -6, 1],
["America/North_Dakota/New_Salem", -6, 1],
["America/Denver", -7, 1],
["America/Boise", -7, 1],
["America/Shiprock", -7, 1],
["America/Phoenix", -7, 1],
["America/Los_Angeles", -8, 1],
["America/Anchorage", -9, 1],
["America/Juneau", -9, 1],
["America/Yakutat", -9, 1],
["America/Nome", -9, 1],
["America/Adak", -10, 1],
["Pacific/Honolulu", -10, 1],
["America/Montevideo", -3, 1],
["Asia/Samarkand", 5, 1],
["Asia/Tashkent", 5, 1],
["Europe/Vatican", 1, 1],
["America/St_Vincent", -4, 0],
["America/Caracas", -4.5, 0],
["America/Tortola", -4, 0],
["America/St_Thomas", -4, 0],
["Asia/Ho_Chi_Minh", 7, 0],
["Pacific/Efate", 11, 0],
["Pacific/Wallis", 12, 0],
["Pacific/Apia", -11, 0],
["Asia/Aden", 3, 0],
["Indian/Mayotte", 3, 0],
["Africa/Johannesburg", 2, 0],
["Africa/Lusaka", 2, 0],
["Africa/Harare", 2, 0],
["PST", -8, 1],
["CST", -6, 1],
["EST", -5, 1],
["Europe/Sweden", 1, 1],
["Asia/Calcutta", 5.5, 1]
];


var geoRespoonses = new Array();
// Create our "tiny" marker icon
var gSmallIcon = null;
var gMarkerBaseIcon = null; 

//== for the left hand detailsPane, locations etc.
var activeLocation = "No location";
var gAutoCenterMarker = true;
var gLastHighlightObj = null;

//== used to store the beginning map center and zoom
var gInitialCenter;  //== gLatLng object
var gIntialZoom = 2;

var reasons=[];   //== Gmap Geocode reason codes, 

//== time variable used to track performance
var gStartTime = new Date();     //== initialize to now when the script is first loaded

//== we need to load the Google map, and the locations JSON data
var gDataToLoad = 2;	//== use to control the Loading status message

//== Stupid IE doesn't support Array.indexOf()!!! let's add it, sigh...
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

function loadMap() {
	
	if(location.href.indexOf("debug")>-1) DEBUG=true;  //== turn on debug if there's a &debug=1 in the parameter
	
	debug("Page loaded, loadMap called");

	if(DEBUG) {
	    var elm = document.getElementById("debugLocationDiv");
          if(elm && elm.style.display!="block") elm.style.display = "block";
	}
	
	if(google) {
		debug("loading google map...");
		
		var gBarOptions = {showOnLoad:true};
		var mapOptions = {googleBarOptions:gBarOptions, backgroundColor:"#99B3CC"};
		
		google.load("maps", "2", {"callback": mapsLoaded, "other_params":mapOptions});
//		google.load("search", "1", {"callback": searchLoaded});
	} else {
		alert("Google API load error!");
	}
	
	//=== Jquery to load locations data
	$.getJSON("loc", null, handleLocationsData);

}

function mapsLoaded() {

	debug("map loaded");
	
	var mapElm = document.getElementById("map");
	if(mapElm) {
		
		gSmallIcon = new google.maps.Icon();
        gSmallIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
        gSmallIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
        gSmallIcon.iconSize = new google.maps.Size(12, 20);
        gSmallIcon.shadowSize = new google.maps.Size(22, 20);
        gSmallIcon.iconAnchor = new google.maps.Point(6, 20);
        gSmallIcon.infoWindowAnchor = new google.maps.Point(5, 1);
		
		gMap = new google.maps.Map2(mapElm);
		gMap.addControl(new google.maps.MapTypeControl());
//		gMap.addControl(new google.maps.HierarchicalMapTypeControl());
		var bottomLeft = new google.maps.ControlPosition(G_ANCHOR_BOTTOM_RIGHT, new google.maps.Size(10, 10));
		gMap.addControl(new google.maps.ScaleControl(), bottomLeft);
		gMap.addControl(new google.maps.LargeMapControl());
		
//		gMap.addControl(new google.maps.OverviewMapControl());
				
		gMap.enableGoogleBar();	//== the Google local search box that show up at the bottom left corner
		
		gMap.enableScrollWheelZoom();
		gMap.enableContinuousZoom();

		gIntialCenter = new google.maps.LatLng(29.840644,5.976563);
		gMap.setCenter(gIntialCenter , gIntialZoom);
		
//		gIntialCenter = gMap.getCenter();
//		gIntialZoom = gMap.getZoom();
		//map.setCenter(new google.maps.LatLng(55.68552,12.609901), 3); //Copenhagen

		gBounds = new google.maps.LatLngBounds();

		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
		var baseIcon = new google.maps.Icon();
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new google.maps.Size(18, 34);
		baseIcon.shadowSize = new google.maps.Size(37, 34);
		baseIcon.iconAnchor = new google.maps.Point(9, 34);

		baseIcon.infoWindowAnchor = new google.maps.Point(9, 2);
		baseIcon.infoShadowAnchor = new google.maps.Point(18, 25);
		
		gMarkerBaseIcon = baseIcon;
		
//		var marker = new google.maps.Marker(gIntialCenter);		
//		gMap.addOverlay(marker);

//		searchLoaded();
		
	} else {
		alert("Map area not found!");
	}
	debug("map started");

	checkDataReady();
}

function handleLocationsData(data, textStatus) {
	
	debug("got json data");
	
	locations = data.locations;
//	alert("locations=" + locations.length + ", status=" + textStatus);
		
	for(var i=0;i<locations.length; i++) {
		//== take care of inconsistent spelling of the data source:(
		locations[i].Lat = locations[i].lat;
		locations[i].Lng = locations[i].lng;
		locations[i].ID = i;		//== overwrite the ID field, which was incorrect
		var txt = locations[i].OfficeCountry + ", " + locations[i].OfficeCity;
		$("#selectLocation").addOption(locations[i].ID, txt);
	}
	
	$("#selectLocation").sortOptions();
	
	$("#selectLocation").addOption("", " select a location to open");
	
	$("#selectLocation").selectOptions("");
	
	//== sort the locations by Country, then City (just simple bubble sort)
	for(var i=0;i<locations.length; i++) {
		for(var j=i+1;j<locations.length;j++) {
			if(locations[i].OfficeCountry > locations[j].OfficeCountry) {
				var tmp = locations[i];
				locations[i] = locations[j];
				locations[j] = tmp;
			} else if(locations[i].OfficeCountry == locations[j].OfficeCountry) {
				if(locations[i].OfficeCity > locations[j].OfficeCity) {
					var tmp = locations[i];
					locations[i] = locations[j];
					locations[j] = tmp;
				}
			}
		}
	}
	
	outputRegions();
	
	debug("location data loaded");

	checkDataReady();
}

function checkDataReady() {
	gDataToLoad--;

	debug("data to load=" + gDataToLoad);
	
	if(gDataToLoad<=0) {
		showLocationsOnMap();
		hideMessage();
	}
}

function outputRegions() {

	//== setup the countries for each region
	for(var i=0;i<locations.length; i++) {
		
			for(var r=0; r<gRegions.length;r++) {
				if(gRegions[r].countryList.indexOf(locations[i].OfficeCountry)>-1) {	//== is this country for this region?
					if(gRegions[r].countries.indexOf(locations[i].OfficeCountry)==-1) {	//== only if the country is NOT already on the list
						gRegions[r].countries.push(locations[i].OfficeCountry);	//== add to the list
						
						var countryHtml = '<div class="countryList" onclick="openCountry(\'' + locations[i].OfficeCountry + '\', true, true)" ><a href="Javascript:openCountry(\'' + locations[i].OfficeCountry + '\',true, true)" class="countryLink">';
						countryHtml += getCountryIcon(locations[i].OfficeCountry) + ' ' + locations[i].OfficeCountry + '</a></div>';
	
						gRegions[r].countriesHtml += countryHtml;
					}
				}
				
			}
	}
	
	var html = '<div id="regionHeader"><table style="width:100%" cellspacing="0"><tr onclick="handleRegionClick()">';
	var width = 100/gRegions.length;
	for(i=0; i<gRegions.length; i++) {
		var id = "region" + gRegions[i].region;
		html += '<th width="' + width + '%" id="' + id + '" class="regionName">' + gRegions[i].region + '</th>';
	}
	html += '</tr></table></div>';

	html += '<div id="regionCountries"><table style="width:100%" cellspacing="0"><tr>';
	//== output the countries
	for(i=0; i<gRegions.length; i++) {
		html += '<td id="' + gRegions[i].id + '" valign="top" width="' + width + '%">' + gRegions[i].countriesHtml + '</td>';
	}
	html += '</tr>';	
	html += '</table></div>';
	
	$("#regionDiv").html(html);
}

function handleRegionClick() {
	resetMap();
	//$(".regionNameActive").removeClass("regionNameActive");
	//toggleCountryList();
}

function toggleCountryList() {
	$("#regionCountries").toggle("slow");
	$("#sitesDiv").toggle("slow");
}

function showCountryList(flag) {
	if(flag)
		$("#regionCountries").show("slow");
	else
		$("#regionCountries").hide("slow");
}

function showLocationDetail(locationIndex, flag) {
	
	var location = locations[locationIndex];
	
	var siteid = "site_" + locationIndex;
	highliteLocation(siteid);
	
	var locationDetailId = "siteDetails_" + locationIndex;
//	var flickrDivId = "flickr_" + location.ScCode;
	
	//== site highliting not working, remove this feature
//	$(".siteActive").removeClass("siteActive");	//== first, unhighlight any active city
//	$("#" + locationDetailId).addClass("siteActive");  //== then highlight the active city
	
	var html = '';
//	html += '<div>';
//		html += '<table width="100%"><tr>';
//		
//		html += '<td width="36%">';
//		html += '<b>Divisions/Functions</b><br/>' + getDivisionFunctionsTable(location);
//		
//		html += '</td><td width="32%">';
//		html += '<b>Contacts</b><br/>';
//		
//		html += (location.Contacts ? location.Contacts : 'n/a'); 
//		
//		html += '</td><td width="32%">';
//		html += '<b>Other Information</b><br/>';
//		html += '<img src="images/wiki.gif" align="absMiddle" style="margin:3px;"> <a href="Javascript:popupWiki(' + locationIndex + ')">About this Location (Wikipedia)</a><br/>';
//		html += '<img src="images/flickr.gif" align="absMiddle" style="margin:3px;"> <a href="Javascript:popupFlickr(' + locationIndex + ')">View Pictures (Flickr)</a>';
//		html += '</td>';
//		
//		html += '</tr></table>';
		
//	html += '</div>';

		
//== corp com. decided to disable the site detail for now
//	$("#" + locationDetailId).html(html);
//	$("#" + locationDetailId).toggle("slow");
		
//	if(location.marker) {
//		gMap.setCenter(location.marker.getLatLng());
//		gMap.setZoom(13);
//	}
	
	if(flag) showMarkerInfoWindow(locationIndex);
}

function popupWiki(locationIndex) {
	
	var location = locations[locationIndex];
	
	var url = 'http://en.wikipedia.org/wiki/' + location.OfficeCity; // + '&TB_iframe=true&height=300&width=500';
	
	$("#wikiPopupTitle").html('Wikipedia: ' + location.OfficeCity + ', ' + location.OfficeCountry);
	
	$("#wikiIframe").attr("src", url);

	$("#wikiPopup").jqm({modal:false}); 
	$("#wikiPopup").jqmShow();
}

function popupFlickr(locationIndex) {
	
	var location = locations[locationIndex];
	
	var flickrSettingDanisco = {
			api_key: "c67bcf296e31e22d189f548267c9c358",
//			text: location.OfficeCity,
			user_id: '38631400@N05', //'daniscoflickr',
			type: 'search',
			tags: location.OfficeCity + ', ' + location.OfficeCountry,
			tag_mode: 'all',
			sort: 'date-posted-desc',
			per_page: 50,
			thumb_size: 't',
			callback: flickrDaniscoCallback
		};
		
//	$("#flickrContent").html("");	//== first clear any old pictures
	$("#flickrDanisco").html('');
	$("#flickrInternet").html('');	
	
	$("#flickrDanisco").flickr(flickrSettingDanisco);
	
	$("#flickrPopup").show();

	var flickrSettingInternet = {
			api_key: "c67bcf296e31e22d189f548267c9c358",
			text: location.OfficeCity,
			type: 'search',
			tags: location.OfficeCity + ', ' + location.OfficeCountry,
			tag_mode: 'all',
			sort: 'relevance', //'date-posted-desc','interestingness-desc', //
			per_page: 30,
			thumb_size: 't',
			callback: flickrInternetCallback
		};
	
	$("#flickrInternet").flickr(flickrSettingInternet);
	
	var title = location.OfficeCity + ', ' + location.OfficeCountry + " pictures";
	
	$("#flickrPopupTitle").html(title);
	
//	$("#flickrPopup").jqm({modal:false}); 
//	$("#flickrPopup").jqmShow();
}

function closeFlickr() {
	$("#flickrPopup").hide();
}

function flickrDaniscoCallback(el){
	
	if($("#flickrDanisco a").size()==0) $("#flickrDanisco").html('No pictures available.');
		
	$("#flickrDanisco a").lightBox();
}

function flickrInternetCallback(el){

	if($("#flickrInternet a").size()==0) $("#flickrInternet").html('No pictures available.');
	
	$("#flickrInternet a").lightBox();
//	$("#flickrContent a:first").click();
}

function getCountryIcon(country) {
	
	var img = "";
	
	for(var i=0;i<countryCodes.length; i++) {
		if(countryCodes[i].name.toLowerCase() == country.toLowerCase()) {
			img = '<img src="images/' + countryCodes[i].code2.toLowerCase() + '.gif" border="0" align="absMiddle">';
		}
	}
	
	return img;

}

function getRegionId(region) {
	for(var i=0; i<gRegions.length; i++) {
		if((gRegions[i].continents).indexOf(region)>-1)
			return gRegions[i].id;
	}
	
	return "";
}

function openCountry(country, zoomFlag, showInfoWindowFlag) {
	
	var html = '';
	
	var hasCountryBar = false;
	
	if(!showInfoWindowFlag) closeInfoWindow();
	
	highliteRegion(country);
	
	//== output cities for selected country
	for(var i=0;i<locations.length; i++) {
		if(locations[i].OfficeCountry == country) {
			
			if(!hasCountryBar) {
				html += '<div class="countryBar ' + getRegionId(locations[i].Region) + '" onclick="openCountry(\'' + country + '\',true, false)">';
				html += getCountryIcon(country) + ' ' + country;
				html += '</div>';
				hasCountryBar = true;
			}
			
			var id="siteDetails_" + i;
			var siteid = "site_" + i;
			
			html += '<div class="site" id="' + siteid + '" onclick="showLocationDetail(' + i + ', true)">';
			
			html += '<table width="100%"><tr>';

			var img = '<img src="' + getDivisionIcon(locations[i].OfficeDivision, "icon") + '" align="absMiddle" class="siteIcon">';
		
			html += '<td width="24">' + img + '</td>';
			html += '<td width="25%" valign="middle">';
			html += '<span class="siteName">' + locations[i].OfficeCity + '</span>';
			html += '<br>' + (locations[i].CompanyName ? locations[i].CompanyName : "");
			html += '</td>';
			
			html += '<td width="25%">' + getAddress(locations[i], "<br>", false) + '</td>';
			
			html += '<td width="25%">';
			html += 'Phone: ' + (locations[i].CallCenterPhone ? locations[i].CallCenterPhone : 'n/a') + '<br>';
//			html += 'Email: ' + (locations[i].InternetAddress ? ('<a href="mailto:' + locations[i].InternetAddress + '">' + locations[i].InternetAddress + '</a>') : 'n/a');
			html += 'Email: <a href="/contact/" target="_self">Contact us</a>';
			html += '</td>';

			html += '<td width="25%">Divisions: ' + toProperCase(getDivision(locations[i])) + '<br/>Functions: ' + getFunction(locations[i]) + '</td>';

//			html += '<td width="25%">About location: <a href="Javascript:popupWiki(\'' + url + '\', true)">Wikipedia</a>' + '</td>';


			html += '</tr></table>';
			html += '</div>';
			
			html += '<div class="siteDetails" id="' + id + '" style="display:none;">';
			html += '</div>';
			
		}
	}
	
	$("#sitesDiv").html(html);
	$("#sitesDiv").show();
	
	$(".site").mouseover( function() {
			$(this).addClass("siteMouseover");
		}
	)

	$(".site").mouseout( function() {
			$(this).removeClass("siteMouseover");
		}
	)
	
	showCountryList(false);
	
	if(zoomFlag) zoomToCountry(country);
	
}

function highliteRegion(country) {

	$(".regionNameActive").removeClass("regionNameActive");
	
	for(var i=0;i<locations.length; i++) {
		if(locations[i].OfficeCountry == country) {
			var regionId="region" + (locations[i].Region ? locations[i].Region : locations[i].REGION); 
			$('#' + regionId).addClass("regionNameActive");
			break;
		}
	}
	
}

function highliteLocation(siteId) {
	$(".siteActive").removeClass("siteActive");
	$('#' + siteId).addClass("siteActive");
	
}

function getDivision(locObj) {
	var div = locObj.OfficeDivision;
	
	if(div.indexOf(";")>-1) {
		return (div.split(";")).join(", ");
	} else 
		return div;
}

function getFunction(locObj) {
	var func = locObj.CompanyType;
	
	var funcArray = new Array();
	if(func.indexOf("A")>-1) funcArray.push("Administrative");
	if(func.indexOf("I")>-1 || func.indexOf("R")>-1 ) funcArray.push("Innovation");
	if(func.indexOf("P")>-1) funcArray.push("Production");
	if(func.indexOf("S")>-1) funcArray.push("Sales");
	
	return funcArray.join(", ");
}

function zoomToCountry(country) {

	var bounds = new google.maps.LatLngBounds();
	
	for(var i=0;i<locations.length; i++) {
		if(locations[i].OfficeCountry == country) {
			var marker = locations[i].marker;
			if(marker) bounds.extend(marker.getLatLng());
		}
	}
	
	gMap.setCenter(bounds.getCenter());

	//== compute the necessary zoom to see the bounds selection
	//== we zoom out one more so that to leave margins around the bound, otherwise markers might hit the edge of the map
	var newZoom = gMap.getBoundsZoomLevel(bounds)-1;
	
	//== set the minimum zoom between 2 to 8, so that it won't zoom too far in (if only one location in the bounds), or too far out 
	gMap.setZoom(Math.max(2, Math.min(8, newZoom)));	
	
}

function createMarker(latlng, locationName) {
	 debug("create marker latlng=" + latlng.lat() + ", " + latlng.lng());		 		   
	   
	 var myicon = new google.maps.Icon(gMarkerBaseIcon);
	 myicon.image = getMarkerIcon(locationName);
	 
	 var markerOptions = {icon:myicon};
	   
	 var marker = new google.maps.Marker(latlng, markerOptions);
	 
	 gBounds.extend(marker.getLatLng());
	   
	 gMap.addOverlay(marker);
	 
	 if(gAutoCenterMarker==true) gMap.setCenter(marker.getLatLng());

	 google.maps.Event.addListener(marker, "click", function() {
			 var html = '<p class="infoWindow">' + getMarkerInfo(locationName) + '</p>';
			 
			 var options = new Object();
			 options.maxWidth = 400;

			 marker.openInfoWindowHtml(html, options);
			 
			 displayLocation(marker);
	   });
	   
	 return marker;
}

function displayLocation(marker) {

	for(var i=0;i<locations.length; i++) {
		if(marker == locations[i].marker) {
			openCountry(locations[i].OfficeCountry, false, true);
			showLocationDetail(i, false);
			break;
		}
	}
}

function handleGeoCodeResponse(response) {
	//debug(response.name + ", " + response.Status.code);

	if(!response || response.Status.code != 200) {
		debug(response.name + " - " + response.Status.code + " " + reasons[response.Status.code]);
	 	window.status = "Sorry, cannot find address: " + response.name;
		
		var loc = findLocation(response.name);
		if(loc) {
			var comboLocation = document.getElementById("locationSelect");
			var option = document.createElement("option");
			option.text = loc.ScCode;
			option.value = loc.ScCode;
			try {
				comboLocation.add(option, null);
			} catch (ex) {
				comboLocation.add(option);
			}
		}

	}  else {
	 
	 var newResponse = new Object();
	 newResponse = response;
	   
	 var lng = response.Placemark[0].Point.coordinates[0];
	 var lat = response.Placemark[0].Point.coordinates[1];
	 var latlng = new google.maps.LatLng(lat,lng);
	 
	 var newMarkerObj = createMarker(latlng, response.name);  
	 loc = findLocation(response.name);
	 if(loc) loc.marker = newMarkerObj;
	}
	 
}

function resetMap() {
	debug("reset gMap called");
	//gMap.setCenter(new google.maps.LatLng(45.828799,10.898438), 2);
	if(gMap) gMap.setCenter(gIntialCenter , gIntialZoom);
	
	$("#selectLocation").selectOptions('');

	$(".regionNameActive").removeClass("regionNameActive");
	
	$("#regionDiv").show();
	showCountryList(true);
	$("#sitesDiv").hide();
	
	closeInfoWindow();
}

function closeInfoWindow() {
	//== close any open info windows
	for(var i=0;i<locations.length; i++) {
		var marker = locations[i].marker;
		if(marker) marker.closeInfoWindow();
	}
}

function showHideMarkers() {
	showMessage("Showing/hiding markers...", 1);
	for(var i=0; i<markers.length; i++) {
		if(markers[i].isHidden()) markers[i].show();
		else markers[i].hide();
	}
}

function findLocation(locationName) {
	var length = locations.length;
	 for(var i=0; i<length; i++) {
	   var loc = locations[i];
	   var addr = getAddress(loc, "<br>", false);
	   if(addr==locationName) {
			 return loc;
	   }
	 }
	 
	 return null;
}

function getMarkerIcon(locationName) {

	 var loc = findLocation(locationName);
	   
	 return computeLocationIcon(loc);
}

function computeLocationIcon(loc) {

	 var icon = "images/multiDivisionMarker.png";	//== by default, it will be a multi division icon

	 if(loc==null) return icon;
	 
	 var division = "";
	 if(loc.OfficeDivisionIcon==null || loc.OfficeDivisionIcon=="")  //== OfficeDivisionIcon field was added Feb 2, 2009
		 division = loc.OfficeDivision;    //== check division list if the icon info is blank
	 else 
		 division = loc.OfficeDivisionIcon;   //== otherwise use the icon instead

	 icon = getDivisionIcon(division,"marker");
	 
	 return icon;
}

function getDivisionIcon(division, iconType) {

	if(iconType=="icon") {
		iconType = "Icon";
	} else {
		iconType = "Marker";
	}
	
	var icon = "multiDivision";	//== by default, it will be a multi division icon
	
	if(division==null)	
		division = "";
	else 
		division = division.toLowerCase();
	
	if(division.indexOf(",")>-1 || division.indexOf(";")>-1 || division.indexOf("multi")>-1) {	//== multiple divisions
		var icon = "images/multiDivision" + iconType + ".png";	//== ie. "genencorMarker.png"
	} else {
		icon = "images/" + division + iconType + ".png";	//== ie. "genencorMarker.png" 
	}	
	
	return icon;
}

function getMarkerInfo(locationName) {
	var html = "";
	 
	for(var i=0;i<locations.length; i++) {
		var loc = locations[i];
		var addr = getAddress(loc, "<br>", false);
		if(addr==locationName) {

//			var addr = getAddress(loc);
			var marker = loc.marker;
			var locationIndex = i;
					
			html += '<table cellspacing="0" cellpadding="0"><tr><td valign="top" class="infoWindow">';
			
			if(marker) {
				//== create a small static map of the location
				var latlng = marker.getLatLng();
				var staticMapUrl = 'http://maps.google.com/staticmap?center=' + latlng.toUrlValue();
				staticMapUrl += '&zoom=12&size=150x130&markers=' + latlng.toUrlValue() + '&key=' + GMAP_KEY;
				
				var googleLink = "http://maps.google.com/maps?f=q&hl=en&t=m&z=16&q=" + escape(getAddress(loc, ",", false)) + "@" + latlng.toUrlValue();
				
				html += '<a href="' + googleLink + '" target="_blank" title="Open Google Map in a New Window">';
				html += '<img src="' + staticMapUrl + '" width="150" height="130" style="border:1px solid gray;margin-right:15px;">';
				html += '</a>';
				
//				html += '<br>';
//				html += '<a href="Javascript:zoomAtLatLng(' + latlng.lat() + ',' + latlng.lng() + ',3)">Zoom In</a> | ';
//				html += '<a href="Javascript:zoomAtLatLng(' + latlng.lat() + ',' + latlng.lng() + ',-3)">Zoom Out</a>';
			}

			 html += '</td><td valign="top" width="250" class="infoWindow">';
			 html += '<span style="font-size:14px;"><b>' + loc.OfficeCity + '</b></span><br>';
			 html += loc.CompanyName ? loc.CompanyName + '<br>' : "";
					 
			 html += addr + '<br><br>';
			 html += 'Phone: ' + (locations[i].CallCenterPhone ? locations[i].CallCenterPhone : 'n/a') + '<br>';
			 html += 'Email: <a href="/contact/" target="_self">Contact us</a><br/>';
			 html += 'Local Time: ' + getLocalTime(loc.OfficeTimeZone ? loc.OfficeTimeZone : 'n/a') + '<br>';
			 
//			 html += 'Email: <a href="http://www.danisco.com/cms/connect/corporate/about+danisco/contact+us/contact_us_en.htm" target="_blank">Contact Us</a>';

			 html += '<br>';
			 
//			 html += '<a href="Javascript:gotoLocation(' + locationIndex  + ')">Details/Contacts</a> &nbsp;';
//			 html += '| <a href="Javascript:openLoc()">Site Details</a>';
			 
//			 var googleLink = "http://maps.google.com/maps?f=q&hl=en&t=h&z=16&geocode=&q=" + escape(getAddress(loc));
			 
			 html += '<a href="' + googleLink + '" target="_blank">Full Google Map <img src="images/external.png" title="Open in a new window" border="0"></a> &nbsp;';
//			 html += '<a href="Javascript:openLocationPane(' + locationIndex + ', \'Directions To Here\')">Directions</a>';
			 html += '<a href="Javascript:openLocationWindow(' + locationIndex + ', \'Directions To Here\')">Directions <img src="images/external.png" title="Open in a new window" border="0"></a>';
			 
			 html += '</td></tr></table>';

			 return html;
		}
	}
	 //=== no match found
	 html = '<p class="infoWindow"><b>' + locationName + '</b><br>Sorry, cannot load detail information.</p>' 
	 return html;
}

//== TODO Need to add Day Light Saving time handling logics here. - Tony Wu, Dec 4, 2009
function getLocalTime(timezone) {
	for(var i=0;i<timzonesList.length; i++) {
		if(timezone == timzonesList[i][0]) {
			
			var offset = timzonesList[i][1];
			
			//== check if day light saving is observed for this timezone
			if(timzonesList[i][2]==1) {
				var now = new Date();
				
				//== if it's between the month of April to October, then add one hour
				//== NOTE that day light saving start/stop time is different everywhere, so this is just a approximation
				if(now.getMonth()>=4 && now.getMonth()<=10) {
					offset += 1;	// add the extra hour for DST
				}
			}
			
		    // create Date object for current location
		    d = new Date();
		   
		    // convert to msec
		    // add local time zone offset
		    // get UTC time in msec
		    utc = d.getTime() + (d.getTimezoneOffset() * 60000);
		   
		    // create new Date object for different city
		    // using supplied offset
		    nd = new Date(utc + (3600000*offset));
		   
		    // return time as a string
		    return dateFormat(nd, "HH:MM mmm d");
			
		}
	}
	//== otherwise timezone info not found in the list, just return the original value
	return timezone;
}

function timedGetLocation(index) {
	var loc = locations[index];
	createLocationMarker(loc);
}

function createLocationMarker(loc) {
		
	 if(loc.Lat!=null && loc.Lat!="" && loc.Lng!=null && loc.Lng!="") {
	   var locName = getAddress(loc, "<br>", false);
	   debug(locName + " - preset coord: " + loc.Lat +"," + loc.Lng);
	   var latlng = new google.maps.LatLng(parseFloat(loc.Lat), parseFloat(loc.Lng));
	   var marker = createMarker(latlng, locName);
	   loc.marker = marker;
	 } else {
			 var ggeo = new google.maps.ClientGeocoder();
			 var address = getAddress(loc, "<br>", false);
			 ggeo.getLocations(address, handleGeoCodeResponse);
	 }
}

function getLocationByScCode(scCode) {
	 for(var i=0;i<locations.length;i++) {
			 if(scCode==locations[i].ScCode) return locations[i];
	 }
	 return null;
}

function getAddress(loc, deliminator, useNativeCity) {
	 
	 var officeCity = loc.OfficeCity; 
	 if(useNativeCity && loc.OfficeCityNative!="") {
		 officeCity = loc.OfficeCityNative;
	 }

	 var zip = loc.OfficeZIP==null ? "": ((loc.OfficeZIP).length>0 ? loc.OfficeZIP + " ": "");
	 var state = loc.OfficeState==null ? "": ((loc.OfficeState).length>0 ? (", " + loc.OfficeState): "");
	 
	 var Postbox = loc.OfficePostBox ? (loc.OfficePostBox + deliminator) : ""; 
	 
	 var addr2 = (loc.OfficeStreetAddress2!=null && loc.OfficeStreetAddress2!="" ? loc.OfficeStreetAddress2 + deliminator : "");
	 var addr = loc.OfficeStreetAddress + deliminator + addr2 + Postbox + zip + officeCity + state + deliminator + loc.OfficeCountry;
	 
	 var country = loc.OfficeCountry;
	 if(("USA, UNITED STATES, CANADA").indexOf(country.toUpperCase())>-1) 
		addr = loc.OfficeStreetAddress + deliminator + addr2 + Postbox + officeCity + ", " + (loc.OfficeState ? loc.OfficeState+" " : "") + loc.OfficeZIP + deliminator + loc.OfficeCountry;
		 
	 return addr;
}

function centerMap() {
	debug("centermap called");

	var currentZoom = gMap.getZoom();
	
	if(currentZoom<=2)  //== at zoom level 2 or less (world), the setCenter behaves weirdly on bounds, so we set our own center
		gMap.setCenter(gIntialCenter, gIntialZoom);   
	else //== otherwise center by the selection (markers shown)
		gMap.setCenter(gBounds.getCenter()); 	 

	//== compute the necessary zoom to see the bounds selection
	//== we zoom out one more so that to leave margins around the bound, otherwise markers might hit the edge of the map
	var newZoom = gMap.getBoundsZoomLevel(gBounds)-1;
	
	//== set the minimum zoom between 2 to 8, so that it won't zoom too far in (if only one location in the bounds), or too far out 
	gMap.setZoom(Math.max(2, Math.min(8, newZoom)));	

	gAutoCenterMarker = true;
}

function showLocationsOnMap() {
	 debug("show locations on map called, total location= " + locations.length);
					 
	 gAutoCenterMarker = false;
	 	 
	 var comboLocation = document.getElementById("locationSelect");
	 comboLocation.options.length = 0;

	 var locationsLength = locations.length;
	 
	 for(var i=0, t=0;i<locationsLength;i++) {
		var loc = locations[i];
		if(loc.Lat!=null && loc.Lat!="" && loc.Lng!=null && loc.Lng!="") {  //if coordinate exist, create marker right away
			timedGetLocation(i);
		} else {
			t++;
			setTimeout("timedGetLocation(" + i + ")", t*250);   // else geocode the address, we only limit 4 geocoding per second, to avoid overloading Google
		}
	 }
	 if(t>1) setTimeout("centerMap()", (t+10)*250);

	 var mapBounds = gMap.getBounds();
	 if(mapBounds.containsBounds(gBounds)) {
		 //== the map can already see all marker bounds, do nothing
	 } else 		 
		 centerMap();  //== otherwise zoom to selection
	 
	 var now = new Date();
	 var diff = now.getTime() - gStartTime.getTime();
	 showMessage("Map loaded in " + diff/1000 + " seconds.", 2);
	 
	 debug("show locations on map finished");
}

function mapZoom(zoomType) {
	if(zoomType=="world") {
//		gMap.setCenter(new google.maps.LatLng(11.178402,22.851563), 2);
		gMap.setCenter(gIntialCenter, gIntialZoom);
	} else if(zoomType=="selection") {
		centerMap();
	}
}

function geocodeAddress(){
	var debugAddress = document.getElementById("debugAddress");
	var ggeo = new google.maps.ClientGeocoder();
			 
    ggeo.getLocations(debugAddress.value, geocodeResult);
}

function geocodeResult(response) {
	var debugAddressResult = document.getElementById("debugAddressResult");
	
	if(!response || response.Status.code != 200) {
		debug(response.name + " - " + response.Status.code + " " + reasons[response.Status.code]);
	 	debugAddressResult = reasons[response.Status.code];
	}  else {
	   
	 var newResponse = new Object();
	 newResponse = response;
	   
	 var lng = response.Placemark[0].Point.coordinates[0];
	 var lat = response.Placemark[0].Point.coordinates[1];
	 var latlng = new google.maps.LatLng(lat,lng);
	 
	 var marker = createMarker(latlng, response.name);  
	 var locObj = findLocation(response.name);
	 if(locObj) locObj.marker = newMarkerObj;
	 var debugLat = document.getElementById("debugLat");
	 var debugLng = document.getElementById("debugLng");
	 debugLat.value = (marker.getLatLng()).lat();
	 debugLng.value = (marker.getLatLng()).lng();
	 
	}
}

function openLocationPane(locationIndex, infoType) {

//	 var gmap = document.getElementById("map");
//	 if(gmap) gmap.style.height = "50%";
//
//	 gMap.checkResize();
//	 
//	 var pane = document.getElementById("locationPane");
//	 pane.style.display = "block";

	var loc = locations[locationIndex];

	var url = "http://maps.google.com";

	var latlng = new google.maps.LatLng();

	if(loc.marker) {
		var marker = loc.marker;
		latlng = marker.getLatLng();
	} else {
		latlng = gMap.getCenter();
	}

	//alert("latlng=" + latlng.toUrlValue());

	var sll = "&sll=" + latlng.toUrlValue(); //== search business from this point
	var ll = "&ll=" + latlng.toUrlValue();  //== center the map here
	var options = "&sspn=0.090425,0.139389&spn=0.180852,0.278778&z=12";

	if(infoType=="Hotels") {
		url = "http://maps.google.com/maps?&q=" + infoType + ll + sll + options; 
	} else if(infoType=="Airport") {
		url = "http://maps.google.com/maps?&q=" + infoType +  ll + sll + options;
	} else if(infoType=="Restaurant") {
		url = "http://maps.google.com/maps?&q=" + infoType +  ll + sll + options;
	} else if(infoType=="Directions To Here") {
		 url = "http://maps.google.com/maps?f=q&hl=en&t=m&z=12&daddr=" + escape(getAddress(loc, ",", false)) + "@" + latlng.toUrlValue();
//		url = "http://maps.google.com/maps?&daddr=" + escape(getAddress(loc)) + "&z=12";
	} else if(infoType=="Info") {
		url = "http://cphgln08.danisco.com/danisco/dip/whoiswho/prod/whoiswho.nsf/ScCodeDIP4/" + loc.ScCode + "?OpenDocument";
	} else if(infoType=="Employees") {
		url = "http://cphgln08.danisco.com/danisco/dip/whoiswho/prod/whoiswho.nsf/employeesList?OpenPage&location=" + loc.ScCode;
	}

	popupWiki(locationIndex);
	$("#wikiIframe").attr("src", url);	
}

function openLocationWindow(locationIndex, infoType) {

	var loc = locations[locationIndex];

	var url = "http://maps.google.com";

	var latlng = new google.maps.LatLng();

	if(loc.marker) {
		var marker = loc.marker;
		latlng = marker.getLatLng();
	} else {
		latlng = gMap.getCenter();
	}

	//alert("latlng=" + latlng.toUrlValue());

	var sll = "&sll=" + latlng.toUrlValue(); //== search business from this point
	var ll = "&ll=" + latlng.toUrlValue();  //== center the map here
	var options = "&sspn=0.090425,0.139389&spn=0.180852,0.278778&z=12";

	if(infoType=="Hotels") {
		url = "http://maps.google.com/maps?&q=" + infoType + ll + sll + options; 
	} else if(infoType=="Airport") {
		url = "http://maps.google.com/maps?&q=" + infoType +  ll + sll + options;
	} else if(infoType=="Restaurant") {
		url = "http://maps.google.com/maps?&q=" + infoType +  ll + sll + options;
	} else if(infoType=="Directions To Here") {
		 url = "http://maps.google.com/maps?f=q&hl=en&t=m&z=12&daddr=" + escape(getAddress(loc, ",", false)) + "@" + latlng.toUrlValue();
//		url = "http://maps.google.com/maps?&daddr=" + escape(getAddress(loc));
	} else if(infoType=="Info") {
		url = "http://cphgln08.danisco.com/danisco/dip/whoiswho/prod/whoiswho.nsf/ScCodeDIP4/" + loc.ScCode + "?OpenDocument";
	} else if(infoType=="Employees") {
		url = "http://cphgln08.danisco.com/danisco/dip/whoiswho/prod/whoiswho.nsf/employeesList?OpenPage&location=" + loc.ScCode;
	}

	window.open(url, "_blank", "");
}

function debug(msg) {
	if(DEBUG) {
		   var elm = document.getElementById("debugtext");
		   if(elm.style.display!="block") elm.style.display = "block";
		   if(elm) {
				 //alert(elm.text);
				 var now = new Date();
				 var diff = now.getTime() - gStartTime.getTime(); 
				 elm.value = diff + "ms: " + msg + "\n" + elm.value;
		   }
	}
}

function getWindowSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return [myWidth, myHeight];
}

//=== show message popup display
//== message --- the message you want to display
//== showDuration ---  -1, show the message indefinitely
//==                    0, hide's the message
//==                    n>1, show the message for n seconds, then hide the msg box 
function showMessage(message, showDuration) {
	var msgObj = document.getElementById("messageBox");
	if(msgObj) {
		msgObj.innerHTML = message;
		if(showDuration==-1) {
			msgObj.style.display = "block";		
		} else if(showDuration==0) {
			hideMessage();
		} else if(showDuration>0) {
			setTimeout("hideMessage()", showDuration*1000);
		}
	} else {
		alert("cannot get messagebox!!");
	}
}
//== hide the message display
function hideMessage() {
	var msgObj = document.getElementById("messageBox");
	if(msgObj) msgObj.style.display = "none";
}

function getDivisionFunctions(locationObj) {
	//== convert an incoming list, ie:
	// All:Sales
	// All:Production
	// Genencor:Sales
	// Genencor:Innovation
	// SAFI:Sales
	// INTO a table display		

	var divFunctions = locationObj.DivisionFunctions;
	
	if(divFunctions=="") 
		return "";
	else { //if(divFunctions.indexOf(",")>-1) 
		var tmpList = divFunctions.split(";");
		tmpList.sort();
		
		var workingList = new Array();
		var divMarkers = new Array();
		for(var i=0; i<tmpList.length; i++) {
			var divFunc = tmpList[i].split(":");  //== now [0]="Genencor", [1]="Sales"
			if(workingList.length==0 || workingList.indexOf(divFunc[0])==-1) {	//== add the division if not already exist
				divMarkers.push(workingList.length);	//== flag where the division label is stored
				workingList.push(divFunc[0]);
			}
			workingList.push(divFunc[1]);	//== push the functions to the list
		}
		
		divMarkers.push(workingList.length);	//== to mark the end boundary, convenient to get the "line" below

		var html = "";
		html += '<table cellspacing="1" cellpadding="0"><tr>';

		for(i=0;i<divMarkers.length-1; i++) {
			var line = workingList.slice(divMarkers[i], divMarkers[i+1]);
					
			var division = line.shift();
			
			//== we don't output the "All" division column, unless this is the only column info available. ie. for Bratislava, Solvak Republic
			if(divMarkers.length==2 || (divMarkers.length>2 && division!="All")) {

				var divImg = '<img src="' + getDivisionIcon(division, "icon") + '" title="' + division + '">';
				html += '<td valign="top">';
				if(division!="All") {
					html += '<div class="functions_division_icon">' + divImg + '</div>';  //== the division icon
					html += '<div class="iconUnderline">&nbsp;</div>';	//== "paint" the line under the "chopped" icon above, so it looks like a completed circle
				}
				
				//== output the site functions
				for(var j=0; j<line.length; j++) {
					var style= 'function_base function_' + line[j];
					                                         
					html += '<div class="' + style + '" title="' + line[j] + '">';
					html += (divMarkers.length>3) ? line[j].substr(0,1): line[j];	//== only use the initial of the function, ie. S = Sales, P= Produciton etc.
					html += '</div>';
				}
				html += "</td>";
			}
		}
			
		html += "</tr></table>";
		return html;	
	}	
		
}

function getDivisionFunctionsTable(locationObj) {
	//== convert an incoming list, ie:
	// All:Sales
	// All:Production
	// Genencor:Sales
	// Genencor:Innovation
	// SAFI:Sales
	// INTO a table display		

	var divFunctions = locationObj.DivisionFunctions;
	
	var functions = ["Administration", "Innovation", "Production", "Sales"];
	var divisions = new Array();
	
	if(divFunctions=="") 
		return "";
	else { //if(divFunctions.indexOf(",")>-1) 
		var tmpList = divFunctions.split(";");
		tmpList.sort();
		
		var workingList = new Array();
		var divMarkers = new Array();
		for(var i=0; i<tmpList.length; i++) {
			var divFunc = tmpList[i].split(":");  //== now [0]="Genencor", [1]="Sales"
			if(workingList.length==0 || workingList.indexOf(divFunc[0])==-1) {	//== add the division if not already exist
				divMarkers.push(workingList.length);	//== flag where the division label is stored
				workingList.push(divFunc[0]);
				divisions.push(divFunc[0]);	//== add to the divisions (table column) list
			}
			workingList.push(divFunc[1]);	//== push the functions to the list
		}
		
//		divMarkers.push(workingList.length);	//== to mark the end boundary, convenient to get the "line" below

		var html = "";
		html += '<table class="divisionsFunctionsTable">';
		
		//== output the divisions line
		html += '<tr><th width="100">&nbsp;</th>'
		for(var d=0;d<divisions.length;d++) {
			if(divisions[d]!="All") {
				html += '<th>';
				var divImg = '<img src="' + getDivisionIcon(divisions[d],"icon") + '" title="' + divisions[d] + '">';
				html += '<div class="functions_division_icon">' + divImg + '</div>';  //== the division icon
				html += '<div class="iconUnderline">&nbsp;</div>';	//== "paint" the line under the "chopped" icon above, so it looks like a completed circle
				html += '</th>';
			}
		}
		html += '</tr>';
		
		//== output the site functions
		for(var f=0; f<functions.length; f++) {
			
			var tmphtml = '';
			var hasDataInRow = false;
			
			tmphtml += '<tr>';
			tmphtml += '<td class="function_base">' + functions[f] + '</td>';
			
			for(d=0;d<divisions.length;d++) {
				if(divisions[d]!="All") {
					var fStyle = "function_" + functions[f];
					
					tmphtml += '<td class="function_base ' + fStyle + '">';
					
					var divFuncPair = divisions[d] + ':' + functions[f];
					if(divFunctions.indexOf(divFuncPair)>-1) {
						hasDataInRow = true;
						tmphtml += '<b>x</b>';
					} else {
						tmphtml += '&nbsp;';
					}
				tmphtml += '</td>';
				}
			}
			
			tmphtml += '</tr>';
			
			if(hasDataInRow) html += tmphtml;	//== we only show a site function row if it has data 
		}
		
		
		html +='</table>';
			
//		var style= 'function_base function_' + line[j];
//			                                         
//			html += '<div class="' + style + '" title="' + line[j] + '">';
//			html += (divMarkers.length>3) ? line[j].substr(0,1): line[j];	//== only use the initial of the function, ie. S = Sales, P= Produciton etc.
//			html += '</div>';
//		}
//
//	
//		for(i=0;i<divMarkers.length-1; i++) {
//			var line = workingList.slice(divMarkers[i], divMarkers[i+1]);
//					
//			var division = line.shift();
//			
//			//== we don't output the "All" division column, unless this is the only column info available. ie. for Bratislava, Solvak Republic
//			if(divMarkers.length==2 || (divMarkers.length>2 && division!="All")) {
//
//				var divImg = '<img src="' + getDivisionIcon(division) + '" title="' + division + '">';
//				html += '<td valign="top">';
//				if(division!="All") {
//					html += '<div class="functions_division_icon">' + divImg + '</div>';  //== the division icon
//					html += '<div class="iconUnderline">&nbsp;</div>';	//== "paint" the line under the "chopped" icon above, so it looks like a completed circle
//				}
//				
//				//== output the site functions
//				for(var j=0; j<line.length; j++) {
//					var style= 'function_base function_' + line[j];
//					                                         
//					html += '<div class="' + style + '" title="' + line[j] + '">';
//					html += (divMarkers.length>3) ? line[j].substr(0,1): line[j];	//== only use the initial of the function, ie. S = Sales, P= Produciton etc.
//					html += '</div>';
//				}
//				html += "</td>";
//			}
//		}
//			
//		html += "</tr></table>";
		return html;	
	}	
		
}

function getDivisionFunctionsTextOutput(locationObj) {
//== convert an incoming list, ie:
// All:Sales
// All:Production
// Genencor:Sales
// Genencor:Innovation
// SAFI:Sales
// INTO:
// All (Sales, Production), Genencor (Sales, Innovation), SAFI (Sales)
	
	var divFunctions = locationObj.DivisionFunctions;
	
	if(divFunctions=="") 
		return "";
	else if(divFunctions.indexOf(",")>-1) {
		var tmpList = divFunctions.split(", ");
		tmpList.sort();
		
		var workingList = new Array();
		var divMarkers = new Array();
		for(var i=0; i<tmpList.length; i++) {
			var divFunc = tmpList[i].split(":");  //== now [0]="Genencor", [1]="Sales"
			if(workingList.indexOf(divFunc[0])==-1) {
				divMarkers.push(workingList.length);	//== flag where the division label is stored
				workingList.push(divFunc[0]);
			}
			workingList.push(divFunc[1]);	//== push the functions to the list
		}
		
		divMarkers.push(workingList.length);

		var html = "";		
		for(i=0;i<divMarkers.length-1; i++) {
			var line = workingList.slice(divMarkers[i], divMarkers[i+1]);
			html += (i>0 ? ", ": "") + line.shift() + " (";	//== genereates this: "Genencor (", or ", Genencor ("
			html += line.join(",");  //== generates this: Sales,Innovation
			html += ")";
		}
		return html;	
	}
	else
		return divFunctions;
}

function replaceStr(originalStr,findStr,replaceStr)
{
	var newStr = originalStr;
	
	if(originalStr.indexOf(findStr)>-1) {
		newStr = (originalStr.split(findStr)).join(replaceStr);
	}	

	return newStr;
}

function zoomAtLatLng(lat, lng, zoomAdjust) {
	var currentZoom = gMap.getZoom();
	gMap.setZoom(currentZoom+zoomAdjust);
}

function handleLocationSelectionChange() {
	var option = $("#selectLocation").selectedOptions();
	
//	alert("you selected " + option[0].value);
	
	for(var i=0;i<locations.length;i++) {
		var loc = locations[i];
		if(loc.ID == option[0].value) {
			gotoLocation(i);
			break;
		}
	}

}

function gotoLocation(locationIndex) {
	var loc = locations[locationIndex];
	openCountry(loc.OfficeCountry,true, true);
	showLocationDetail(locationIndex, true);
}

function showMarkerInfoWindow(locationIndex) {
	//== popup the Gmap info window
	var locationObj = locations[locationIndex];
	if(locationObj) {
		 var marker = locationObj.marker;
		 if(marker) {
			 
			gMap.setCenter(marker.getLatLng(), 11);
			
			var locName = getAddress(locationObj, "<br>", false);
		 	var html = '<p class="infoWindow">' + getMarkerInfo(locName) + '</p>'; 
			var options = new Object();
			options.maxWidth = 400;
			marker.openInfoWindowHtml(html, options);
		}
	 }
}

function getCenter() {
	var latlng = gMap.getCenter();
	
	alert(latlng.toUrlValue());
}


//========================================================================
/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

//== http://www.michaelapproved.com/articles/timezone-detect-and-ignore-daylight-saving-time-dst/
function TimezoneDetect(){
    var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
    var intOffset = 100; //set initial offset high so it is adjusted on the first attempt
    var intMonth;
    var intHoursUtc;
    var intHours;
    var intDaysMultiplyBy;

    //go through each month to find the lowest offset to account for DST
    for (intMonth=0;intMonth < 12;intMonth++){
        //go to the next month
        dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);

        //To ignore daylight saving time look for the lowest offset.
        //Since, during DST, the clock moves forward, it'll be a bigger number.
        if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
            intOffset = (dtDate.getTimezoneOffset() * (-1));
        }
    }

    return intOffset;
}

//== http://www.michaelapproved.com/articles/daylight-saving-time-dst-detect/
//Find start and end of DST
function DstDetect(){
    var dtDstDetect = new Date();
    var dtDstStart = '';
    var dtDstEnd = '';
    var dtDstStartHold = ''; //Temp date hold
    var intYearDayCount = 732; //366 (include leap year) * 2 (for two years)
    var intHourOfYear = 1;
    var intDayOfYear;
    var intOffset = TimezoneDetect(); //Custom function. Make sure you include it.

    //Start from a year ago to make sure we include any previously starting DST
    dtDstDetect = new Date()
    dtDstDetect.setUTCFullYear(dtDstDetect.getUTCFullYear() - 1);
    dtDstDetect.setUTCHours(0,0,0,0);

    //Going hour by hour through the year will detect DST with shorter code but that could result in 8760
    //FOR loops and several seconds of script execution time. Longer code narrows this down a little.
    //Go one day at a time and find out approx time of DST and if there even is DST on this computer.
    //Also need to make sure we catch the most current start and end cycle.
    for(intDayOfYear = 1; intDayOfYear <= intYearDayCount; intDayOfYear++){
        dtDstDetect.setUTCDate(dtDstDetect.getUTCDate() + 1);

        if ((dtDstDetect.getTimezoneOffset() * (-1)) != intOffset && dtDstStartHold == ''){
            dtDstStartHold = new Date(dtDstDetect);
        }
        if ((dtDstDetect.getTimezoneOffset() * (-1)) == intOffset && dtDstStartHold != ''){
            dtDstStart = new Date(dtDstStartHold);
            dtDstEnd = new Date(dtDstDetect);
            dtDstStartHold = '';

            //DST is being used in this timezone. Narrow the time down to the exact hour the change happens
            //Remove 48 hours (a few extra to be on safe side) from the start/end date and find the exact change point
            //Go hour by hour until a change in the timezone offset is detected.
            dtDstStart.setUTCHours(dtDstStart.getUTCHours() - 48);
            dtDstEnd.setUTCHours(dtDstEnd.getUTCHours() - 48);

            //First find when DST starts
            for(intHourOfYear=1; intHourOfYear <= 48; intHourOfYear++){
                dtDstStart.setUTCHours(dtDstStart.getUTCHours() + 1);

                //If we found it then exit the loop. dtDstStart will have the correct value left in it.
                if ((dtDstStart.getTimezoneOffset() * (-1)) != intOffset){
                    break;
                }
            }

            //Now find out when DST ends
            for(intHourOfYear=1; intHourOfYear <= 48; intHourOfYear++){
                dtDstEnd.setUTCHours(dtDstEnd.getUTCHours() + 1);

                //If we found it then exit the loop. dtDstEnd will have the correct value left in it.
                if ((dtDstEnd.getTimezoneOffset() * (-1)) != (intOffset + 60)){
                    break;
                }
            }

            //Check if DST is currently on for this time frame. If it is then return these values.
            //If not then keep going. The function will either return the last values collected
            //or another value that is currently in effect
            if ((new Date()).getTime() >= dtDstStart.getTime() && (new Date()).getTime() <= dtDstEnd.getTime()){
                return new Array(dtDstStart,dtDstEnd);
            }

        }
    }
    return new Array(dtDstStart,dtDstEnd);
}

//==

function toProperCase(str)
{
	    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
