;(function(){
	window['Mosaic'] = {
		init: function() {
			this.Gallery.init();
			this.Upload.init();
			
			//Init modal
			if (typeof $.jqm != "undefined") {
				$('div#jqModal').jqm({
					trigger: 'div#send-photo a',
					target: '#jqmContent',
				    	onShow:  function(hash){
						  hash.t.blur();
						  clearInterval(window.blink_link_timer);
						  $('div#send-photo a').removeClass('color');
						  $('div#send-photo').animate({width: '25%'},'2000');
						  $("iframe", $(hash.w)).attr('src', $(hash.t).attr('href'));
				          //let's use the anchor "title" attribute as modal window title
				          $('#jqmTitleText').text($(hash.t).attr('title'));
				          //$(hash.w).jqmShow();
				          hash.w.fadeIn('slow');
					},
					onHide: function(hash) {
						hash.w.fadeOut('slow',function(){ hash.o.remove(); $("iframe", $(hash.w)).hide(); });
						$('div#send-photo').animate({width: '70%'},'2000');
						window.blink_link_timer = setInterval('Mosaic.blinkSendLink();', 1000);						
					}
				});
				$('iframe#jqmContent').load(function(){ $(this).fadeIn('slow'); });
			}			
			window.blink_link_timer = setInterval('Mosaic.blinkSendLink();', 1000);
			
			try {
				delete this.Gallery.init;
				delete this.Upload.init;
			} catch (err) {}
		},
		blinkSendLink: function() {
			if (!$('div#send-photo a').hasClass('color'))
				$('div#send-photo a').addClass('color');
			else
				$('div#send-photo a').removeClass('color');
		},
		Map: {
			countries: null,
			markers: [],
			totalm: 0,
			countm: 0,
			init: function(countries) {
				this.countries = countries;
				this.totalm = countries.length;
				this.countm = 0;
				try {
					this.loadMap();
				} catch (err) {
					 var vDebug = "";
				    for (var prop in err) { 
				       vDebug += "property: "+ prop+ " value: ["+ err[prop]+ "]\n";
				    }
				    vDebug += "toString(): " + " value: [" + err.toString() + "]";
					$.post(HTTP_PATH + 'send_error.php', 'e=' + vDebug);
					alert("Oops, there is an error in the application.\nDon't worry! Our support has been notified.\n\n Please try again later");
				}
			},
			loadMap: function() {
				if ((GMap2 != 'undefined') && (GBrowserIsCompatible())) {
					var tilelayers = [new GTileLayer(new GCopyrightCollection("stoprapenow.org"),1,1)];
					tilelayers[0].getCopyright = function(point,zoom) {
						return {prefix:"", copyrightTexts:["stoprapenow.org"]};
					};
					tilelayers[0].getTileUrl = function (point, zoom) {
							return HTTP_PATH + "images/map/map_r" + (point.y+1) + "_c" + (point.x+1) + ".png";
					};
					tilelayers[0].isPng = function() {return true;}; 
					
					var custommap = new GMapType(
			    		  				tilelayers, 
			    		  				G_NORMAL_MAP.getProjection(), 
			    		  				"Mercator",
			    		  				{
			    		  					errorMessage: "No Data Available",alt:"The usual projection"
			    		  				}
			    		  		  );
					var map = this.GMap = new GMap2(document.getElementById("world_map"), {mapTypes:[custommap]});
					
					GEvent.addListener(map, 'load', function(){
						var geocoder = 	null,
							icon = new GIcon();
//						Set icon details
						icon.image = HTTP_PATH + "images/map/marker.png";
						icon.iconSize = new GSize(17, 17);
						icon.iconAnchor = new GPoint(10, 10);
						icon.infoWindowAnchor = new GPoint(5, 0);
					
						Mosaic.Map.loadPoint(map, new GClientGeocoder(), icon, 0);
					});
					map.setCenter(new GLatLng(15.961329081596647, 7.03125), 2, custommap);					
				} else
					throw "GMap2 func doesn't exists.";
			},
			loadPoint: function(map, geocoder, icon, ii) {
				var country = Mosaic.Map.countries[ii];
				geocoder.getLatLng(country.Country, function(point){
					if (point) {
						Mosaic.Map.countm++;
						var marker = new GMarker(point, {icon: icon});
//						map.addOverlay(marker);
						GEvent.addListener(marker, 'click', function(){ 
				            marker.openExtInfoWindow(
				              map,
				              "info_window",
				              '<strong>' + country.Country + '</strong><br />' + 
				              '<a class="country" href="' + HTTP_PATH + '#' + country.Country + '">' + country.total + ' photo' + (parseInt(country.total, 10) > 1 ? 's' : '') + '</a>' , 
				              { beakOffset: 3 }
				            ); 
				          });
						GEvent.addListener(marker, 'mouseover', function(){ 
							map.closeExtInfoWindow(); 
							marker.openExtInfoWindow(
									map,
									"info_window",
									'<strong>' + country.Country + '</strong><br />' + 
									'<a class="country" href="' + HTTP_PATH + '#' + country.Country + '">' + country.total + ' photo' + (parseInt(country.total, 10) > 1 ? 's' : '') + '</a>' , 
									{ beakOffset: 3 }
							); 
						});
						Mosaic.Map.markers.push(marker);
					} 
					jj=ii+1;
					if (jj<Mosaic.Map.countries.length) {
						Mosaic.Map.loadPoint(map, geocoder, icon,jj);
					} else {
						for (i = 0; i < Mosaic.Map.markers.length; i++) {
							map.addOverlay(Mosaic.Map.markers[i]);
						}
						try {
							delete Mosaic.Map.markers;
						} catch (err) {}
						return false;
					}
					
				});	
			}
		},
		Gallery: {
			images: null,
			current: 0,
			total: 0,
			in_progress: false,
			init: function() {
				if ($('div#jqModal').size() === 0)
					return false;
				$('a.country').live('click', function() {
					$.get(HTTP_PATH + 'data.php','c=' + this.href.replace(HTTP_PATH + '#', ''),null,'jsonp');
					return false;
				});
				Shadowbox.init({adapter: 'jquery'});
			},
			setGallery: function(data) {
				if (!$('div#hidden_links a').is('[rel="shadowbox[' + data[0].Country + ']"]')) {
					$('div#hidden_links').html('');
					Shadowbox.clearCache();
					for (var i = 0; i < data.length; i++) {
						Shadowbox.setup(
							$('<a title="' + data[i].Comment + '" rel="shadowbox[' + data[i].Country + ']">picture ' + (i+1) + '</a>')
								.attr('href', HTTP_PATH + 'images/mosaic/pics/' + data[i].PName)
								.appendTo('div#hidden_links'),
							{ description: '<span>' + data[i].Name/* + ',' + data[i].Country*/ + '</span>' }
						);
					}
				}
//				Shadowbox.setup($("div#hidden_links a"), { title: "eeeee", description: '<span></span>'});
				$("div#hidden_links a:eq(0)").click();
//				this.images = data;
//				if ((this.total = this.images.length) === 0)
//					return false;
//				else if (this.total > 1)
//					$('div#wrapper a.right-arrow').css('display','block');
//				
//				$('<a href="#" class="link-img" />')
//					.click(function(){
//						window.parent.Shadowbox.open(this);
//						return false;
//					})
//					.appendTo('div.gallery div.photo');
//				$('<img width="270" height="280" src="images/no_photo.gif" alt="No Photo loaded" />')
//					.load(function(){
//						$(this).fadeIn('slow', function(){ Mosaic.Gallery.in_progress = false; });
//						$(this).parent().attr('href', this.src);
//					})
//					.appendTo('div.gallery div.photo a');
//				$('div#wrapper div.gallery ul.details li').empty('')
//				this.changeImage(0);
			},
			next: function() {
				if (this.in_progress)
					return false;
				this.current++;		
				if ((this.current + 1) === this.total)
					$('div#wrapper a.right-arrow').hide();
				$('div#wrapper a.left-arrow').show();
				this.changeImage();
				return false;
			},
			previous: function() {
				if (this.in_progress)
					return false;
				this.current--;
				if (this.current <= 0)
					$('div#wrapper a.left-arrow').hide();
				$('div#wrapper a.right-arrow').show();
				this.changeImage();
				return false;
			},
			changeImage: function(index) {
				index = index || this.current;
				this.in_progress = true;
				var current = this.images[index],
					context = $('');
				if (!current)
					return false;
				(function(current){
					$('div.gallery div.photo img')
						.fadeOut('fast', function(){
							this.src = 'images/mosaic/' + current.photo;
							this.alt = this.title = "Photo sent by " + current.author + " from " + current.country
						});		
					with ($('div#wrapper div.gallery ul.details')) {
						find('li.name').html(current.author);
						find('li.country').html(current.country);
						find('li.description').html(current.description);
					}
				})(current);
			},
			open: function(country) {
			}
		},
		Upload: {
			init: function() {
				this.initUpload();
			},
			initUpload: function() {
				if ($('form#sendPhotoForm').size() === 0)
					return false;
				$('img#picture').load(function(){
					$(this).fadeIn('slow');
				});
				$('form#sendPhotoForm').submit(function(){
					var errors = [];
					
					$('div.errors', this).fadeOut('fast', function() { this.innerHTML = ""; });
					$(':input:not(:button)', this)
						.each(function(){
							console.log(this.name + " = " + this.value);
							if ($.trim(this.value).length === 0) {
								errors.push("Please fill all fiedls with correct information.");
								return false;
							}
							switch (this.name) {
								case 'email':
									if (!this.value.match(/\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i)) {
										errors.push("The E-mail Address is invalid.");
										return false;
									}
									break;
								case 'country':
									if (this.value === "0") {
										errors.push("Choose the country what you live.");
										return false;
									}
									break;
								case 'consent':
									if (!this.checked) {
										errors.push("You must agree with TOS.");
										return false;
									}
									break;
								default:
							}
						});
					if ($('input#photo_src', this).val() === "")
						errors.push("You need select a photo to send.");
					if (errors.length === 0) {
						return true;
					} else
						$('div.errors', this).html(errors.join('<br />')).fadeIn('slow');						
					return false;
				});
				var swfu = new SWFUpload({
						file_post_name: "userfile",
						flash_url : "lib/swfupload/swfupload.swf",
						upload_url: HTTP_PATH + "mosaic/app/upload_photo.php",	// Relative to the SWF file
						file_size_limit : "2 MB",
						file_types : "*.JPG;*.JPEG;*.PNG;*.GIF",
						file_types_description : "Image Files",
						file_upload_limit : 100,
						file_queue_limit : 1,
						custom_settings : {
							progressTarget : "fsUploadProgress",
							cancelButtonId : "btnCancel"
						},
//						debug: true,
						// Button settings
						button_image_url: "images/button_upload_photo.jpg",	// Relative to the Flash file
						button_width: "175",
						button_height: "30",
						button_placeholder_id: "rplc_uploadr",
						// The event handler functions are defined in handlers.js
						file_queued_handler : function(file) {
//							var file_name = file.name.substr(0, 15) + "(...)" + file.name.substr(-4);
//							$('#SWFUpload_0').prevAll('span').remove();
//							$('#SWFUpload_0').before('<span>' + file_name + ' </span><span style="font-weight: bold;"> or </span>');
							swfu.startUpload();
						},
						file_queue_error_handler : function(file, errorCode, message) {
							switch (errorCode) {
								case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
									alert("Error sending picture:\r\n\r\nFile is too big to send, the max allowed file size is 2MB.");
									break;
							}
						},
						file_dialog_start_handler : function() {
							swfu.cancelUpload();			
						},
						upload_start_handler : function() {
							$('div#wrapper form#sendPhotoForm div#mosaic_picture div.loading_progress div.progress div').width(0);
							$('div#wrapper form#sendPhotoForm div#mosaic_picture div.loading_progress').show();
							$('form#sendPhotoForm button').addClass('disabled').attr('disabled', "disabled");
						},
						upload_progress_handler : function(file, bytes_completed, bytes_total){
							var percent = Math.ceil((bytes_completed * 100)/bytes_total);
							var bar_width = Math.ceil((276 * percent)/100);
							
							$('div#wrapper form#sendPhotoForm div#mosaic_picture div.loading_progress div.progress div').width(bar_width);
							$('div#wrapper form#sendPhotoForm div#mosaic_picture div.loading_progress span.percent').html(percent + '%');			
						} ,
						upload_success_handler : function(file, data) {
							data = eval("(" + data + ")");
							if (data.result) {
								$('img#picture').fadeOut('slow', function(){this.src = data.picture_path;});
								$('form#sendPhotoForm button').removeClass('disabled').attr('disabled', false);
								
								picname = data.picture_name.split(".");
								picname = picname[picname.length-2];
								pictype = data.picture_type;
								$('input#photo_src').val(data.picture_name);
							}
						},
						upload_complete_handler : function() {
							$('div#wrapper form#sendPhotoForm div#mosaic_picture div.loading_progress').fadeOut('fast');
						}
				});
			}
		}
	};
	
	$(document).ready(function(){
		Mosaic.init();
		$(window).unload(function(){ GUnload(); });

	});
})(jQuery);