// Page specific JavaScript

$(function() {

/**
 * @desc Load Galleria
 *
 */
	var host = window.location.hostname;

	// generate profile images on the fly.
	var _target = $("ul.gallery_unstyled").children('li');
	var _photo_cnt;
	$(_target).each(function(i){
		var str = $(this).attr('id');
		var obj = str.toString().split('-'.toString());

		var url = "http://" + host + "/tbn0/tbn/images";
		url += "?src=http://" + host + "/modules/files/gen/";
		url += obj[1].toString() + "/hl:" + generic.params.hl + "/criteria:sale_props";
		url += "&w=264&h=264&q=50";
		url += "&bg=ffffff";

		$(this).image(url, {
			before:function () { 
			},
			after:function () { 
				$(_target).children("img.loading").remove();
				//$(_target).children("img").attr({alt:"Prop "+obj[1].toString()});
				//$(_target).children("img").attr({title:"Prop "+obj[1].toString()});
			}				
		})
		_photo_cnt = ++i;
    })
	
	if(_photo_cnt <= 1) {
		
		origImage = $("ul.gallery_unstyled").children("li").children("img");
		$("#main_image").html(origImage);
		$("#prop-photos-thumbs").hide();
		
		src = $("img", "#main_image").attr("src");
		$("#magnify_photos").attr("href", getImageURL(src));		
		$("#magnify_photos").attr("title", $("#location").text());
	} else {
		// excute Galleria. 
		$('.gallery_unstyled').addClass('gallery'); // adds new class name to maintain degradability
		
		$('ul.gallery').galleria({
			history   : false, // activates the history object for bookmarking, back-button etc.
			clickNext : true, // helper for making the image clickable
			insert    : '#main_image', // the containing selector for our main image
			onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
				
				// fade in the image & caption
				image.css('display','none').fadeIn(1000);
				caption.css('display','none').fadeIn(1000);
				
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				
				
				// fade out inactive thumbnail
				_li.siblings().children('img.selected').fadeTo(500,0.3);
				
				// fade in active thumbnail
				thumb.fadeTo('fast',1).addClass('selected');
				
				// add a title for the clickable image
				image.attr('title','次の写真 >>');
				
				// get the URL of an original (non-resized) image from its thumbnail URL.
				src = getImageURL(image.attr("src"));
				$("#magnify_photos").attr("href", src);
				$("#magnify_photos").attr("title", $("#location").text());
			},
			onThumb : function(thumb) { // thumbnail effects goes here
				
				// fetch the thumbnail container
				var _li = thumb.parents('li');
				
				// if thumbnail is active, fade all the way.
				var _fadeTo = _li.is('.active') ? '1' : '0.3';
				
				// fade in the thumbnail when finnished loading
				thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
				
				// hover effects
				thumb.hover(
					function() { thumb.fadeTo('fast',1); },
					
					// don't fade out if the parent is active
					function() { _li.not('.active').children('img').fadeTo('fast',0.3); }
				)
			}
		})
	}
	
	// get the URL of an original (non-resized) image from its thumbnail URL.
    function getImageURL(url){
        var regObj = new RegExp(/http:\/\/[a-z0-9\.\-\_\~]+\/modules\/([a-z0-9\/\.\:\_]+)/gi);
        return url.match(regObj);
    }	
/**
 * @desc Get the json data for the selects.
 *
 */
	$.getJSON("/modules/el_schools/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormElSchoolId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#el_school").append(data);
		}
	);

	$.getJSON("/modules/jh_schools/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormJhSchoolId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#jh_school").append(data);
		}
	);

	$.getJSON("/modules/bldg_structures/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormBldgStructureId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#bldg_structure").append(data);
		}
	);

	$.getJSON("/modules/land_certificates/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormLandCertificateId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#land_certificate").append(data);
		}
	);

	$.getJSON("/modules/mngmnt_types/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormMngmntTypeId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#mngmnt_type").append(data);
		}
	);

	$.getJSON("/modules/urban_plannings/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormUrbanPlanningId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#urban_planning").append(data);
		}
	);

	$.getJSON("/modules/land_types/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormLandTypeId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#land_type").append(data);
		}
	);

	$.getJSON("/modules/land_uses/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormLandUseId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#land_use").append(data);
		}
	);

	$.getJSON("/modules/land_forms/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormLandFormId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#land_form").append(data);
		}
	);

	$.getJSON("/modules/move_in_dates/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormMoveInDateId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#move_in_date").append(data);
		}
	);
	
	$.getJSON("/modules/type_of_purchases/gen", {
		'hl': generic.params.hl,
		'sel': $("#FormTypeOfPurchaseId").val()
		},
		function(data, status) {
			if(data.length > 0) $("#type_of_purchase").append(data);
		}
	)

/**
 * @desc Load Google Maps
 *
 */
	var apikey = 'ABQIAAAA7TWIqiwj1mKi9xrVruRP-RSFNoZaEohrif3PXbFqDEaOoQuvQRQsOtzjBI6YOCeLsuaBuuExvpFS8Q';

	loadScript();	   
		   
	function loadScript() {
		var script = document.createElement("script");
		script.type = "text/javascript";
		script.src = 'http://maps.google.com/maps?file=api&v=2.x&key='+apikey+'&async=2&callback=loadMap';
		document.body.appendChild(script);
	};		   
		   
	loadMap = function() {
		if (GBrowserIsCompatible()) {
			// a location to call
			var address = '島根県' + (document.getElementById("location")).innerHTML;
			
			// generate GClientGeocoder
			var clientGeocoder = new GClientGeocoder();
	
			if (clientGeocoder) {
				clientGeocoder.getLatLng(
					address,
						function(point) {
						if (point) {
							//call getLatLng
							clientGeocoder.getLatLng(address, showMap);
						} else {
							alert('所在地が Googleマップの形式に適合していないため、地図が表示されていません。');
						}
					}
				);
			}
		}
	}
	
	function showMap(point) {
	
		// generate GMap2
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(point, 16);
		
		// maker
		var marker = new GMarker(point)
		map.addOverlay(marker);
		
		// Map：map.setMapType(G_NORMAL_MAP);
		// Satelite and Map：map.setMapType(G_SATELLITE_MAP);
		// Hybrid and Map：map.setMapType(G_HYBRID_TYPE);
		map.setMapType(G_NORMAL_MAP);
	
		// add control to Hybrid map
		map.addControl(new GMapTypeControl()); 
			
		// add a bubble
		//map.openInfoWindowHtml(point, "<b></b>");
		//marker.html = (document.getElementById("location")).innerHTML;
		
		GEvent.addListener(marker, "click", 
		function() {
			//marker.openInfoWindowHtml(marker.html);
		});
	
		// add scale control
		map.addControl(new GSmallMapControl());
	}
		   
	/*if (GBrowserIsCompatible()){
		loadMap();
	}
	$(window).unload(function(){
		GUnload();
	})*/
});
