$(document).ready(function() {
	KMaps.loadMap();
	KMaps.loadStores();
	KMaps.autoFill();	
});

var KMaps = {
	map: '',
	stores: {},
	markers: [],
	search: '',
	geocoder: '',
	results: [],
	
	loadMap: function() {
		this.map = new GMap2(document.getElementById('map'));
		this.map.setUIToDefault();
		//var antwerp = new GLatLng(51.209293,4.393614);
		var antwerp = new GLatLng(0, 0);
		this.map.setCenter(antwerp, 1);
		this.geocoder = new GClientGeocoder();
	},
	loadStores: function() {
		$.getJSON(Generatrix.href('/storelocator/stores'), {}, function(json) {
			KMaps.stores = json;
			KMaps.runLoop();
			//setTimeout(function(){KMaps.runLoop();}, 500);
		});
	},
	autoFill: function() {
		$.ajax ({
      type : "GET" ,
      dataType : "json",
      url : Generatrix.href("/ajax/getStoresInfo"),
      success : function ( data ) {
										var locations = [];
										for ( x in data ) {
											if ( data[x]['city'] != '' && data[x]['state'] && data[x]['country'] ) {
												locations.push ( data[x]['city'] + ', ' +  data[x]['state'] + ', '+ data[x]['country'] );
											} else if ( data[x]['city'] == '' && data[x]['state'] && data[x]['country'] ) {
												locations.push ( data[x]['state'] + ', '+ data[x]['country'] );
											} else if ( data[x]['city'] && data[x]['state'] == '' && data[x]['country'] ) {
												locations.push ( data[x]['city'] + ', '+ data[x]['country'] );
											} 
										}
										$("#text").autocomplete(locations, {
											matchContains: true,
										});
            }
    });
	},
	runLoop: function() {
		var new_search = $("#text").val();
		if((new_search != this.search) || (new_search.length == '')) {
			this.search = new_search;
			this.map.clearOverlays();
			for(x in this.stores) {
				this.match(x);
			}
			this.displayMatchedShops();
			this.displayResults();
		}
		setTimeout("KMaps.runLoop()", 6000);
	},

	displayFirst: function() {
		var result = '';
		var value = 1;
		result = '<h3 id="maps_results"><a href="#showmap">' + this.stores[value].name + '</a></h3><p>' + this.stores[value].address + '<br />' + this.stores[value].city + ', ' + this.stores[value].state + '<br /> ' + this.stores[value].zip + '<br /> ' + this.stores[value].country + '<br />' + this.stores[value].phone__space__number + '<br />' + this.stores[value].link + '</p>';
		return result;
	},

	match: function(store_id) {
		var hl = false;
		
		if(this.search != '') {
			var split = this.search.split(',');
			var arrlength = split.length;
			var re = new RegExp(this.search, "i");
	
			if( arrlength == 3 ) {
				var match_city =  new RegExp( split[0].replace(/^\s*/, "").replace(/\s*$/, ""), "i");
				var city_results = KMaps.stores[store_id].city.match(match_city);
				var match_state =  new RegExp( split[1].replace(/^\s*/, "").replace(/\s*$/, ""), "i");
				var state_results = KMaps.stores[store_id].state.match(match_state);
				var match_country =  new RegExp( split[2].replace(/^\s*/, "").replace(/\s*$/, ""), "i");
				var country_results = KMaps.stores[store_id].country.match(match_country);


				if((city_results != null) && (country_results != null) && (state_results != null ) ) {
					if((KMaps.stores[store_id].longitude != null) && (KMaps.stores[store_id].latitude != null)) {
	          hl = true;
	          this.results.push(store_id);
						this.map.clearOverlays();
	          //this.setMarker(store_id, 1);
        	}
				}
			} if( arrlength == 2 ) {
				var match_citystate =  new RegExp( split[0].replace(/^\s*/, "").replace(/\s*$/, ""), "i");
				var city_results = KMaps.stores[store_id].city.match(match_citystate);
				var state_results = KMaps.stores[store_id].state.match(match_citystate);
				
				var match_country =  new RegExp( split[1].replace(/^\s*/, "").replace(/\s*$/, ""), "i");
				var country_results = KMaps.stores[store_id].country.match(match_country);

				if((city_results != null || state_results != null) && (country_results != null) ) {
					if((KMaps.stores[store_id].longitude != null) && (KMaps.stores[store_id].latitude != null)) {
	          hl = true;
	          this.results.push(store_id);
						this.map.clearOverlays();
	          //this.setMarker(store_id, 1);
        	}
				}
			} if (arrlength == 1 ) {
				var res = new RegExp( split[0].replace(/^\s*/, "").replace(/\s*$/, ""), "i" );
				var city_results = KMaps.stores[store_id].city.match(res);
				var state_results = KMaps.stores[store_id].state.match(res);
				var country_results = KMaps.stores[store_id].country.match(res);
				if((city_results != null) || (country_results != null) || (state_results != null)) {
					if((KMaps.stores[store_id].longitude != null) && (KMaps.stores[store_id].latitude != null)) {
	          hl = true;
	          this.results.push(store_id);
						this.map.clearOverlays();
	          //this.setMarker(store_id, 1);
        	}
				}
			}
		}
	},
	displayMatchedShops: function() {
		for(x in this.results) {
			this.setMarker(this.results[x], 1);
		}
	},
	setMarker: function(store_id, highlight) {
		var lng = KMaps.stores[store_id].longitude;
		var lat = KMaps.stores[store_id].latitude;
		var address = KMaps.stores[store_id].address;
		var name = KMaps.stores[store_id].name;
		var state = KMaps.stores[store_id].state;
		var city = KMaps.stores[store_id].city;
		var country = KMaps.stores[store_id].country;	
		var image_file = KMaps.stores[store_id].image_file;	
		var zip = KMaps.stores[store_id].zip;	
		var phone = KMaps.stores[store_id].phone__space__number;	
			
		var img_color = (highlight == 1) ? 'orange' : 'gray';
	
		if((lat != '') && (lng != '')) {
			var point = new GLatLng(lat, lng);
			
			if(this.markers[store_id] != null) {
				this.map.removeOverlay(this.markers[store_id]);
			}
			
			this.markers[store_id] = new GMarker(point);
			var marker = this.markers[store_id];
			this.map.addOverlay(this.markers[store_id]);

			GEvent.addListener(marker, 'mouseover',
      	function() {
				var htmlString = '';
					if(image_file.length > 1) {
						var htmlString = '<div id="maps_results"><h3>' + name + '</h3></div><p>' + address  + '<br />' + city + state + '<br />' + zip + '<br />'+ country +  '<br />phone: ' + phone + '<br /><div class="result-store-img" style="height: 150px;"><img src="' + Generatrix.href('/framework/external/timthumb/timthumb.php?src='+Generatrix.href(image_file)+'&w=218&h=147').replace(/ /g, "")  + '"/></div></p>';
					}else {
						var htmlString = '<div id="maps_results"><h3>' + name + '</h3></div><p>' + address  + '<br />' + city + state + '<br />' + zip + '<br />'+ country +  '<br />phone: ' + phone + '</p>';
					}

         	marker.openInfoWindowHtml(htmlString);
      	}
   		);
			
			this.markers[store_id].setImage(Generatrix.href('/public/images/orange.png'));
		}
	},
	displayResults: function() {
		$("#results").html('');
		var firstplace;
		var map2= this.map;
		var inputval = $("#text").val(); 
		if(!this.results.length && inputval != '' ) {
			$("#results").append("We have no stockist in your city, please enter the country for nearest store, or contact <a style='color: #FFF; font-size: 12px; font-weight:normal; text-decoration: normal;' href='mailto:distribution@kirkoriginals.com'>distribution@kirkoriginals.com</a> ");
		KMaps.loadMap();
		} else {
			$("#results").append("");
		}
		for(x in this.results) {
			var value = this.results[x];
			var firstplace = this.results[0];
		
			var name = this.stores[value].name + '@$$@' + this.stores[value].address + '@$$@' + this.stores[value].city + '@$$@' + this.stores[value].state + '@$$@' + this.stores[value].zip + '@$$@' + this.stores[value].country + '@$$@'  + this.stores[value].phone__space__number + '@$$@' + this.stores[value].link + '@$$@' +  this.stores[value].image_file ;  

			var address = this.stores[value].address + ', ' + this.stores[value].city + ', ' + this.stores[value].state + ', ' + this.stores[value].country;
			var displayaddress = '';

			if(this.stores[value].link != '' ) {
				link = this.stores[value].link;
				var str = link.match('http://');
				if(str){
					link = this.stores[value].link;
				} else {
					link = 'http://'+this.stores[value].link;
				}
					
				$("#results").append('<div class="results-title"  id="maps_results"><a class="maphover" href="#showmap" name=" ' + name + ' "  title="' + address + '" >' + this.stores[value].name + '</a><p>' + this.stores[value].address + '<br />'  +  this.stores[value].city + ' ' + this.stores[value].state + '<br />' + this.stores[value].zip + '<br />' + this.stores[value].country + '<br /> Phone : ' + this.stores[value].phone__space__number + '<br /><a style="color: #FFF; font-weight: normal;font-size: 13px" target="_blank"  href="' + link + '">' + this.stores[value].link + '</a></p></div>');
			} else {
				$("#results").append('<div class="results-title" id="maps_results"><a class="maphover"   href="#showmap" name=" ' + name + ' "  title="' + address + '" >' + this.stores[value].name + '</a><p>' + this.stores[value].address + '<br />' + this.stores[value].city + ' ' + this.stores[value].state + ' <br />' + this.stores[value].zip + '<br />' + this.stores[value].country + '<br /> Phone : ' + this.stores[value].phone__space__number + '<br />&nbsp;</p></div>');
			}


		var displayaddress = '';

var stores = new Array(this.stores[firstplace].name, this.stores[firstplace].address, this.stores[firstplace].city, this.stores[firstplace].state, this.stores[firstplace].zip, this.stores[firstplace].country, this.stores[firstplace].phone__space__number, this.stores[firstplace].link, this.stores[firstplace].image_file);

		if(x == 0) {

			 if(stores[7] ) {
			      if(stores[8].length > 1) {
			          displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' + stores[5] + '<br />Phone: ' + stores[6] + '<br />' + stores[7] + '<br /><div class="result-store-img"  style="height: 150px;"><img  src="' + Generatrix.href('/framework/external/timthumb/timthumb.php?src='+Generatrix.href(stores[8])+'&w=218&h=147').replace(/ /g, "")  + '"/></p>';
			      } else {
			          displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' + stores[5] + '<br />Phone: ' + stores[6] + '<br />' + stores[7] + '</p>';
				
			      }
			    } else {
			      if(stores[8].length > 1) {
			          displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' +  stores[5] + '<br />Phone: ' + stores[6] + '<br /><div class="result-store-img" style="height: 150px"><img src="' + Generatrix.href('/framework/external/timthumb/timthumb.php?src='+Generatrix.href(stores[8])+'&w=218&h=147').replace(/ /g, "") + '"/></div></p>';
			      } else {
			          displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' +  stores[5] + '<br />Phone: ' + stores[6] + '</p>';

			      }
		    }

		
		var stores = new Array(this.stores[firstplace].name, this.stores[firstplace].address, this.stores[firstplace].city, this.stores[firstplace].state, this.stores[firstplace].zip, this.stores[firstplace].country, this.stores[firstplace].phone__space__number, this.stores[firstplace].link, this.stores[firstplace].image_file);


    if(stores[7]) {
      if(stores[8].length > 1) {
          displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' + stores[5] + '<br />Phone: ' + stores[6] + '<br />' + stores[7] + '<br /><div class="result-store-img"  style="height: 150px;"><img  src="' + Generatrix.href('/framework/external/timthumb/timthumb.php?src='+Generatrix.href(stores[8])+'&w=218&h=147').replace(/ /g, "")  + '"/></p>';
      } else {
          displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' + stores[5] + '<br />Phone: ' + stores[6] + '<br />' + stores[7] + '</p>';

      }
    } else {
      if(stores[8].length > 1) {
          displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' +  stores[5] + '<br />Phone: ' + stores[6] + '<br /><div class="result-store-img" style="height: 150px"><img src="' + Generatrix.href('/framework/external/timthumb/timthumb.php?src='+Generatrix.href(stores[8])+'&w=218&h=147').replace(/ /g, "") + '"/></div></p>';
      } else {
          displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' +  stores[5] + '<br />Phone: ' + stores[6] + '</p>';

      }
    }
		
			this.displayZoom( this.stores[firstplace].address + ', ' +  this.stores[firstplace].city + ', ' + this.stores[firstplace].state + ', ' + this.stores[firstplace].country , displayaddress, x);

		}

			KMaps.mapHover ();
		}
		this.results = []
	},
	
	mapHover : function () {
		
		$('.maphover').click( function() {
			var name = this.name;
			var stores = name.split('@$$@');	
			var displayaddress = '';
			if(stores[7] ) {
				if(stores[8].length > 1) {
					displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' + stores[5] + '<br />Phone: ' + stores[6] + '<br />' + stores[7] + '<br /><div class="result-store-img"  style="height: 150px;"><img  src="' + Generatrix.href('/framework/external/timthumb/timthumb.php?src='+Generatrix.href(stores[8])+'&w=218&h=147').replace(/ /g, "")  + '"/></p>';
				} else {
					displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' + stores[5] + '<br />Phone: ' + stores[6] + '<br />' + stores[7] + '</p>';
	
				}
			} else {
				if(stores[8].length > 1) {
					displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' +  stores[5] + '<br />Phone: ' + stores[6] + '<br /><div class="result-store-img" style="height: 150px"><img src="' + Generatrix.href('/framework/external/timthumb/timthumb.php?src='+Generatrix.href(stores[8])+'&w=218&h=147').replace(/ /g, "") + '"/></div></p>';
				} else {
					displayaddress = '<div id="maps_results"><h3>' + stores[0] + '</h3></div><p>' + stores[1] + '<br />' + stores[2] + ', ' + stores[3] + ' ' + stores[4] + '<br />' +  stores[5] + '<br />Phone: ' + stores[6] + '</p>';

				}
			}
			KMaps.displayZoom ( $(this).attr('title') , displayaddress );
		});
	},

	displayZoom: function(address, name, x) {
		var map2= this.map;
		if (this.geocoder) {
			this.geocoder.getLatLng(
				address,
				function(point) {
					if (!point) {
					} else {
						map2.setCenter(point, 4);
						var marker = new GMarker(point);
						map2.setZoom (13);
						map2.addOverlay(marker);
						var htmlString = name;
						if( x == 0 ) {
							GEvent.addListener(marker, 'mouseover',
							function() {
								marker.openInfoWindowHtml(htmlString);							
							});
						}

						if(name != '')
							marker.openInfoWindowHtml(name);
					}
				}
			);
		}
	} 
};
