$(function(){
	if($('#embassy-table').length && $('#filter').length) {
		var IncrementalSearchableTable = new IncrementalSearch('embassy-table', 'filter', 2);
	}
});

(function($){
	$.fn.embassy = function(options, param){
		var defaults = {
			country: '#country',
			info: '.embassy-info',
			map: '.embassy-map',
			embassyType: 'ru',
			related: '.embassy-related',
			resultLinks: '#result-links'
		};
			
		newOptions = $.extend(defaults, options);
		
		return this.each(function(){
			var embassy = new Embassy(this, newOptions);
		});
	}
	
	var Embassy = function(el, options){
		var el = $(el);
		var self = this;
		
		this.IE = $.browser.msie && $.browser.versionX < 8;
		this.GZoom = new Array(2, 4, 6, 10, 12, 13, 16, 16, 17);
		
		this.init = function() {
			var code = document.location.toString().match(/embassies\/([A-Z]{2})/)[1];
			var city = null;
			
            this.selectCountry(code, city, true);
            this.setResultLinks(code);
		}
		
		this.selectCountry = function(code, city, leaveHash) {
			var o = options;
				
            this.cityGroup = {};
            
            // init map first
            this.initMap();
            
            self.initTabs(o.embassyData.info, code, city);
        
            if (o.related) {
                var related = $(o.related);
                if (o.existsRelated) {
                    var visibility = 'visible';
                } else {
                    var visibility = 'hidden';
                }
                
                related.css({
                    visibility: visibility
                });
            }
            
            if(!leaveHash) {
                this.setHash(code, city);
            }
            
            //this.setResultLinks(code, city);
            //this.setRelated(code);
		}
		
		this.initTabs = function(info, countryCode, cityHash) {
			var o = options;
			
			infoTabs = el.find(o.info).eq(0);
			infoTabs.tabs('destroy');
			infoTabs.empty();
			
			var nav = '<ul>', content = '';
			for(var i in info) {
				var cityInfo = info[i];
				
				nav += '<li><a href="#' + (this.IE ? 'embassy-' : '') + countryCode + '-' + (o.embassyType == 'ru' ? i : o.cityHashes[cityInfo.city]) + '">' + cityInfo.city + '</a></li>';
				
				content += '<div id="' + (this.IE ? 'embassy-' : '') + countryCode + '-' + (o.embassyType == 'ru' ? i : o.cityHashes[cityInfo.city]) + '">';
				
				for(var j in cityInfo.service) {
					var service = cityInfo.service[j];
					
					content += '<div class="service">';
					
					var type;
					if(service.name) {
						type = service.name;
					} else {
						type = s('embassy-office-' + service.type);
					}
					
					if(type) {
						content += '<h3 class="title">'+type+'</h3>';
					}
					
					content += '<div class="sections">';
					
					if (service.comment) {
						content += '<div class="section comment">' + service.comment + '</div>';
					}
					
					if (service.href) {
						var text = service.href.replace(/^http:\/\//, '').replace(/\/.*$/, '');
						content += '<div class="section link"><a href="' + service.href + '">' + text + '</a></div>';
					}
					
					content += '<div class="section address">' + service.address + '</div>';
					
					if (service.phone.length) {
						content += '<div class="section phones"><div class="phones-title">' + (service.phone.length - 1 ?  s('Phones') : s('Phone')) + '</div>';
						
						var prevCode = '';
						for (var k in service.phone) {
							var phone = service.phone[k];
							
							var code = '+' + phone.code + ' ' + phone.city;
							content += '<div class="phone">' + (code == prevCode ? '<span class="copiable">' + code + '</span>' : code) +	' ' + phone.number +
							(phone.comment ? ' <span class="comment">(' + phone.comment + ')</span>' : '') + '</div>';
							prevCode = code;
						}
						
						content += '</div>';
					}
					
					if (service.fax.length) {
						content += '<div class="section phones"><div class="phones-title">' + (service.fax.length - 1 ? s('Faxes') : s('Fax')) + '</div>';
						
						var prevCode = '';
						for (var k in service.fax) {
							var phone = service.fax[k];
							
							var code = '+' + phone.code + ' ' + phone.city;
							content += '<div class="phone">' + (code == prevCode ? '<span class="copiable">' + code + '</span>' : code) +	' ' + phone.number +
							(phone.comment ? ' <span class="comment">(' + phone.comment + ')</span>' : '') + '</div>';
							prevCode = code;
						}
						
						content += '</div>';
					}
					
					if (service.email.length) {
						content += '<div class="section emails"><div class="emails-title">' + s('E-mail') + '</div>';
						
						for (var k in service.email) {
							var email = service.email[k];
							
							content +=	'<div class="email">' + 
											'<a href="mailto:' + email.mail + '">' + email.mail + '</a>' + 
											(email.comment ? ' <span class="comment">(' + email.comment + ')</span>' : '') + 
										'</div>';
						}
						
						content += '</div>';
					}
					
					content += '</div>';
					
					content += '</div>';
					
					if(service.address) {						
						if (o.embassyType == 'ru') {
							if (i == 0 && j == cityInfo.service.length - 1) {
								var isMapShown = true;
							} else {
								var isMapShown = false;
							}
						
							var address = service.address;
						} else {
							if (((cityHash && o.cityHashes && cityHash == o.cityHashes[cityInfo.city]) || (!cityHash && i == 0)) && j == cityInfo.service.length - 1) {
								var isMapShown = true;
							} else {
								var isMapShown = false;
							}
							
							var address = cityInfo.city + ', ' + service.address;
						}
						// adding to map
                        //this.showMap();
						this.addAddressToMap(address, i, isMapShown);
					}
				}
				
				content += '</div>';
			}
			nav += '</ul>';
			
			infoTabs.html(nav + content);
			infoTabs.tabs({
				select: function(event, ui) {
					self.updateCityMap(ui.index);
				}
			});
		}
		
		this.initMap = function() {
			var o = options;
			
			this.hideMap();
			
			if (!this.map) {
                var latlng = new google.maps.LatLng(55.7, 36.9);
                var mapOptions = {
                    zoom: 19,
                    center: latlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                this.map = new google.maps.Map($(o.map)[0], mapOptions);
                this.infoWindow = new google.maps.InfoWindow({
                    content: 'test info window'
                });
                this.markers = [];

			} else {
				if (this.markers)
                    for (var i = 0; i != this.markers.length; i++)
                        this.markers[i].setMap(null);
                if (this.infoWindow)
                    this.infoWindow.setContent('');
			}
		}
		
		this.addAddressToMap = function(address, cityIndex, isMapShown) {
			var o = options;
			var map = this.map;
            var infoWindow = this.infoWindow;
            var markers = this.markers;

            var geocoder = new google.maps.Geocoder();
            geocoder.geocode(   
                {'address': address, 'language': o.localeLanguage == 'ru' ? 'ru' : 'en'}, 
                function(results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        var marker =  new google.maps.Marker({
                            position: results[0].geometry.location, 
                            map: map
                            });
                        markers.push(marker);
                        google.maps.event.addListener(marker, 'click', function(){
                           infoWindow.setContent(results[0].formatted_address);
                           infoWindow.open(map, marker);
                        });
                    
                        if (!self.cityGroup[cityIndex]) {
                            self.cityGroup[cityIndex] = [];
                        }
                        
                        self.cityGroup[cityIndex].push(results[0].geometry);
                        
                        if (isMapShown) {
                            self.updateCityMap(cityIndex);
                            self.showMap();
                        }
                    }
                }
            );
		}
		
		this.updateCityMap = function(cityIndex) {
			
			if (this.cityGroup[cityIndex]) {
                var latLngBounds = this.cityGroup[cityIndex][0].viewport;

                for (var i = 1; i != this.cityGroup[cityIndex].length; i++) 
                    latLngBounds = latLngBounds.union(this.cityGroup[cityIndex][i].viewport);

                this.map.panToBounds(latLngBounds);
                this.map.fitBounds(latLngBounds);
				this.showMap();
			} else {
				this.hideMap();
			}

        }
		
		this.setHash = function(countryCode, cityHash) {
			//document.location.hash = '#' + countryCode + (cityHash ? '-' + cityHash : '');
		}
		
		this.setResultLinks = function(countryCode) {
			var o = options;
			var resultLinks = $(o.resultLinks);
			var url = document.location.toString().replace(/\/[A-Z]{2}\/?/, '/' + countryCode);
            resultLinks.find('#result-link-url').val(url);
            resultLinks.find('#result-link-code').val('<a href="' + url + '">' + titleText + '</a>');
        }
		
/*		this.setRelated = function(code) {
			var o = options;
			
			if (o.related && $(o.related).length) {
				
				var linkText = '';
				var link = $(o.related).find('div[class$=link] a');
				
				if (o.embassyType == 'ru') {
					linkText = s('embassy-of') + ' ';
					for (var i in o.countryList) {
						var country = o.countryList[i];
						if (country.code == code) {
							linkText += country.genitive;
							break;
						}
					}
					linkText += ' ' + s('in-russia');
				
					link.attr('href', location.toString().replace(/#.*$/, '').replace('ru_embassy', 'embassy'));
				} else {
					linkText += s('Embassy') + ' ' + s('of russia') + ' ';
					
					for (var i in o.countryList) {
						var country = o.countryList[i];
						if (country.code == code) {
							linkText += (country.prep ? country.prep : s('in')) + ' ' + country.prepositional;
							break;
						}
					}
					
					link.attr('href', location.toString().replace(/#.*$/, '').replace('embassy', 'ru_embassy'));
				}
				link.text(linkText);
			}
		}
*/		
		this.showMap = function() {
			var o = options;
			
			$(o.map).css({
				visibility: 'visible'
			});
		}
		
		this.hideMap = function() {
			var o = options;
			
			$(o.map).css({
				visibility: ''
			});
		}
		
		this.init();
	}
})(jQuery);
