/*
* Copyright (C) 2009 Joel Sutherland.
* Liscenced under the MIT liscense
* TODO:
* 1. Create API
* 2. Address accesibility automatically
* 3. Make object oriented
*/


/////////////////////////ZOOMAP
/*
* Copyright (C) 2009 Joel Sutherland.
* Liscenced under the MIT liscense
* TODO:
* 1. Create API
* 2. Address accesibility automatically
* 3. Make object oriented
*/

(function($) {
	$.fn.zoommap = function(settings) {
		settings = $.extend({
			zoomDuration: 1000,
			zoomClass: 'zoomable',
			popupSelector: 'div.popup',
			popupCloseSelector: 'a.close',
			bulletWidthOffset: '10px',
			bulletHeightOffset: '10px',
			showReturnLink: true,
                        showCloseLink: true,
			returnId: 'returnlink',
                        closeId: 'closelink',
			returnText: 'Return to Previous Map'
		}, settings);

		$(this).each(function(){
			var map = $(this);
			$(this).data('currentId', '');

			function showMapById(id){
				var region = findRegion(settings.map, id);
				if(region != -1){
					displayMap(region);
				}
			}

			// recursive id find
			function findRegion(root, id){
				if(root.id == id){
					return root;
				}else{
					if(root.maps != undefined){
						for(var i=0; i<root.maps.length; i++){
							var possible = findRegion(root.maps[i], id);
							if(possible != -1)
								return possible;
						}
					}
				}
				return -1;
			}

			// region is a map
			// This gets called every time we zoom
			function displayMap(region){
				//Set Current Region Id
				$(this).data('currentId', region.id);

				//Clear the Map and Set the Background Image
				//alert(region.image);
				map.empty().css({
					backgroundImage: 'url(' + region.image + ')',
					width: settings.width,
					height: settings.height
				});
				//var check = map.css('background-image');

				//Load RegionData
				loadRegionData(region);
			}
			/************************************************************************************/


			//Show Return Link
			function showReturnLink(region){
				map.append('<a href="javascript:void(0);" id="' + settings.returnId + '">' + settings.returnText + '</a>');
				$('#' + settings.returnId).hide().fadeIn().click(function(){
                                   // $('#map_menu').find('.home').removeClass('open');
                                    $('#map_menu').find('.text .open_tag').text('Overview');
					showMapById(region.parent);
				});
			}
                        function showCloseLink(region){
				map.append('<a href="javascript:void(0);" id="' + settings.closeId + '">' + settings.closeText + '</a>');
				$('#' + settings.closeId).hide().fadeIn().click(function(){
                                   // $('#map_menu').find('.home').removeClass('open');
                                    $('#map_menu').find('.text .open_tag').text('Overview');
                                    $('.view_map').click();
					showMapById(region.parent);
				});
			}


			//Load the Bullets
			function loadRegionData(region){
				var url = region.data;
				var width = settings.width;
				var height = settings.height;
				var sub_region;

				map.load(url, {}, function(){

					//Set up each submap as an item to click
					if(region.maps != undefined){
						for(var i=0; i<region.maps.length; i++){
							addZoom(region.maps[i]);
						}
					}

					//place header bullets
					$(this).children('a.header_bullet').each(function(j){
                                            $(this).click(function(){
                                                $('#map_menu .map_menu_header a.text .open_tag').text($(this).attr('title')).parent().show().prev().addClass('open');
                                            })
						var coords = $(this).attr('rel').split('-');
						$(this).css({left: Number(coords[0]), top: Number(coords[1])}).click(function(e){
									sub_region = region.maps[j];
									//alert($('#'+$(this).attr('id')+'_img').attr('id'));
									$('#'+$(this).attr('id')+'_img').load(function(){

											$(this).fadeIn('slow')
												   .animate({
														width: width,
														height: height,
														top: '0px',
														left: '0px'
													}, settings.zoomDuration, '', function(){

														displayMap(sub_region);
													});
										}).attr('src', sub_region.image);
								})
					});

					//place bullets
					$(this).children('a.bullet').each(function(j){
						var coords = $(this).attr('rel').split('-');
						$(this).css({left: addpx(Number(coords[0]) - rempx(settings.bulletWidthOffset)), top: addpx(Number(coords[1]) - rempx(settings.bulletHeightOffset))})
							   .hide()
								.fadeIn('fast')
								.mouseover(function(){
									$('#'+$(this).attr('id')+'-tooltip')
										.css({left:Number(coords[0])+10,top:Number(coords[1])-6})
										.fadeIn('fast');
                                                                                hidePopup();;
                                                                                showPopup($(this).attr('id'));
								})
								.mouseout(function(){
									map.find("div.tooltip").fadeOut("fast");
                                                                        hidePopup();

                                                                      $('#Main-box').animate({
                                                                            left: '640px'
                                                                          },{queue:false,duration:200});
                                                                        
								}).click(function(e){
                                                                    if ($(this).hasClass('popup_flash')) {
                                                                        return true;
                                                                    }
                                                                    window.location.href=$('#'+$(this).attr('id')+'-box a').attr('href');
                                                                });


					});

					//Create Return Link
					if(settings.showReturnLink && region.parent != undefined){
						showReturnLink(region);
					}

                                        //Create Return Link
					if(settings.showCloseLink && region.parent != undefined){
						showCloseLink(region);
					}

					showBottomFrame();
				});
			}
                        function hidePopup(){
                            map.find('.popup').stop(true).animate({
				    left: '880px'
				  }, {queue:false, duration:200}, function() {
				    // Animation complete.
                                    
				  });
                        }
			function showPopup(id, leftbul, topbul){
				//map.find(settings.popupSelector).fadeOut();

				//slide out

				map.find(settings.popupSelector).stop(true).animate({
				    left: '880px'
				  }, {queue:false, duration:200}, function() {
				    // Animation complete.
				  });

				var boxid = '#' + id + '-box';

				//slide in
				$(boxid).stop(true).animate({
				    left: '640px'
				  }, {queue:false, duration:500}, function() {
				    // Animation complete.
				  });

				//$(boxid).fadeIn();
				/*
				$(settings.popupCloseSelector).click(function(){
					//$(this).parent().fadeOut();
					$(this).parent().animate({
					    left: '880px'
					  }, 100, function() {
					    // Animation complete.
					  });
				});
				*/
			}

			//add a clickable image for a region on the current map
			function addZoom(region){
				$('<img />').addClass(settings.zoomClass)
					.attr({
						src: settings.blankImage,
						id: region.id
					}).css({
						position: 'absolute',
						width: region.width,
						height: region.height,
						top: region.top,
						left: region.left
						//cursor: 'pointer'
					}).appendTo(map).click(function(){
						//hide neighboring bullets and zoomables
						/*
						var width = settings.width;
						var height = settings.height;
						if(region.scan){
							width = region.scanwidth;
							height = region.scanheight;
						}
						$(this).siblings().fadeOut();
						$(this).hide()
							   .attr('src', region.image).load(function(){
									$(this).fadeIn('slow')
										   .animate({
												width: width,
												height: height,
												top: '0px',
												left: '0px'
											}, settings.zoomDuration, '', function(){
												displayMap(region);
											});
								});
						*/
					});
			}

			function rempx(string){
				return Number(string.substring(0, (string.length - 2)));
			}

			function addpx(string){
				return string + 'px';
			}

			function showHash(string){
				string = string.replace('#', '');
				showMapById(string);
			}

			function showBottomFrame(){
				showPopup("Main");
				if($('#bottom_frame')){
					$('#bottom_frame').load("/wp-content/themes/newsroom/bottom_frame.php", {}, function(){
						$(this).css({left:0,bottom:"-70px"})
								.animate({
										bottom: '0px',
										left: '0px'
									}, "fast", function(){
										initBottomFrame();
									});
					});
				}
			}

			function initBottomFrame(){
				$('#bottom_frame').children('div.left_col').find('a').each(function(index){
						$(this).click(function(){
							var id = $(this).attr('id');
                                                        if(id == "SHOW ALL"){
                                                            map.find('a.bullet').fadeIn('fast');
                                                        }else{
                                                            map.find('a.bullet:not([status="'+id+'"])').fadeOut('fast');
                                                            map.find('a.bullet[status="'+id+'"]').fadeIn('fast');
                                                        }
						})
					});

				$('#bottom_frame').children('div.right_col').find('a').each(function(index){
						$(this).click(function(){
							var id = $(this).attr('id');
                                                        if(id=="SHOW ALL"){
                                                            map.find('a.bullet').fadeIn('fast');
                                                        }else{
                                                            map.find('a.bullet:not([type="'+id+'"])').fadeOut('fast');
                                                            map.find('a.bullet[type="'+id+'"]').fadeIn('fast');
                                                        }
						})
					});
			}

			function initMenu(){
				$('#map_menu').children('div.map_menu_container').find('a').each(function(index){
						$(this).click(function(){
							var id = $(this).attr('class');
                                                        $('#map_menu .map_menu_header a.text .open_tag').text($(this).attr('title')).parent().show().prev().addClass('open');
							showMapById(id);
						})

					});
			}

			//initialize map
			var hash = self.document.location.hash;
			if(hash.length > 0)
				showHash(hash);
			else{
				displayMap(settings.map);
				initMenu();

			}

			return this;
		});
	}
})(jQuery);



