// -----------------------------------------------------------------------------------
//
//	Lightbox v2.02
//	by Lokesh Dhakar - http://www.huddletogether.com
//	3/31/06
//
//	For more information on this script, visit:
//	http://huddletogether.com/projects/lightbox2/
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//
//	Credit also due to those who have helped, inspired, and made their code available to the public.
//	Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.org), Thomas Fuchs(mir.aculo.us), and others.
//
//
// -----------------------------------------------------------------------------------
//
//  edited by nao-pon - http://hypweb.net/
//  $Id: lightbox.js,v 1.18 2009/10/01 23:37:22 nao-pon Exp $
//
// -----------------------------------------------------------------------------------

if (!Lightbox) {

//
//	Configuration
//

var resizeSpeed = 9;	// controls the speed of the image resizing (1=slowest and 10=fastest)

var borderSize = 10;	//if you adjust the padding in the CSS, you will need to update this variable

var lightbox_timeout = 10000; // Timeout for load a image.(ms)
// -----------------------------------------------------------------------------------

//
//	Global Variables
//
var imageArray = new Array;
var activeImage;

if(resizeSpeed > 10){ resizeSpeed = 10;}
if(resizeSpeed < 1){ resizeSpeed = 1;}
resizeDuration = (11 - resizeSpeed) * 0.15;

// -----------------------------------------------------------------------------------

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth;
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src;
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href;
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

// -----------------------------------------------------------------------------------

//
//	Extending built-in Array object
//	- array.removeDuplicates()
//	- array.empty()
//
Array.prototype.removeDuplicates = function () {
	for(i = 1; i < this.length; i++){
		if(this[i][0] == this[i-1][0]){
			this.splice(i,1);
		}
	}
}

// -----------------------------------------------------------------------------------

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

// -----------------------------------------------------------------------------------

var Lightbox = Class.create();

Lightbox.prototype = {

	initialize: function() {
		if (!document.getElementsByTagName){ return; }
		
		this.timer = null;
		this.imgPreloader = null;
		this.myAjax = null;
		
		//regexp my host name
		this.myhost = location.protocol+"//"+location.host;
		var reg = /([\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:\\])/g;
		//for NN4.x bug
		this.myhost = this.myhost.replace(reg, "##__BACK_SLASH__##$1").replace(/##__BACK_SLASH__##/g, '\\');
		this.myhost = new RegExp("^"+this.myhost,"i");
		
		var objBody = document.getElementsByTagName('body')[0];
		var r = document.evaluate('descendant::a[@type="img"][@href!=""]', objBody, null, 7, null);
		for (var i=0; i<r.snapshotLength; i++){
			var anchor = r.snapshotItem(i);
			anchor.setAttribute("rel", "lightbox[stack]");
			anchor.onclick = function () {myLightbox.start(this); return false;}
		}
		
		if ($('lightbox')) {
			Element.remove($('lightbox'));
		}
		
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay');
		objOverlay.style.display = 'none';
		objOverlay.onclick = function() { myLightbox.end(); return false; }
		objBody.appendChild(objOverlay);

		var objLightbox = document.createElement("div");
		objLightbox.setAttribute('id','lightbox');
		objLightbox.style.display = 'none';
		objBody.appendChild(objLightbox);

		var objOuterImageContainer = document.createElement("div");
		objOuterImageContainer.setAttribute('id','outerImageContainer');
		objLightbox.appendChild(objOuterImageContainer);

		var objImageContainer = document.createElement("div");
		objImageContainer.setAttribute('id','imageContainer');
		objOuterImageContainer.appendChild(objImageContainer);

		var objLightboxImage = document.createElement("img");
		objLightboxImage.setAttribute('id','lightboxImage');
		objImageContainer.appendChild(objLightboxImage);

		var objHoverNav = document.createElement("div");
		objHoverNav.setAttribute('id','hoverNav');
		objImageContainer.appendChild(objHoverNav);

		var objPrevLink = document.createElement("a");
		objPrevLink.setAttribute('id','prevLink');
		objPrevLink.setAttribute('href','#');
		objHoverNav.appendChild(objPrevLink);

		var objNextLink = document.createElement("a");
		objNextLink.setAttribute('id','nextLink');
		objNextLink.setAttribute('href','#');
		objHoverNav.appendChild(objNextLink);

		var objLoading = document.createElement("div");
		objLoading.setAttribute('id','loading');
		objImageContainer.appendChild(objLoading);

		var objLoadingLink = document.createElement("a");
		objLoadingLink.setAttribute('id','loadingLink');
		objLoadingLink.setAttribute('href','#');
		objLoadingLink.onclick = function() { myLightbox.end(); return false; }
		objLoading.appendChild(objLoadingLink);

		var objLoadingImage = document.createElement("img");
		objLoadingImage.setAttribute('src', wikihelper_root_url + '/skin/loader.php?src=loading.gif');
		objLoadingLink.appendChild(objLoadingImage);

		var objImageDataContainer = document.createElement("div");
		objImageDataContainer.setAttribute('id','imageDataContainer');
		objImageDataContainer.className = 'clearfix';
		objLightbox.appendChild(objImageDataContainer);

		var objImageData = document.createElement("div");
		objImageData.setAttribute('id','imageData');
		objImageDataContainer.appendChild(objImageData);

		var objBottomNav = document.createElement("div");
		objBottomNav.setAttribute('id','bottomNav');
		objImageData.appendChild(objBottomNav);

		var objBottomNavCloseLink = document.createElement("a");
		objBottomNavCloseLink.setAttribute('id','bottomNavClose');
		objBottomNavCloseLink.setAttribute('href','#');
		objBottomNavCloseLink.onclick = function() { myLightbox.end(); return false; }
		objBottomNavCloseLink.innerHTML = '&#38281;&#12376;&#12427;';
		objBottomNavCloseLink.setAttribute('title',objBottomNavCloseLink.innerHTML);
		objBottomNav.appendChild(objBottomNavCloseLink);

		var objBottomNavOriginalLinkNew = document.createElement("a");
		objBottomNavOriginalLinkNew.setAttribute('id','originalLinkNew');
		objBottomNavOriginalLinkNew.setAttribute('href','#');
		objBottomNavOriginalLinkNew.onclick = function() { myLightbox.viewOriginalNew(); return false; };
		objBottomNavOriginalLinkNew.style.display = 'none';
		objBottomNavOriginalLinkNew.innerHTML = '&#26032;&#12375;&#12356;&#12454;&#12452;&#12531;&#12489;&#12454;&#12391;&#38283;&#12367;';
		objBottomNavOriginalLinkNew.setAttribute('title',objBottomNavOriginalLinkNew.innerHTML);
		objBottomNav.appendChild(objBottomNavOriginalLinkNew);

		var objBottomNavOriginalLink = document.createElement("a");
		objBottomNavOriginalLink.setAttribute('id','originalLink');
		objBottomNavOriginalLink.setAttribute('href','#');
		objBottomNavOriginalLink.onclick = function() { myLightbox.viewOriginal(); return false; };
		objBottomNavOriginalLink.style.display = 'none';
		objBottomNavOriginalLink.innerHTML = '&#21516;&#12376;&#12454;&#12452;&#12531;&#12489;&#12454;&#12391;&#12458;&#12522;&#12472;&#12490;&#12523;&#30011;&#20687;&#12434;&#38283;&#12367;';
		objBottomNavOriginalLink.setAttribute('title',objBottomNavOriginalLink.innerHTML);
		objBottomNav.appendChild(objBottomNavOriginalLink);

		var objImageDetails = document.createElement("div");
		objImageDetails.setAttribute('id','imageDetails');
		objImageData.appendChild(objImageDetails);

		var objCaption = document.createElement("span");
		objCaption.setAttribute('id','caption');
		objImageData.appendChild(objCaption);

		var objNumberDisplay = document.createElement("span");
		objNumberDisplay.setAttribute('id','numberDisplay');
		objImageData.appendChild(objNumberDisplay);

	},

	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
	//
	start: function(imageLink) {

		hideSelectBoxes();

		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		Element.setHeight('overlay', arrayPageSize[1]);
		new Effect.Appear('overlay', { duration: 0.2, from: 0.0, to: 0.8 });

		imageArray = [];
		imageNum = 0;

		if (!document.getElementsByTagName){ return; }
		
		var myrel = imageLink.getAttribute('rel');
		if((myrel == 'lightbox')){
			// add single image to imageArray
			imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title')));
		} else if (myrel) {
			// if image is part of a set..

			// loop through anchors, find other images in set, and add them to imageArray
			var r = document.evaluate('descendant::a[@rel="'+myrel+'"]', document, null, 7, null);
			for (var i=0; i<r.snapshotLength; i++){
				var anchor = r.snapshotItem(i);
				if (anchor.getAttribute('href')) {
					imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
				}
			}

			imageArray.removeDuplicates();
			while(imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}
		}

		// calculate top offset for the lightbox and display
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 50);

		Element.setTop('lightbox', lightboxTop);
		Element.show('lightbox');

		this.changeImage(imageNum);
	},

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {

		activeImage = imageNum;	// update global var

		// hide elements during transition
		Element.show('loading');
		Element.hide('lightboxImage');
		Element.hide('hoverNav');
		Element.hide('prevLink');
		Element.hide('nextLink');
		Element.hide('imageDataContainer');
		Element.hide('numberDisplay');

		this.imgPreloader = new Image();

		// once image is preloaded, resize image container
		this.imgPreloader.onload=function(){
			if (this.timer) {clearTimeout(this.timer);this.timer=null;};
			this.myAjax = null;
			Element.setSrc('lightboxImage', this.imgPreloader.src);
			this.resizeImageContainer(this.imgPreloader.width, this.imgPreloader.height);
		}.bind(this);
		
		if (this.timer) {clearTimeout(this.timer);this.timer=null;}
			this.timer = setTimeout(function(){
			this.imgPreloader.src = wikihelper_root_url + '/skin/loader.php?src=timeout.gif';
		}.bind(this),lightbox_timeout);
		
		// Check URL found or notfound?
		//if (this.imgPreloader.src.match(/^http/i) && !this.imgPreloader.src.match(this.myhost))
		//{
		//	this.checkUrl(this.imgPreloader.src);
		//}
		
		this.imgPreloader.src = imageArray[activeImage][0];
	},
	
	
	// Check URL by ajax
	checkUrl: function(url) {
		var url = './plugin_data/lightbox/checkurl.php?q=' + encodeURIComponent(url);
		this.myAjax = new Ajax.Request(
			url, 
			{
				method: 'GET',
				requestHeaders: ['Referer',document.location],
				onComplete: this.onCheckedUrl.bind(this)
			});
	},
	
	// Checked URL
	onCheckedUrl: function(Req) {
		var rc = eval(Req.responseText);
		if (rc != 200)
		{
			this.imgPreloader.src = wikihelper_root_url + '/skin/loader.php?src=notfound.gif';
		}
	},
	
	//
	//	resizeImageContainer()
	//
	resizeImageContainer: function( imgWidth, imgHeight ) {

		document.getElementById('bottomNavClose').style.display = 'block';
		document.getElementById('originalLinkNew').style.display = 'none';
		document.getElementById('originalLink').style.display = 'none';
		var boxHeight = imgHeight + 36 + (borderSize * 3);
		var boxWidth = imgWidth + (borderSize * 2);
		var ratio = 0.96;
		
		if(arrayPageSize[3] <= boxHeight | arrayPageSize[2] <= boxWidth){
			if(arrayPageSize[3] <= boxHeight) {
				imgRatio = imgWidth / imgHeight;
				imgHeight = (arrayPageSize[3] - 36 - (borderSize * 3)) * ratio;
				imgWidth = imgHeight * imgRatio;
				if(arrayPageSize[2] <= boxWidth) {
					imgRatio = imgHeight / imgWidth;
					imgWidth = (arrayPageSize[2] - (borderSize * 2)) * ratio;
					imgHeight = imgWidth * imgRatio;
					if(arrayPageSize[3] <= boxHeight) {
						imgRatio = imgWidth / imgHeight;
						imgHeight = (arrayPageSize[3] - 36 - (borderSize * 3)) * ratio;
						imgWidth = imgHeight * imgRatio;
					}
				}
			} else if(arrayPageSize[2] <= boxWidth) {
				imgRatio = imgHeight / imgWidth;
				imgWidth = (arrayPageSize[2] - (borderSize * 2)) * ratio;
				imgHeight = imgWidth * imgRatio;
				if(arrayPageSize[3] <= boxHeight) {
					imgRatio = imgWidth / imgHeight;
					imgHeight = (arrayPageSize[3] - 36 - (borderSize * 3)) * ratio;
					imgWidth = imgHeight * imgRatio;
					if(arrayPageSize[2] <= boxWidth) {
						imgRatio = imgHeight / imgWidth;
						imgWidth = (arrayPageSize[2] - (borderSize * 2)) * ratio;
						imgHeight = imgWidth * imgRatio;
					}
				}
			}
		document.getElementById('originalLinkNew').style.display = 'block';
		document.getElementById('originalLink').style.display = 'block';
		}
		

		document.getElementById('lightboxImage').width = imgWidth;
		document.getElementById('lightboxImage').height = imgHeight;
		
		imageDetails_w = imgWidth - 220;
		if (imageDetails_w < 1) imageDetails_w = imgWidth;
		document.getElementById('imageDetails').style.width = imageDetails_w + 'px';

		// get current height and width
		this.wCur = Element.getWidth('outerImageContainer');
		this.hCur = Element.getHeight('outerImageContainer');

		// scalars based on change from old to new
		this.xScale = ((imgWidth  + (borderSize * 2)) / this.wCur) * 100;
		this.yScale = ((imgHeight  + (borderSize * 2)) / this.hCur) * 100;

		// calculate size difference between new and old image, and resize if necessary
		wDiff = (this.wCur - borderSize * 2) - imgWidth;
		hDiff = (this.hCur - borderSize * 2) - imgHeight;

		if(!( hDiff == 0)){ new Effect.Scale('outerImageContainer', this.yScale, {scaleX: false, duration: resizeDuration, queue: 'front'}); }
		if(!( wDiff == 0)){ new Effect.Scale('outerImageContainer', this.xScale, {scaleY: false, delay: resizeDuration, duration: resizeDuration}); }

		// if new and old image are same size and no scaling transition is necessary,
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);}
		}

		Element.setHeight('prevLink', imgHeight);
		Element.setHeight('nextLink', imgHeight);
		Element.setWidth( 'imageDataContainer', imgWidth + (borderSize * 2));

		this.showImage();
	},

	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//
	showImage: function(){
		Element.hide('loading');
		new Effect.Appear('lightboxImage', { duration: 0.5, queue: 'end', afterFinish: function(){	myLightbox.updateDetails(); } });
		this.preloadNeighborImages();
	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {

		Element.show('caption');
		Element.setInnerHTML( 'caption', imageArray[activeImage][1]);

		// if image is part of set display 'Image x of x'
		if(imageArray.length > 1){
			Element.show('numberDisplay');
			Element.setInnerHTML( 'numberDisplay', "<a href=\""+imageArray[activeImage][0]+"\" title=\"Open this window\">Image " + eval(activeImage + 1) + "</a> of " + imageArray.length);
		}

		new Effect.Parallel(
			[ new Effect.SlideDown( 'imageDataContainer', { sync: true, duration: resizeDuration + 0.25, from: 0.0, to: 1.0 }),
			  new Effect.Appear('imageDataContainer', { sync: true, duration: 1.0 }) ],
			{ duration: 0.65, afterFinish: function() { myLightbox.updateNav();} }
		);
	},

	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {

		Element.show('hoverNav');

		// if not first image in set, display prev image button
		if(activeImage != 0){
			Element.show('prevLink');
			document.getElementById('prevLink').onclick = function() {
				myLightbox.changeImage(activeImage - 1); return false;
			}
		}

		// if not last image in set, display next image button
		if(activeImage != (imageArray.length - 1)){
			Element.show('nextLink');
			document.getElementById('nextLink').onclick = function() {
				myLightbox.changeImage(activeImage + 1); return false;
			}
		}

		this.enableKeyboardNav();
	},

	//
	//	enableKeyboardNav()
	//
	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction;
	},

	//
	//	disableKeyboardNav()
	//
	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	//
	//	keyboardAction()
	//
	keyboardAction: function(e) {
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}

		key = String.fromCharCode(keycode).toLowerCase();

		if((key == 'x') || (key == 'o') || (key == 'c')){	// close lightbox
			myLightbox.end();
		} else if(key == 'p'){	// display previous image
			if(activeImage != 0){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(activeImage - 1);
			}
		} else if(key == 'n'){	// display next image
			if(activeImage != (imageArray.length - 1)){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(activeImage + 1);
			}
		}


	},

	//
	//	preloadNeighborImages()
	//	Preload previous and next images.
	//
	preloadNeighborImages: function(){

		if((imageArray.length - 1) > activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = imageArray[activeImage + 1][0];
		}
		if(activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = imageArray[activeImage - 1][0];
		}

	},

	//
	//	end()
	//
	end: function() {
		if (this.timer) {clearTimeout(this.timer);this.timer=null;}
		document.getElementById('bottomNavClose').style.display = 'none';
		document.getElementById('originalLinkNew').style.display = 'none';
		document.getElementById('originalLink').style.display = 'none';
		this.disableKeyboardNav();
		Element.hide('lightbox');
		new Effect.Fade('overlay', { duration: 0.2});
		showSelectBoxes();
	},

	viewOriginalNew: function() {
		window.open(document.getElementById('lightboxImage').src);
	},

	viewOriginal: function() {
		window.location.href = document.getElementById('lightboxImage').src;
	}
}

// -----------------------------------------------------------------------------------

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll)
	return arrayPageScroll;
}

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){

	var xScroll, yScroll;
	
	var documentBody = (document.documentElement || document.body);
	
	if (window.innerHeight && window.scrollMaxY) {
		xScroll = documentBody.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (documentBody.scrollHeight > documentBody.offsetHeight){ // all but Explorer Mac
		xScroll = documentBody.scrollWidth;
		yScroll = documentBody.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = documentBody.offsetWidth;
		yScroll = documentBody.offsetHeight;
	}

	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else {
		windowWidth = documentBody.clientWidth;
		windowHeight = documentBody.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();

	if(key == 'x'){
	}
}

// -----------------------------------------------------------------------------------

//
// listenKey()
//
function listenKey () {	document.onkeypress = getKey; }

// ---------------------------------------------------

function showSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		if (!selects[i].id.match(/^edit_/))  // for fusen plugin by nao-pon
		{
			selects[i].style.visibility = "visible";
		}
	}
}

// ---------------------------------------------------

function hideSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		if (!selects[i].id.match(/^edit_/))  // for fusen plugin by nao-pon
		{
			selects[i].style.visibility = "hidden";
		}
	}
}

// ---------------------------------------------------

//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

// ---------------------------------------------------

function initLightbox() { myLightbox = new Lightbox(); }

XpWiki.domInitFunctions.push(initLightbox);

}
if (typeof(googlemaps_maps) == 'undefined') {
	// add vml namespace for MSIE
	var agent = navigator.userAgent.toLowerCase();
	if (agent.indexOf("msie") != -1 && agent.indexOf("opera") == -1) {
		try {
		document.namespaces.add('v', 'urn:schemas-microsoft-com:vml');
		document.createStyleSheet().addRule('v\:*', 'behavior: url(#default#VML);');
		} catch(e) {}
	}

	var googlemaps_maps = new Array();
	var googlemaps_markers = new Array();
	var googlemaps_marker_mgrs = new Array();
	var googlemaps_icons = new Array();
	var googlemaps_crossctrl = new Array();
	var onloadfunc = new Array();
	var onloadfunc2 = new Array();
}

function PGMarker (point, icon, page, map, hidden, visible, title, maxtitle, maxcontent, minzoom, maxzoom) {
	var marker = null;
	if (hidden == false) {
		var opt = new Object();
		if (icon != '') {
			opt.icon = googlemaps_icons[page][icon];
		} else if (!!googlemaps_icons[page]['_default']) {
			opt.icon = googlemaps_icons[page]['_default'];
		}
		if (title != '') { opt.title = title; }
		marker = new GMarker(point, opt);
		GEvent.addListener(marker, "click", function() { this.pukiwikigooglemaps.onclick(); });
		marker.pukiwikigooglemaps = this;
	}

	this.marker = marker;
	this.icon = icon;
	this.map = map;
	this.point = point;
	this.minzoom = minzoom;
	this.maxzoom = maxzoom;

	var _visible = false;
	var _html = null;
	var _zoom = null;
	var _type = null;

	this.setHtml = function(h) {_html = h;}
	this.setZoom = function(z) {_zoom = parseInt(z);}
	this.setType = function(t) {_type = t;}
	this.getHtml = function() {return _html;}
	this.getZoom = function() {return _zoom;}
	//this.getType = function() {return _type;}

	this.onclick = function () {
		var map = googlemaps_maps[page][this.map];
        var maxContentDiv = document.createElement('div');

        maxContentDiv.innerHTML = 'Loading...';
        infowindowopts = {maxContent:maxContentDiv, maxTitle:maxtitle};
        if (maxcontent == "") {
            map.getInfoWindow().disableMaximize();
            infowindowopts = {};
        }
		
		if (_type !== map.getCurrentMapType()) {
			map.setMapType(_type);
		}
		
		if (_zoom) {
			if (map.getZoom() != _zoom) {
				map.setZoom(_zoom);
			}
		}
		
		map.panTo(this.point);
		
		if ( _html && this.marker ) {
			//map.panTo(this.point);
			// Wait while load image.
			var root = document.createElement('div');
			root.innerHTML = _html;

			var checkNodes = new Array();
			var doneOpenInfoWindow = false;
			checkNodes.push(root);

			while (checkNodes.length) {
				var node = checkNodes.shift();
				if (node.hasChildNodes()) {
					for (var i=0; i<node.childNodes.length; i++) {
						checkNodes.push(node.childNodes.item(i));
					}
				} else {
					var tag = node.tagName;
					if (tag && tag.toUpperCase() == "IMG") {
						if (node.complete == false) {
							// Wait while load image.
							var openInfoWindowFunc = function (xmlhttp) {
								marker.openInfoWindowHtml(_html, infowindowopts);
							}
							var async = false;
							if (agent.indexOf("msie") != -1 && agent.indexOf("opera") == -1) {
								async = true;
							}
							if (PGTool.downloadURL(node.src, openInfoWindowFunc, async, null, null)) {
								doneOpenInfoWindow = true;
							}
							break;
						}
					}
				}
			}
			if (doneOpenInfoWindow == false) {
				this.marker.openInfoWindowHtml(_html, infowindowopts);
                if (maxcontent) {
                    maxContentDiv.style.width = "100%";
                    maxContentDiv.style.height = "98%";
                    maxContentDiv.innerHTML = '<iframe src="' + maxcontent + 
                    '" frameborder="0" height=100% width=100%>required iframe enabled browser</iframe>';
                }
			}
		} else {
			//map.panTo(this.point);
		}
	}
	
	this.isVisible = function () {
		return _visible;
	}
	this.show = function () {
		if (_visible) return;
		if (this.marker) this.marker.show();
		_visible = true;
	}

	this.hide = function () {
		if (!_visible) return;
		if (this.marker != null) this.marker.hide();
		_visible = false;
	}
	
	if (visible) {
		this.show();
	} else {
		this.hide();
	}
	return this;
}


var PGTool = new function () {
	this.fmtNum = function (x) {
		var n = x.toString().split(".");
		n[1] = (n[1] + "000000").substr(0, 6);
		return n.join(".");
	}
	this.getLatLng = function (x, y, api) {
		switch (api) {
			case 0:
				x = x - y * 0.000046038 - x * 0.000083043 + 0.010040;
				y = y - y * 0.00010695  + x * 0.000017464 + 0.00460170;
			case 1:
				t = x;
				x = y;
				y = t;
				break;
		}
		return new GLatLng(x, y);
	}
	this.getXYPoint = function (x, y, api) {
		if (api < 2) {
			t = x;
			x = y;
			y = t;
		}
		if (api == 0) {
			nx = 1.000083049 * x + 0.00004604674815 * y - 0.01004104571;
			ny = 1.000106961 * y - 0.00001746586797 * x - 0.004602192204;
			x = nx;
			y = ny;
		}
		return {x:x, y:y};
	}
	this.createXmlHttp = function () {
		if (typeof(XMLHttpRequest) == "function") {
			return new XMLHttpRequest();
		}
		if (typeof(ActiveXObject) == "function") {
			try {
				return new ActiveXObject("Msxml2.XMLHTTP");
			} catch(e) {};
			try {
				return new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {};
		}
		return null;
	}
	this.downloadURL = function (url, func, async, postData, contentType) {
		var xmlhttp = this.createXmlHttp();
		if (!xmlhttp) {
			return null;
		}
		if (async && func) {
			xmlhttp.onreadystatechange = function () {
				if (xmlhttp.readyState == 4) {
					func(xmlhttp);
				}
			};
		}
		try {
			if (postData) {
				xmlhttp.open("POST", url, async);
				if (!contentType) {
					contentType = "application/x-www-form-urlencoded";
				}
				xmlhttp.setRequestHeader("Content-Type", contentType);
				xmlhttp.send(postData);
			} else {
				xmlhttp.open("GET", url, async);
				xmlhttp.send(null);
			}
		} catch(e) {
			return false;
		}
		if (!async && func) func(xmlhttp);
	}

	this.transparentGoogleLogo = function(map) {
		var container = map.getContainer();
		for (var i=0; i<container.childNodes.length; i++) {
			var node = container.childNodes.item(i);
			if (node.tagName != "A") continue;
			if (node.hasChildNodes() == false) continue;

			var img = node.firstChild;
			if (img.tagName != "IMG") continue;
			if (img.src.match(/http:.*\/poweredby\.png/) == null) continue;

			node.style.backgroundColor = "transparent";
			break;
		}
		return;
	}
	
	this.getMapTypeName = function(type) {
		if (type == G_HYBRID_MAP) {
			return 'hybrid';
		} else if (type == G_SATELLITE_MAP) {
			return 'satellite';
		} else if (type == G_PHYSICAL_MAP) {
			return 'physical';
		} else {
			return 'normal';
		}
	}
}

var PGDraw = new function () {
	var self = this;
	this.weight = 10;
	this.opacity = 0.5;
	this.color = "#00FF00";
	this.fillopacity = 0;
	this.fillcolor = "#FFFF00";

	this.line = function (plist) {
		return new GPolyline(plist, this.color, this.weight, this.opacity);
	}
	
	this.rectangle = function (p1, p2) {
		var points = new Array (
			p1,
			new GLatLng(p1.lat(), p2.lng()),
			p2,
			new GLatLng(p2.lat(), p1.lng()),
			p1
		);
		return draw_polygon (plist);
	}
	
	this.circle  = function (point, radius) {
		return draw_ngon(point, radius, 0, 48, 0, 360);
	}
	
	this.arc = function (point, outradius, inradius, st, ed) {
		while (st > ed) { ed += 360; }
		if (st == ed) {
			return this.circle(point, outradius, inradius);
		}
		return draw_ngon(point, outradius, inradius, 48, st, ed);
	}
	
	this.ngon = function (point, radius, n, rotate) {
		if (n < 3) return null;
		return draw_ngon(point, radius, 0, n, rotate, rotate+360);
	}
	
	this.polygon = function (plist) {
		return draw_polygon (plist);
	}
	
	function draw_ngon (point, outradius, inradius, div, st, ed) {
		if (div <= 2) return null;

		var incr = (ed - st) / div;
		var lat = point.lat();
		var lng = point.lng();
		var out_plist = new Array();
		var in_plist  = new Array();
		var rad = 0.017453292519943295; /* Math.PI/180.0 */
		var en = 0.00903576399827824;   /* 1/(6341km * rad) */
		var out_clat = outradius * en; 
		var out_clng = out_clat/Math.cos(lat * rad);
		var in_clat = inradius * en; 
		var in_clng = in_clat/Math.cos(lat * rad);
		
		for (var i = st ; i <= ed; i+=incr) {
			if (i+incr > ed) {i=ed;}
			var nx = Math.sin(i * rad);
			var ny = Math.cos(i * rad);

			var ox = lat + out_clat * nx;
			var oy = lng + out_clng * ny;
			out_plist.push(new GLatLng(ox, oy));

			if (inradius > 0) {
			var ix = lat + in_clat  * nx;
			var iy = lng + in_clng  * ny;
			in_plist.push (new GLatLng(ix, iy));
			}
		}

		var plist;
		if (ed - st == 360) {
			plist = out_plist;
			plist.push(plist[0]);
		} else {
			if (inradius > 0) {
				plist = out_plist.concat( in_plist.reverse() );
				plist.push(plist[0]);
			} else {
				out_plist.unshift(point);
				out_plist.push(point);
				plist = out_plist;
			}
		}

		return draw_polygon(plist);
	}

	function draw_polygon (plist) {
		if (self.fillopacity <= 0) {
		return new GPolyline(plist, self.color, self.weight, self.opacity);
		}
		return new GPolygon(plist, self.color, self.weight, self.opacity, 
		self.fillcolor, self.fillopacity); 
	}

}


//
// Center Cross control
//
function PGCross() {
	this.map = null;
	this.container = null;
};
PGCross.prototype = new GControl(false, false);

PGCross.prototype.initialize = function(map) {
	this.map = map;
	this.container = document.createElement("div");
	var crossDiv = this.createWidget(16, 2, "#000000");
	this.container.appendChild(crossDiv);
	this.container.width = crossDiv.width;
	this.container.height = crossDiv.height;
	
	var cross = this;
	GEvent.addDomListener(map, "resize", function(e) {
		var size = cross.getCrossCenter();
		cross.container.style.top  = size.height + 'px';
		cross.container.style.left = size.width  + 'px';
	});
	// TODO:The mouse event on Cross is spread to Map of the layer below.
	//GEvent.addDomListener(crossDiv, "dblclick", function(e) {
	//		if (map.doubleClickZoomEnabled())
	//			map.zoomIn();
	//});
	
	map.getContainer().appendChild(this.container);
	
	info = map.getInfoWindow();
	var container = this.container;
	var hidefunc = function() { map.getContainer().removeChild(container); }
	var showfunc = function() { map.getContainer().appendChild(container); }
	GEvent.addListener(map, "infowindowclose", function(){ showfunc(); });
	GEvent.addListener(info, "maximizeclick", function(){ hidefunc(); });
	GEvent.addListener(info, "restoreend", function(){ showfunc(); });

	return this.container;
}

PGCross.prototype.getCrossCenter = function() {
	var msize = this.map.getSize();
	var x = (msize.width  - this.container.width)/2.0;
	var y = (msize.height - this.container.height)/2.0;
	return new GSize(Math.ceil(x), Math.ceil(y));
}

PGCross.prototype.createWidget = function(nsize, lwidth, lcolor) {
	var hsize = (nsize - lwidth) / 2;
	var nsize = hsize * 2 + lwidth;
	var border = document.createElement("div");
	border.width = nsize;
	border.height = nsize;
	var table = '\
<table width="'+nsize+'" border="0" cellspacing="0" cellpadding="0">\
  <tr>\
  <td style="width:'+ hsize+'px; height:'+hsize+'px; background-color:transparent; border:0px;"></td>\
  <td style="width:'+lwidth+'px; height:'+hsize+'px; background-color:'+lcolor+';  border:0px;"></td>\
  <td style="width:'+ hsize+'px; height:'+hsize+'px; background-color:transparent; border:0px;"></td>\
  </tr>\
  <tr>\
  <td style="width:'+ hsize+'px; height:'+lwidth+'px; background-color:'+lcolor+'; border:0px;"></td>\
  <td style="width:'+lwidth+'px; height:'+lwidth+'px; background-color:'+lcolor+'; border:0px;"></td>\
  <td style="width:'+ hsize+'px; height:'+lwidth+'px; background-color:'+lcolor+'; border:0px;"></td>\
  </tr>\
  <tr>\
  <td style="width:'+ hsize+'px; height:'+hsize+'px; background-color:transparent; border:0px;"></td>\
  <td style="width:'+lwidth+'px; height:'+hsize+'px; background-color:'+lcolor+';  border:0px;"></td>\
  <td style="width:'+ hsize+'px; height:'+hsize+'px; background-color:transparent; border:0px;"></td>\
  </tr>\
</table>';
	border.innerHTML = table;
	border.firstChild.style.MozOpacity = 0.5;
	border.firstChild.style.filter = 'alpha(opacity=50)';
	return border;
}

PGCross.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, this.getCrossCenter());
}

PGCross.prototype.changeStyle = function(color, opacity) {
	var table = this.container.firstChild.firstChild;
	var children = table.getElementsByTagName("td");
	for (var i = 0; i < children.length; i++) {
		var node = children[i];
		if (node.style.backgroundColor != "transparent") {
			node.style.backgroundColor = color;
		}
	}
	table.style.MozOpacity = opacity;
	table.style.filter = 'alpha(opacity=' + (opacity * 100) + ')';
}

//
// Marker ON/OFF
//

function p_googlemaps_marker_toggle (page, mapname, check, name) {
	var markers = googlemaps_markers[page][mapname];
	for (key in markers) {
		if (!markers.hasOwnProperty(key)) continue;
		var m = markers[key];
		if (m.icon == name) {
			if (check.checked) {
				m.show();
			} else {
				m.hide();
			}
		}
	}
}

function p_googlemaps_togglemarker_checkbox (page, mapname, undefname, defname) {
	var icons = {};
	var markers = googlemaps_markers[page][mapname];
	for (key in markers) {
		if (!markers.hasOwnProperty(key)) continue;
		var map = markers[key].map;
		var icon = markers[key].icon;
		icons[icon] = 1;
	}
	var iconlist = new Array();
	for (n in icons) {
		if (!icons.hasOwnProperty(n)) continue;
		iconlist.push(n);
	}
	iconlist.sort();

	var r = document.createElement("div");
	var map = document.getElementById(mapname);
	map.parentNode.insertBefore(r, map.nextSibling);

	for (i in iconlist) {
		if (!iconlist.hasOwnProperty(i)) continue;
		var name = iconlist[i];
		var id = "ti_" + mapname + "_" + name;
		var input = document.createElement("input");
		var label = document.createElement("label");
		input.setAttribute("type", "checkbox");
		input.id = id;
		label.htmlFor = id;
		if (name == "") {
		label.appendChild(document.createTextNode(undefname));
		} else if (name == "Default") {
		label.appendChild(document.createTextNode(defname));
		} else {
		label.appendChild(document.createTextNode(name));
		}
		eval("input.onclick = function(){p_googlemaps_marker_toggle('" + page + "','" + mapname + "', this, '" + name + "');}");

		r.appendChild(input);
		r.appendChild(label);
		input.setAttribute("checked", "checked");
	}
}

function p_googlemaps_regist_marker (page, mapname, center, key, option) {
	if (document.getElementById(mapname) == null) {
		mapname = mapname.replace(/^pukiwikigooglemaps2_/, "");
		page = mapname.match(/(^.*?)_/)[1];
		mapname = mapname.replace(/^.*?_/, "");
		alert("googlemaps2: '" + option.title + "' It failed in the marker's registration." + 
		"PageName: " + page + ", Not found map name '" + mapname + "'.");
		return;
	}
	option.title = option.title.replace(/&lt;/g, '<');
	option.title = option.title.replace(/&gt;/g, '>');
	option.title = option.title.replace(/&quot;/g, '"');
	option.title = option.title.replace(/&#039;/g, '\'');
	option.title = option.title.replace(/&amp;/g, '&');
	var m = new PGMarker(center, option.icon, page, mapname, option.noicon, true, option.title, option.maxtitle, option.maxcontent, option.minzoom, option.maxzoom);
	m.setHtml(option.infohtml);
	if (!option.zoom) {
		option.zoom = googlemaps_maps[page][mapname].getZoom();
	}
	m.setZoom(option.zoom);
	if (!option.type) {
		option.type = googlemaps_maps[page][mapname].getCurrentMapType();
	}
	m.setType(option.type);
	googlemaps_markers[page][mapname][key] = m;
}

function p_googlemaps_regist_to_markermanager (page, mapname, use_marker_mgr) {
	var markers = googlemaps_markers[page][mapname];
	
	if (use_marker_mgr == false) {
		for ( var key in markers) {
			if (!markers.hasOwnProperty(key)) continue;
			var m = markers[key];

			if (m.marker) {
				googlemaps_maps[page][mapname].addOverlay(m.marker);
			}
		}
		return;
	}

	var mgr = googlemaps_marker_mgrs[page][mapname];
	var levels = new Object();

	for (key in markers) {
		if (!markers.hasOwnProperty(key)) continue;
		var m = markers[key];
		var minzoom = m.minzoom<0 ? 0:m.minzoom;
		var maxzoom = m.maxzoom>17? 17:m.maxzoom;
		if (minzoom > maxzoom) {
			maxzoom = minzoom;
		}

		if (m.marker) {
			if (levels[minzoom] == undefined) {
				levels[minzoom] = new Object();
			}
			if (levels[minzoom][maxzoom] == undefined) {
				levels[minzoom][maxzoom] = new Array();
			}
			levels[minzoom][maxzoom].push(m.marker);
		}
	}

	for (minzoom in levels) {
		if (!levels.hasOwnProperty(minzoom)) continue;
		for (maxzoom in levels[minzoom]) {
			if (!levels[minzoom].hasOwnProperty(maxzoom)) continue;
			if (levels[minzoom][maxzoom])
			mgr.addMarkers(levels[minzoom][maxzoom], parseInt(minzoom), parseInt(maxzoom));
		}
	}
	mgr.refresh();
}

function p_googlemaps_auto_zoom (page, mapname) {
		var gb;
		var first = 1;
		var map = googlemaps_maps[page][mapname];
		var markers = googlemaps_markers[page][mapname];
		for( var key in markers ){
			if (!markers.hasOwnProperty(key)) continue;
			var marker = markers[key].marker;
			if( first ){
				gb = new GLatLngBounds( marker.getPoint(), marker.getPoint() );
				first = 0;
			}else{
				var point = marker.getPoint();
				gb.extend( point );
			}
		}
		map.setCenter( gb.getCenter(), map.getBoundsZoomLevel( gb ) );
}

XpWiki.domInitFunctions.push(function() {
	if (GBrowserIsCompatible()) {
		while (onloadfunc.length > 0) {
			onloadfunc.shift()();
		}
		while (onloadfunc2.length > 0) {
			onloadfunc2.shift()();
		}
	}
});

window.onunload = function () {
	GUnload();
}

