
var default_lat = 46.34692761055676;
var default_lng = 11.865234375;
var default_radius = 10;
var zoom_level = 4;
var map_width = "100%";
var map_height = "400px";
var special_text = "";
var units = "km";
var limit = "20";
var plugin_url = "http://www.tally-weijl.com/wp-content/plugins/tallymap/";
var autozoom = 4;
var default_domain = ".ch";
var address_format = "town, province postalcode";
var visit_website_text = "View details";
var get_directions_text = "Get Directions";
var location_tab_text = "Location";
var description_tab_text = "Description";
var phone_text = "Phone";
var fax_text = "Fax";
var tags_text = "Tags";
var noresults_text = "No results found.";

// added by cb
var icl_lang = "en";

var map;
var geocoder;

// initalize marker clusterer
var markerCluster = null;
var markers1 = [];
var zoom = 10;
var size = 50;
var styles = [[{
	url: "/wp-content/themes/tallyworld/images/tw-marker/marker-big.png",
	height: 47,
	width: 31,
	opt_anchor: [24, 13],
	opt_textColor: '#FFFFFF'
  },
  {
	url: "/wp-content/themes/tallyworld/images/tw-marker/marker-big.png",
	height: 47,
	width: 31,
	opt_anchor: [24, 11],
	opt_textColor: '#FFFFFF'
  },
  {
	url: "/wp-content/themes/tallyworld/images/tw-marker/marker-big.png",
	height: 47,
	width: 31,
	opt_anchor: [24, 9],
	opt_textColor: '#FFFFFF'
}]];

function codeAddress() {
	geocoder = new GClientGeocoder();
	var d_address = document.getElementById("default_address").value;
	//alert(address);
		 geocoder.getLatLng(d_address, function(latlng) {
			document.getElementById("default_lat").value = latlng.lat();
			document.getElementById("default_lng").value = latlng.lng();
		 });
}

function codeNewAddress() {
	document.new_location_form.submit();

	/*
	if (document.getElementById("store_lat").value != '' && document.getElementById("store_lng").value != '') {
		document.new_location_form.submit();
	}
	else {
		geocoder = new GClientGeocoder();
		var address = '';
		var street = document.getElementById("store_address").value;
		var city = document.getElementById("store_city").value;
		var state = document.getElementById("store_state").value;
		var country = document.getElementById("store_country").value;
		
		if (street) { address += street + ', '; }
		if (city) { address += city + ', '; }
		if (state) { address += state + ', '; }
		address += country;
	
		 geocoder.getLatLng(address, function(latlng) {
			document.getElementById("store_lat").value = latlng.lat();
			document.getElementById("store_lng").value = latlng.lng();
			document.new_location_form.submit();
		 });
	}
	*/
}

function codeChangedAddress() {
	geocoder = new GClientGeocoder();
	var address = '';
	var street = document.getElementById("store_address").value;
	var city = document.getElementById("store_city").value;
	var state = document.getElementById("store_state").value;
	var country = document.getElementById("store_country").value;
	
	if (street) { address += street + ', '; }
	if (city) { address += city + ', '; }
	if (state) { address += state + ', '; }
	address += country;

	geocoder.getLatLng(address, function(latlng) {
		document.getElementById("store_lat").value = latlng.lat();
		document.getElementById("store_lng").value = latlng.lng();
	});
}

function searchLocations(categories) {
 var address = document.getElementById('addressInput').value;
 address = address.replace(/&/gi, " ");
 var country = document.getElementById('countrySelector').value;
 var city = document.getElementById('citySelector').value;
 
 geocoder.getLatLng(address, function(latlng) {
   if (!latlng) {
     latlng = new GLatLng(150,100);
     searchLocationsNear(latlng, address, "search", "unlock", categories, country, city);
   } else {
     searchLocationsNear(latlng, address, "search", "unlock", categories, country, city);
   }
 });
}

function searchLocationsNear(center, homeAddress, source, mapLock, categories, country, city) {
	
	if (document.getElementById('radiusSelect')) {
		if (units == 'mi') {
		  	var radius = parseInt(document.getElementById('radiusSelect').value);
		}
		else if (units == 'km') {
		  	var radius = parseInt(document.getElementById('radiusSelect').value) / 1.609344;
		}
	}
	else {
		if (units == 'mi') {
		  	var radius = parseInt(default_radius);
		}
		else if (units == 'km') {
		  	var radius = parseInt(default_radius) / 1.609344;
		}
	}
 
	if (source == 'auto_all') {
		var searchUrl = encodeURI(plugin_url + 'actions/create-xml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=infinite&namequery=' + homeAddress + '&limit=0&categories=' + categories + '&country=' + country + '&city=' + city + '&icl_lang=' + icl_lang);
	}
	else {
		var searchUrl = encodeURI(plugin_url + 'actions/create-xml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&namequery=' + homeAddress + '&limit=' + limit + '&categories=' + categories + '&country=' + country + '&city=' + city + '&icl_lang=' + icl_lang);
	}
	GDownloadUrl(searchUrl, function(data) {
		var xml = GXml.parse(data);
			
		if(xml.documentElement == null){
			location.reload(true);
		}
		else{
			var markers = xml.documentElement.getElementsByTagName('marker');
			var cities = xml.documentElement.getElementsByTagName('city');
			
			selectbox = document.getElementById('citySelector');
			
			var selectedItem;
			if(cities.length>0){
				selectedItem = selectbox.value;
				markers1 = [];
				markerCluster.clearMarkers();
				selectbox.options.length = 0;
			}
			for (var i = 0; i < cities.length; i++) {
				var selected = false;
				if (selectedItem === cities[i].getAttribute('name')){
					selected = true;
				}
				addOption(selectbox,cities[i].getAttribute('name'),cities[i].getAttribute('name'),selected);
			}
			
			map.enableScrollWheelZoom();
			map.clearOverlays();
			
			if (markers.length == 0) {
				map.setCenter(new GLatLng(default_lat,default_lng), zoom_level);
				return;
			}
			
			// Remove previous items in sidebar
			$("div#addresses ul li").remove();
			
			// Country all ready selected?
			var selectedCountry = $('select#citySelector').val();

			var bounds = new GLatLngBounds();
			for (var i = 0; i < markers.length; i++) {
				var name = markers[i].getAttribute('name');
				var address = markers[i].getAttribute('address');
				var address2 = markers[i].getAttribute('address2');
				var city = markers[i].getAttribute('city');
				var state = markers[i].getAttribute('state');
				var zip = markers[i].getAttribute('zip');
				var country = markers[i].getAttribute('country');
				var distance = parseFloat(markers[i].getAttribute('distance'));
				var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
				var url = document.location + (document.location.toString().indexOf('?') > -1 ? '&' : '?') + 'sid=' + markers[i].getAttribute('id');
				var phone = markers[i].getAttribute('phone');
				var fax = markers[i].getAttribute('fax');
				var special = markers[i].getAttribute('special');
				var category = markers[i].getAttribute('category');
				var tags = markers[i].getAttribute('tags');
				var pic1_big = markers[i].getAttribute('pic1_big');
				var pic1_small = markers[i].getAttribute('pic1_small');
				var pic2_big = markers[i].getAttribute('pic2_big');
				var pic2_small = markers[i].getAttribute('pic2_small');
				var pic3_big = markers[i].getAttribute('pic3_big');
				var pic3_small = markers[i].getAttribute('pic3_small');
				if (markers[i].firstChild) {
					var description = markers[i].firstChild.nodeValue;
				}
				else {
					var description = '';
				}
				
				var markerIndex = i;
				// case if no country got selected, initial page where all bunny get displayed
				if(selectedCountry == 0){
					markerIndex = -1;
				}

				var marker = createMarker(point, name, address, address2, city, state, zip, country, homeAddress, url, phone, fax, special, category, tags, description, markerIndex, pic1_big, pic1_small, pic2_big, pic2_small, pic3_big, pic3_small);
				if(markerIndex != -1){
					// show numbered marker
					map.addOverlay(marker);
					var sidebarEntry = createSidebarEntry(marker, name, address, address2, city, state, zip, country, distance, homeAddress, phone, fax, url, special, category, tags, description, i);
					$("div#addresses ul").append(sidebarEntry);
				}
				else{
					// show clustered marker
					markers1.push(marker);
				}
				bounds.extend(point);
			}
			
			if(selectedCountry == 0){
				markerCluster = new MarkerClusterer(map, markers1, {maxZoom: zoom, gridSize: size, styles: styles[0]});
			}

			// Resize/initalize panel which contains the address results
			// $('#addresses').jScrollPane({width:265, scrollbarWidth:17, scrollbarMargin:10, showArrows:true, arrowSize: 17, wheelSpeed:71});
			
			if (source == "search") {
				map.setCenter(bounds.getCenter(), (map.getBoundsZoomLevel(bounds) - 1));
			}
			else if (mapLock == "unlock") {
				map.setCenter(bounds.getCenter(), autozoom);
			}
		}
	});
}


function stringFilter(s) {
	filteredValues = "emnpxt%";     // Characters stripped out
	var i;
	var returnString = "";
	for (i = 0; i < s.length; i++) {  // Search through string and append to unfiltered values to returnString.
		var c = s.charAt(i);
		if (filteredValues.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function createMarker(point, name, address, address2, city, state, zip, country, homeAddress, url, phone, fax, special, category, tags, description, markerindex, pic1_big, pic1_small, pic2_big, pic2_small, pic3_big, pic3_small) {
	
	// Create our "tiny" marker icon
	var blueIcon = new GIcon(G_DEFAULT_ICON);

	//blueIcon.image = "http://chart.apis.google.com/chart?chst=d_map_pin_icon&chld=bar";
	
	if(markerindex == -1){
		blueIcon.iconSize = new GSize(23, 23);
		blueIcon.shadowSize = new GSize(28, 23);
		blueIcon.shadow = null;
		blueIcon.image         = "/wp-content/themes/tallyworld/images/tw-marker/marker-bunny.png";
		//blueIcon.transparent   = "/wp-content/themes/tallyworld/images/tw-marker/marker-bunny-transparent.png";
		blueIcon.printImage    = "/wp-content/themes/tallyworld/images/tw-marker/JPEG/marker-bunny.jpg";
		blueIcon.mozPrintImage = "/wp-content/themes/tallyworld/images/tw-marker/JPEG/marker-bunny.jpg";
		
		blueIcon.iconAnchor = new GPoint(12,12);
		blueIcon.imageMap = [11,0,12,1,12,2,13,3,14,4,16,5,17,6,18,7,19,8,19,9,19,10,19,11,19,12,18,13,17,14,17,15,17,16,18,17,18,18,18,19,18,20,18,21,16,22,4,22,4,21,4,20,4,19,4,18,6,17,7,16,7,15,7,14,8,13,9,12,10,11,10,10,9,9,7,8,6,7,5,6,5,5,4,4,4,3,4,2,8,1,9,0];

	}
	else{
		blueIcon.iconSize = new GSize(21, 23);
		blueIcon.shadow = null; 
		blueIcon.shadowSize = new GSize(28, 23);
		blueIcon.image         = "/wp-content/themes/tallyworld/images/tw-marker/marker"+(markerindex+1)+".gif";
		// blueIcon.transparent   = null;
		// blueIcon.transparent   = "/wp-content/themes/tallyworld/images/tw-marker/marker-n-transparent.png";
		blueIcon.printImage    = "/wp-content/themes/tallyworld/images/tw-marker/JPEG/marker"+(markerindex+1)+".jpg";
		blueIcon.mozPrintImage = "/wp-content/themes/tallyworld/images/tw-marker/JPEG/marker"+(markerindex+1)+".jpg";
		
		blueIcon.iconAnchor = new GPoint(12,12);
		blueIcon.imageMap = [11,0,12,1,12,2,13,3,14,4,16,5,17,6,18,7,19,8,19,9,19,10,19,11,19,12,18,13,17,14,17,15,17,16,18,17,18,18,18,19,18,20,18,21,16,22,4,22,4,21,4,20,4,19,4,18,6,17,7,16,7,15,7,14,8,13,9,12,10,11,10,10,9,9,7,8,6,7,5,6,5,5,4,4,4,3,4,2,8,1,9,0];

	}
					
	// Set up our GMarkerOptions object
	markerOptions = { icon:blueIcon };
	
	var marker = new GMarker(point, markerOptions);
	
	var mapwidth = Number(stringFilter(map_width));
	var mapheight = Number(stringFilter(map_height));
	
	var maxbubblewidth = Math.round(mapwidth / 1.5);
	var maxbubbleheight = Math.round(mapheight / 2.2);
	
	var fontsize = 12;
	var lineheight = 12;
	
	var titleheight = 3 + Math.floor((name.length + category.length) * fontsize / (maxbubblewidth * 1.5));
	// var titleheight = 2;
	var addressheight = 2;
	if (address2 != '') {
		addressheight += 1;
	}
	if (phone != '' || fax != '') {
		addressheight += 1;
		if (phone != '') {
			addressheight += 1;
		}
		if (fax != '') {
			addressheight += 1;
		}
	}
	var tagsheight = 3;
	var linksheight = 2;
	var totalheight = (titleheight + addressheight + tagsheight + linksheight + 1) * fontsize;
		
	if (totalheight > maxbubbleheight) {
		totalheight = maxbubbleheight;
	}
	
	var html = '<div class="markertext" style="height: ' + totalheight + 'px; overflow-y: auto; overflow-x: hidden;">';
	html += '		<h3 style="margin-top: 0; padding-top: 0; border-top: none;">Tally Weijl</h3>';
	
	if (pic1_small != '') {
		html += '			<img src="/wp-content/uploads/store_pictures/' + pic1_small + '" height="70" width="70" style="float: left; margin: 5px 5px 5px 0;" />';
	}	
	
	html += '		<span>' + address;
					if (address2 != '') {
	html += ', ' + address2;
					}
	html += '		</span><br/>';				
	html += '		<span class="postal-code">'+zip+'</span> <span class="locality">'+city+'</span>, <span class="country-name">'+country+'</span><br />';

	/*
	if (description != '') {
		html += '			<p style="margin: 10px 0;">' + description +'</p>';
						}

					if (phone != '') {
	html += '			<p>' + phone +'</p>';
					}
	*/

					if (url != '') {
	html += '			<a style="color:#DD0059;font-weight:bold;letter-spacing:0;" href="' + url + '" title="' + name + '">' + visit_website_text + '</a>';
					}
	//html += '		</p>';
	
	html += '	</div>';
	
	/*
	if (description != '') {
		var numlines = Math.ceil(description.length / 40);
		var newlines = description.split('<br />').length - 1;
		var totalheight2 = 0;
		
		if (description.indexOf('<img') == -1) {
			totalheight2 = (numlines + newlines + 1) * fontsize;
		}
		else {
			var numberindex = description.indexOf('height=') + 8;
			var numberend = description.indexOf('"', numberindex);
			var imageheight = Number(description.substring(numberindex, numberend));
			
			totalheight2 = ((numlines + newlines - 2) * fontsize) + imageheight;
		}
		
		if (totalheight2 > maxbubbleheight) {
			totalheight2 = maxbubbleheight;
		}
		
		var html2 = '	<div class="markertext" style="height: ' + totalheight2 + 'px; overflow-y: auto; overflow-x: hidden;">' + description + '</div>';
		
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowTabsHtml([new GInfoWindowTab(location_tab_text, html), new GInfoWindowTab(description_tab_text, html2)], {maxWidth: maxbubblewidth});
			
		});
	}

	else {
	*/
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html, {maxWidth: maxbubblewidth});
			
		});
	//}
	return marker;
}

function createSidebarEntry(marker, name, address, address2, city, state, zip, country, distance, homeAddress, phone, fax, url, special, category, tags, description, index) {
  // var li = document.createElement('li');
  var li = '';
  
  // Beginning of result
  var html = '';
  
  // Flagged special
  if (special == 1 && special_text != '') {
  	html += '<div class="special">' + special_text + '</div>';
  }
  
  // Index
  html += '<div class="index">'+(index+1)+'</div>';
  
  // Address
  html += '<div class="vcard"><div class="fn">' + address;
  if (address2 != '') {
  	html += ', ' + address2;
  }
  html += '</div>';
  html +='<span class="postal-code">'+zip+'</span>&nbsp;<span class="locality">'+city+'</span>,&nbsp;<span class="country-name">'+country+'</span>'; 
  
  // Phone
  if (phone != '') {
	html += '<div class="tel">'+phone+'</div>';
  }
  
  //
  if (marker) {
	html += '<abbr class="geo" title="52.686;-2.193"></abbr>';
  }

  // end vcard
  html += '</div>';
  
  var classes = ((index+1) % 2) ? "address odd" : "address even";
  // li.innerHTML = html;
  // li = '<li class="'+ classes +'">' + html + '</li>';
  
  
  return $('<li>')
	.append(html)
	.attr("class", classes)
	.click(function(){
	  GEvent.trigger(marker, 'click');
	  // alert('test');
  });
  
  // li.setAttribute("class", classes);
  // GEvent.addDomListener(li, 'click', function() {
	//GEvent.trigger(marker, 'click');
  // });
  // GEvent.addDomListener(li, 'mouseover', function() {
    //li.style.backgroundColor = '#eee';
  // });
  // GEvent.addDomListener(li, 'mouseout', function() {
    //li.style.backgroundColor = '#fff';
  // });
  // return li;
}

function addOption(selectbox,text,value,selected){
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	if (selected){
		optn.selected = 'selected'
	}
	selectbox.options.add(optn);
}