var icon = new GIcon();
icon.image = '';
icon.iconSize = new GSize(0, 0);
icon.iconAnchor = new GPoint(0, 0);
icon.infoWindowAnchor = new GPoint(300, 20);
var bigOpts	 = {icon: icon, itemType: "", itemFilename: "", itemUserAvatarFilename:"default.png", tab:"", ownerID: "", ownerDisplayName:"", labelOffset: new GSize(-9,-269), labelType: "bigmarker", id:"", title:"", description:"", datetime:"", locationName:"", labelClass:"bigmarker_container", clickable:false};
var smallOpts = {icon: icon, itemType: "", itemFilename: "", tab:"", ownerID: "", ownerDisplayName:"", labelOffset: new GSize(0,-52), labelType: "smallmarker", id:"", title:"", labelClass:"smallmarker_container", clickable:false};

var bigMarkerBgrndWidth = 216;
var bigMarkerBgrndHeight = 260;
var smallMarkerBgrndWidth = 46;
var smallMarkerBgrndHeight = 50;

var map;

var nochangeloop = 0;

var userid = 0;
var viewerid = 0;
var indexlist = new Array();
var usernamelist = new Array();
var owneridlist = new Array();
var itemidlist = new Array();
var itemlatlnglist = new Array();
var itemtitlelist = new Array();
var itemdescriptionlist = new Array();
var itemlocationnamelist = new Array();
var itemdatetimelist = new Array();
var itemtagslist = new Array();
var itemtypelist = new Array();
var itemfilenamelist = new Array();
var itemuseravatarfilenamelist = new Array();

var preloaditemlist = new Array();
var preloadthumblist = new Array();var srcthumblist = new Array();

var randomItemlist = new Array();

var lastitemindex;

photopath_30x30 = staticpath+"/asset/photo/30x30/";
photopath_mini = staticpath+"/asset/photo/37x28/";
photopath_medium = staticpath+"/asset/photo/medium/";
photopath_thumb = "/asset/photo/200x150/";

videopngpath_30x30 = "/asset/video/png/30x30/";
videopngpath_mini = "/asset/video/png/37x28/";
videopngpath_medium = "/asset/video/png/medium/";
videopngpath_thumb = "/asset/video/png/200x150/";

var bigmarkers = new Array();
var smallmarkers = new Array();
var markerCount = 0;

var preloadbigmkbgrnd = new Image();
preloadbigmkbgrnd.src = "/static/v2p/images/big_marker.png";
var preloadsmallmkbgrnd = new Image();
preloadsmallmkbgrnd.src = "/static/v2p/images/small_marker.png";

var center = new GLatLng(13.744617, 100.533786);
var zoom = 13;

var isNormalMap = true;
var lastdatetime = 0;
var getdatetime;

var updateItemTimer;
closebigMarkerTimer=0;
var isNewestItemIndexPopup = false;
var effectmove;
bigMarkerPopupIndex=0;

var infopaneimglist = new Array();

var defaultnUser = 18;
var tab = 'user';//'friend','public'
var isInitializing = false;

var placeidlist = new Array();
var placelatlnglist = new Array();
var placeinfolist = new Array();
var placefilenamelist = new Array();
var lastPlaceID = 0;
var getPlaceID;
var updatePlaceTimer;

function getViewportWidth(){
    var width = window.innerWidth; // Safari
    var mode = document.compatMode;
    if(mode || isIE){
        width = isStrict ? document.documentElement.clientWidth : document.body.clientWidth;
    }
    return width;
}

function getDocumentWidth(){
    var scrollWidth = isStrict ? document.documentElement.scrollWidth : document.body.scrollWidth;
    return Math.max(scrollWidth, getViewportWidth());
}

function init(){
	if(isInitializing == true) return;
	isInitializing = true;
    $("map-loading").style.display = "block";
	for(var i = 0; i < indexlist.length; i++){
		if(preloaditemlist[indexlist[i]] != undefined)preloaditemlist[indexlist[i]].onload = function(){};
	}
	
	map.clearOverlays();
	bigmarkers.length = 0;
	smallmarkers.length = 0;
	markerCount = 0;
	
	nochangeloop = 0;
	indexlist.length = 0;
	usernamelist.length = 0;
	owneridlist.length = 0;
	itemidlist.length = 0;
	itemlatlnglist.length = 0;
	itemtitlelist.length = 0;
	itemdescriptionlist.length = 0;
	itemlocationnamelist.length = 0;
	itemdatetimelist.length = 0;
	itemtagslist.length = 0;
	itemtypelist.length = 0;
    itemuseravatarfilenamelist.length = 0;
	preloaditemlist.length = 0;
	preloadthumblist.length = 0;
	
	lastitemindex = undefined;
	
	lastdatetime = 0;
	getdatetime = undefined;
	
	clearTimeout(updateItemTimer);
	clearTimeout(closebigMarkerTimer);
	closebigMarkerTimer = 0;
	
	isNewestItemIndexPopup = false;
	if(effectmove) effectmove.cancel();
	var length = isNormalMap==true ? (parseInt($("map").getStyle('left')) + $("map").getWidth() + parseInt($("map_wrapper").getStyle('borderLeftWidth')) - parseInt($("infopane_wrapper").getStyle('left'))) : getDocumentWidth() - parseInt($("infopane_wrapper").getStyle('left'))
	effectmove = new Effect.Move("infopane_wrapper",{x:length,y:0,duration:0.5});
	
	bigMarkerPopupIndex=0;
	
	var infopane_imgcontainer = $('infopane_imgcontainer');
	infopane_imgcontainer.innerHTML = '';
	infopaneimglist.length = 0;
	d = null;
	if(tab == 'public'){
		d = loadJSONDoc("/updatemaps",{userid: 0, nUser: defaultnUser, tab: tab});
	}else{
		d = loadJSONDoc("/updatemaps",{userid: userid, nUser: defaultnUser, tab: tab});
	}
	d.addCallback(handleLoadCallback);
}

function switchTab(tabname){
	if(isInitializing == true) return;
	if(tab != tabname){
        var currenttab = $(tabname+"tab");
        currenttab.className = "selected";
        currenttab.siblings().each(function(li){
            li.className = "";
        });
        tab = tabname;
		if(map){
			init();
		}
	}
}

function load(id){
	userid = id;
	if(GBrowserIsCompatible()){
		map = new GMap2($("map"));
		map.setCenter(center, zoom);
        map.setUIToDefault();
        map.disableScrollWheelZoom();
        map.enableContinuousZoom();
		
		if(userid == 0){
			switchTab("public");
		}else{
			if(isInitializing == true) return;
			isInitializing = true;
            $("map-loading").style.display = "block";
			d = null;
			d = loadJSONDoc("/updatemaps",{userid: userid, nUser: defaultnUser, tab: tab});
			d.addCallback(handleLoadCallback);
		}
	}
}

function handleLoadCallback(result) {
	if(isInitializing == false) return;
	isInitializing = false;
	if(result.ItemCount > 0){
		parsePhotoInformation(result);
		randomItemlist = result.randomItemlist;
		appendAllItemToInfoPane();
        updateItemTimer = setTimeout("handlePhotoChange()",10000);
	}else{
		lastdatetime = 0;
		getdatetime = 0;
        clearTimeout(updateItemTimer);
        $("map-loading").style.display = "none";
	}
	if(result.PlaceCount > 0){
		parsePlaceInformation(result);
		appendAllPlaceMarker();
	}
	if(!updatePlaceTimer) updatePlaceTimer = setTimeout("handlePlaceChange()",60000);
}

function toggleScreen(){
	var header = $("header");
	var nav = $("nav");
	var outerwrapper = $("outerwrapper");
	var wrapper = $("wrapper");
	var content = $("content");
	var map_tabs = $("map_tabs");
	var map_wrapper = $("map_wrapper");
	var div = $("map");
	var infopane_wrapper = $("infopane_wrapper");

	var footerdiv = $("footer");
	var btn = $("fullscreenbtn");
    var maploading = $("map-loading");

	if(isNormalMap){
		header.style.display = "none";
		nav.style.display = "none";

		outerwrapper.style.position = "absolute";
		outerwrapper.style.width = "100%";
		outerwrapper.style.height = "100%";
		outerwrapper.style.margin = "0";

		wrapper.style.position = "absolute";
		wrapper.style.borderLeft = "0";
		wrapper.style.borderRight = "0";
		wrapper.style.width = "100%";
		wrapper.style.height = "100%";
		wrapper.style.margin = "0";
		wrapper.style.border = "0";
		wrapper.style.overflow = "hidden";

		content.style.position = "absolute";
		content.style.width = "100%";
		content.style.height = "100%";
		content.style.paddingTop = "0";
		content.style.paddingLeft = "0";
		content.style.paddingRight = "0";
		content.style.paddingBottom = "0";
		content.style.background = "#4895AA url(/static/v2p/images/homepage/background_cloud.jpg) repeat-x fixed left top";

		map_tabs.style.top = "20px";

		map_wrapper.style.position = "relative";
		map_wrapper.style.width = "100%";
		map_wrapper.style.height = "90%";
		map_wrapper.style.top = "20px";
		//map_wrapper.style.borderWidth = "0";
		map_wrapper.style.borderTop = "1px solid #666";
		map_wrapper.style.borderBottom = "1px solid #666";
		

		div.style.width = "100%";
		div.style.height = "100%";
		div.style.marginBottom = "0";

		infopane_wrapper.style.left = getDocumentWidth()+"px";

		if(isIE){
			btn.style.backgroundPosition="left top";
			btn.style.color = "#0099FF";
		}
		btn.style.position = "absolute";
		btn.style.top = "10px";
		btn.style.right = "0";

		showElement("logo");
		footerdiv.style.zIndex = div.style.zIndex - 1;
		$('content').style.minHeight='300px';
        maploading.addClassName("fullscreen");
		isNormalMap = false;
	}else{
		header.style.display = "block";
		nav.style.display = "block";

		outerwrapper.style.position = "static";
		outerwrapper.style.width = "980px";
		outerwrapper.style.height = "auto";
		outerwrapper.style.margin = "0 auto";

		wrapper.style.position = "static";
		wrapper.style.width = "960px";
		wrapper.style.height = "auto";
		wrapper.style.margin = "0 auto";
		wrapper.style.border = "1px solid #19466D";

		content.style.position = "relative";
		content.style.width = "auto";
		content.style.height = "auto";
		content.style.paddingTop = "20px";
		content.style.paddingLeft = "10px";
		content.style.paddingRight = "10px";
		content.style.paddingBottom = "10px";
		content.style.background = "#FFFFFF url(/static/v2p/images/inner_body3.jpg) repeat-x scroll left top";

		map_tabs.style.top = "0";

		map_wrapper.style.position = "relative";
		map_wrapper.style.width = "auto";
		map_wrapper.style.height = "500px";
		map_wrapper.style.border = "1px solid #999";
		map_wrapper.style.top = "0";
		map_wrapper.style.clear = "both";

		div.style.width = "100%";
		div.style.height = "100%";
		div.style.marginBottom = "10px";

		if(!isIE){
			infopane_wrapper.style.left = (parseInt($("map").getStyle('left')) + $("map").getWidth() + parseInt($("map_wrapper").getStyle('borderLeftWidth')))+"px";
		}else{
			infopane_wrapper.style.left = ($("map").offsetLeft + $("map").offsetWidth)+"px";
			btn.style.backgroundPosition="left top";
			btn.style.color = "#0099FF";
		}
		btn.style.top = "10px";
		btn.style.right = "5px";

		hideElement("logo");
		footerdiv.style.zIndex = div.style.zIndex;
		if(isIE)$('content').style.minHeight = '600px';
        maploading.removeClassName("fullscreen");
		isNormalMap = true;
	}
	if(effectmove) effectmove.cancel();
	map.checkResize();
}

function parsePhotoInformation(result){
	if(isInitializing == true) return;
	var tmpindexlist = tab == 'public' ? result.ItemOwnerID:result.ItemID;

	lastitemindex = indexlist[0];
	lastdatetime = result.lastItemDateTime;
	getdatetime = lastdatetime;

	for (i = tmpindexlist.length - 1; i >= 0 ; i--)
	{
		var index = tmpindexlist[i] + result.ItemType[i];
		indexlist[i] = index;
		usernamelist[index] = result.ItemUserDisplayName[i];
		owneridlist[index] = result.ItemOwnerID[i];
		itemidlist[index] = result.ItemID[i];
		itemtitlelist[index] = result.ItemTitle[i]!='' ? result.ItemTitle[i]:'&nbsp';
		itemdescriptionlist[index] = result.ItemDescription[i]!='' ? result.ItemDescription[i]:'&nbsp';
		itemlocationnamelist[index] = result.ItemLocationName[i]
		itemlatlnglist[index] = new GLatLng(Number(result.ItemLat[i]),Number(result.ItemLng[i]));
		itemtypelist[index] = result.ItemType[i];
		itemdatetimelist[index] = result.ItemDateTime[i];
		itemtagslist[index] = result.ItemTags[i]!='' ? result.ItemTags[i]:'&nbsp';
		itemfilenamelist[index] = itemtypelist[indexlist[i]]=="photo" ? result.ItemFilename[i]:result.ItemFilename[i].substring(0,result.ItemFilename[i].lastIndexOf("."));
        itemuseravatarfilenamelist[index] = result.ItemUserAvatarFilename[i];

		preloaditemlist[index] = new Image();
		preloaditemlist[index].id = 'preloaditemlist'+index;
		preloaditemlist[index].onload = function(){addPhotoMarker0(this.id.substring(15));this.onload = function(){};}
		preloaditemlist[index].src = itemtypelist[indexlist[i]]=="photo" ? photopath_mini+getPhotoPath(owneridlist[index])+"/"+itemfilenamelist[index]:videopngpath_mini+owneridlist[index]+"/"+itemfilenamelist[index]+".png";
		srcthumblist[index] = itemtypelist[index]=="photo" ? photopath_thumb+getPhotoPath(owneridlist[index])+"/"+itemfilenamelist[index]:videopngpath_thumb+owneridlist[index]+"/"+itemfilenamelist[index]+".png";
		preloadthumblist[index] = new Image();
		preloadthumblist[index].onload = function(){};
		preloadthumblist[index].src = srcthumblist[index];
	}
	indexlist.reverse();
}

function handlePhotoChange() {
	if(isInitializing == true) return;
	if(closebigMarkerTimer !=0 && lastdatetime !=0){
		getdatetime = lastdatetime;
		nochangeloop = 0;
	}
	
	var randomItemCount = randomItemlist.length;
	if(randomItemCount > 0 && getdatetime == 0){
		var r = Math.random();
		var chosenIndex = 0;
		if(markerCount < defaultnUser){
			chosenIndex = Math.floor(r*(randomItemlist.length));
			if(chosenIndex != bigMarkerPopupIndex) delayCloseBigMarker(indexlist[chosenIndex],10000);
			if(tab == 'public'){
				pi = loadJSONDoc("/photoonmap",{userid: 0, getdatetime: lastdatetime, tab: tab, r: r});
			}else{
				pi = loadJSONDoc("/photoonmap",{userid: userid, getdatetime: lastdatetime, tab: tab, r: r});
			}
		}else{
			chosenIndex = Math.floor(r*(randomItemlist.length-markerCount));
			if(tab == 'public'){
				pi = loadJSONDoc("/photoonmap",{userid: 0, getdatetime: getdatetime, tab: tab, getItemID: randomItemlist[chosenIndex][0], getItemType: randomItemlist[chosenIndex][1], r: r});
			}else{
				pi = loadJSONDoc("/photoonmap",{userid: userid, getdatetime: getdatetime, tab: tab, getItemID: randomItemlist[chosenIndex][0], getItemType: randomItemlist[chosenIndex][1], r: r});
			}
		}
	}else{
		if(tab == 'public'){
			pi = loadJSONDoc("/photoonmap",{userid: 0, getdatetime: lastdatetime, tab: tab, r: r});
		}else{
			pi = loadJSONDoc("/photoonmap",{userid: userid, getdatetime: lastdatetime, tab: tab, r: r});
		}
	}
	pi.addCallback(handlePhotoCallback);
}

function handlePhotoCallback(result) {
	if(isInitializing == true) return;
	if(result.ItemCount > 0){
		updatePhoto(result);
		nochangeloop = 0;
	}else if(nochangeloop > 0){
		getdatetime = 0;
		nochangeloop = 0;
	}else if(lastdatetime !=0){
		getdatetime = lastdatetime;
	}
	if(closebigMarkerTimer != 0) nochangeloop = 0;
	
	updateItemTimer = setTimeout("handlePhotoChange()",10000);
	nochangeloop++;
}

function addPhotoMarker0(index){
	if(isInitializing == true) return;
	lastitemindex = index;

	bigOpts.title 		= itemtitlelist[lastitemindex];
	smallOpts.title		= itemtitlelist[lastitemindex];
	bigOpts.description = itemdescriptionlist[lastitemindex];
	bigOpts.datetime	= itemdatetimelist[lastitemindex];
	bigOpts.locationName= itemlocationnamelist[lastitemindex];
	bigOpts.id 			= itemidlist[lastitemindex];
	smallOpts.id		= itemidlist[lastitemindex];

	bigOpts.itemType	= itemtypelist[lastitemindex];
	bigOpts.itemFilename= itemfilenamelist[lastitemindex];
    bigOpts.itemUserAvatarFilename = itemuseravatarfilenamelist[lastitemindex];
	bigOpts.ownerID = owneridlist[lastitemindex];
	bigOpts.ownerDisplayName= usernamelist[lastitemindex];
	bigOpts.tab = tab;
	smallOpts.itemType	= itemtypelist[lastitemindex];
	smallOpts.itemFilename= itemfilenamelist[lastitemindex];
	smallOpts.ownerID	= owneridlist[lastitemindex];
	smallOpts.ownerDisplayName= usernamelist[lastitemindex];
	smallOpts.tab = tab;

	bigmarkers[lastitemindex] = new LabeledMarker(itemlatlnglist[lastitemindex],bigOpts);
	smallmarkers[lastitemindex] = new LabeledMarker(itemlatlnglist[lastitemindex],smallOpts);

	map.addOverlay(bigmarkers[lastitemindex]);
	bigmarkers[lastitemindex].hide();
	map.addOverlay(smallmarkers[lastitemindex]);

	markerCount++;

	if(lastitemindex == indexlist[indexlist.length-1]){
		isNewestItemIndexPopup = false;
		if(closebigMarkerTimer == 0){
			if(tab == 'public'){
				delayCloseBigMarker(owneridlist[lastitemindex]+itemtypelist[lastitemindex],10000);
			}else{
				delayCloseBigMarker(itemidlist[lastitemindex]+itemtypelist[lastitemindex],10000);
			}
		}
	}
	if(bigmarkers[bigMarkerPopupIndex] != undefined){
		if(!bigmarkers[bigMarkerPopupIndex].isHidden()){
			ensureMarkerIsVisible(bigMarkerPopupIndex,'popup');
		}
	}
}

function addPhotoMarker(index){
	if(isInitializing == true) return;
	lastitemindex = index;

	bigOpts.title 		= itemtitlelist[lastitemindex];
	smallOpts.title		= itemtitlelist[lastitemindex];
	bigOpts.description = itemdescriptionlist[lastitemindex];
	bigOpts.datetime	= itemdatetimelist[lastitemindex];
	bigOpts.locationName= itemlocationnamelist[lastitemindex];
	bigOpts.id 			= itemidlist[lastitemindex];
	smallOpts.id		= itemidlist[lastitemindex];

	bigOpts.itemType	= itemtypelist[lastitemindex];
	bigOpts.itemFilename= itemfilenamelist[lastitemindex];
    bigOpts.itemUserAvatarFilename = itemuseravatarfilenamelist[lastitemindex];
	bigOpts.ownerID		= owneridlist[lastitemindex];
	bigOpts.ownerDisplayName= usernamelist[lastitemindex];
	bigOpts.tab = tab;
	smallOpts.itemType	= itemtypelist[lastitemindex];
	smallOpts.itemFilename= itemfilenamelist[lastitemindex];
	smallOpts.ownerID	= owneridlist[lastitemindex];
	smallOpts.ownerDisplayName= usernamelist[lastitemindex];
	smallOpts.tab = tab;

	bigmarkers[lastitemindex] = new LabeledMarker(itemlatlnglist[lastitemindex],bigOpts);
	smallmarkers[lastitemindex] = new LabeledMarker(itemlatlnglist[lastitemindex],smallOpts);

	map.addOverlay(bigmarkers[lastitemindex]);
	bigmarkers[lastitemindex].hide();
	map.addOverlay(smallmarkers[lastitemindex]);

	markerCount++;

	isNewestItemIndexPopup = false;
	if(closebigMarkerTimer == 0){
		if(tab == 'public'){
			delayCloseBigMarker(owneridlist[lastitemindex]+itemtypelist[lastitemindex],10000);
		}else{
			delayCloseBigMarker(itemidlist[lastitemindex]+itemtypelist[lastitemindex],10000);
		}
	}

	if(bigmarkers[bigMarkerPopupIndex] != undefined){
		if(!bigmarkers[bigMarkerPopupIndex].isHidden()){
			ensureMarkerIsVisible(bigMarkerPopupIndex,'popup');
		}
	}
}

function openInfoPane(index,delay){
	if(isInitializing == true) return;
	clearTimeout(closebigMarkerTimer);
	
	if(tab == 'public'){
		for(var i = 0; i < indexlist.length; i++){
			if(owneridlist[indexlist[i]]+itemtypelist[indexlist[i]] == index){
				index = indexlist[i];
				break;
			}
		}
	}

	if(bigMarkerPopupIndex != index){
		if(bigmarkers[bigMarkerPopupIndex] != undefined){
			bigmarkers[bigMarkerPopupIndex].hide();
			if(smallmarkers[bigMarkerPopupIndex]!=undefined){
				smallmarkers[bigMarkerPopupIndex].show();
			}
		}
		bigMarkerPopupIndex = index;

		panTo(bigMarkerPopupIndex);
		ensureMarkerIsVisible(bigMarkerPopupIndex,'popup');
		bigmarkers[bigMarkerPopupIndex].show();
		smallmarkers[bigMarkerPopupIndex].hide();
	}

	for(var i = 0; i < infopaneimglist.length; i++){
		if(infopaneimglist[i].id.substring(14) == bigMarkerPopupIndex){
			infopaneimglist[i].className = "selected";
		}else{
			infopaneimglist[i].className = "normal";
		}
	}

	if(effectmove) effectmove.cancel();
	var length = isNormalMap==true ? (parseInt($("map").getStyle('left')) + $("map").getWidth() + parseInt($("map_wrapper").getStyle('borderLeftWidth')) - parseInt($("infopane_wrapper").getStyle('left'))) - (parseInt($("infopane").getStyle('width')) + parseInt($("infopane").getStyle('paddingLeft')) + parseInt($("infopane").getStyle('paddingRight')) + parseInt($("infopane").getStyle('marginLeft'))) : (getDocumentWidth() + parseInt($("map_wrapper").getStyle('borderLeftWidth')) - parseInt($("infopane_wrapper").getStyle('left'))) - (parseInt($("infopane").getStyle('width')) + parseInt($("infopane").getStyle('paddingLeft')) + parseInt($("infopane").getStyle('paddingRight')) + parseInt($("infopane").getStyle('marginLeft')))
	effectmove = new Effect.Move("infopane_wrapper",{x:length,y:0,duration:0.5});

	$('itemid').innerHTML = itemidlist[bigMarkerPopupIndex];
	$('itemtype').innerHTML = itemtypelist[bigMarkerPopupIndex];
	$('itemtitle').innerHTML = itemtitlelist[bigMarkerPopupIndex];
	$('itemdatetime').innerHTML = itemdatetimelist[bigMarkerPopupIndex];
	$('itemlocationname').innerHTML = itemlocationnamelist[bigMarkerPopupIndex];
	$('itemdescription').innerHTML = itemdescriptionlist[bigMarkerPopupIndex];
	$('itemtags').innerHTML = itemtagslist[bigMarkerPopupIndex];

	if(viewerid != 0){
		$('txtcomment').value = '';
		$('commentresult').innerHTML = '';
	}

	closebigMarkerTimer = setTimeout(function(){
		//bigmarkers[bigMarkerPopupIndex].hide();
		//ensureMarkerIsVisible(bigMarkerPopupIndex,'normal');
		closebigMarkerTimer = 0;
		if(bigMarkerPopupIndex != lastitemindex && !isNewestItemIndexPopup){
			isNewestItemIndexPopup = true;
			delayCloseBigMarker(itemidlist[lastitemindex],10000);
		}

		if(effectmove) effectmove.cancel();
		var length = isNormalMap==true ? (parseInt($("map").getStyle('left')) + $("map").getWidth() + parseInt($("map_wrapper").getStyle('borderLeftWidth')) - parseInt($("infopane_wrapper").getStyle('left'))) : getDocumentWidth() - parseInt($("infopane_wrapper").getStyle('left'))
		effectmove = new Effect.Move("infopane_wrapper",{x:length,y:0,duration:0.5});
		
	},delay);
}

function closeBigMarker(){
	if(isInitializing == true) return;
	bigmarkers[bigMarkerPopupIndex].hide();
	ensureMarkerIsVisible(bigMarkerPopupIndex,'normal');
	closeInfoPane();
}

function closeInfoPane(){
	if(isInitializing == true) return;
	clearTimeout(closebigMarkerTimer);

	if(effectmove) effectmove.cancel();
	var length = isNormalMap==true ? (parseInt($("map").getStyle('left')) + $("map").getWidth() + parseInt($("map_wrapper").getStyle('borderLeftWidth')) - parseInt($("infopane_wrapper").getStyle('left'))) : getDocumentWidth() - parseInt($("infopane_wrapper").getStyle('left'))
	effectmove = new Effect.Move("infopane_wrapper",{x:length,y:0,duration:0.5});

	//bigmarkers[bigMarkerPopupIndex].hide();
	//ensureMarkerIsVisible(bigMarkerPopupIndex,'normal');
	closebigMarkerTimer = 0;
	if(bigMarkerPopupIndex != lastitemindex && !isNewestItemIndexPopup){
		isNewestItemIndexPopup = true;
		delayCloseBigMarker(itemidlist[lastitemindex],10000);
	}
}

function delayCloseBigMarker(index,delay){
	if(isInitializing == true) return;
	clearTimeout(closebigMarkerTimer);
	
	if(tab == 'public'){
		for(var i = 0; i < indexlist.length; i++){
			if(owneridlist[indexlist[i]]+itemtypelist[indexlist[i]] == index){
				index = indexlist[i];
				break;
			}
		}
	}

	if(smallmarkers[index] != undefined){
		if(bigmarkers[bigMarkerPopupIndex] != undefined){
			bigmarkers[bigMarkerPopupIndex].hide();
			if(smallmarkers[bigMarkerPopupIndex]!=undefined){
				smallmarkers[bigMarkerPopupIndex].show();
			}
		}
		bigMarkerPopupIndex = index;
	
		panTo(bigMarkerPopupIndex);
		ensureMarkerIsVisible(bigMarkerPopupIndex,'popup');
		bigmarkers[bigMarkerPopupIndex].show();
		smallmarkers[bigMarkerPopupIndex].hide();

		if(effectmove) effectmove.cancel();
		var length = isNormalMap==true ? (parseInt($("map").getStyle('left')) + $("map").getWidth() + parseInt($("map_wrapper").getStyle('borderLeftWidth')) - parseInt($("infopane_wrapper").getStyle('left'))) : getDocumentWidth() - parseInt($("infopane_wrapper").getStyle('left'))
		effectmove = new Effect.Move("infopane_wrapper",{x:length,y:0,duration:0.5});

		if(bigMarkerPopupIndex == lastitemindex) isNewestItemIndexPopup = true;
	}

	closebigMarkerTimer = setTimeout(function(){
		//bigmarkers[bigMarkerPopupIndex].hide();
		//ensureMarkerIsVisible(bigMarkerPopupIndex,'normal');
		closebigMarkerTimer = 0;
		if(bigMarkerPopupIndex != lastitemindex && !isNewestItemIndexPopup){
			isNewestItemIndexPopup = true;
			delayCloseBigMarker(itemidlist[lastitemindex],10000);
		}
	},delay);
    $("map-loading").style.display = "none";
}

function panTo(index){
	if(isInitializing == true) return;
	if(smallmarkers[index] != undefined)smallmarkers[index].openExtInfoWindow(map,"dummy_info_window","<div style='height:300px'></div>'",{beakOffset: 0, paddingLeft: 20, paddingBottom: 50, isNormalMap: true});
	map.closeExtInfoWindow();
}

function ensureMarkerIsVisible(index,mode){
	if(isInitializing == true) return;
	if(smallmarkers[index] != undefined){
		var p0 = map.fromDivPixelToLatLng(new GPoint(0,0));
		if(mode=='popup'){
			for(var i = 0; i < indexlist.length; i++){
				if(indexlist[i] != index){
					if(smallmarkers[indexlist[i]] != undefined)smallmarkers[indexlist[i]].show();
				}
			}
			var pBig = map.fromDivPixelToLatLng(new GPoint(bigMarkerBgrndWidth,bigMarkerBgrndHeight));
			var pSmall = map.fromDivPixelToLatLng(new GPoint(smallMarkerBgrndWidth,smallMarkerBgrndHeight));

			var latBig = Math.abs((p0.lat()-pBig.lat()));
			var latSmall = Math.abs((p0.lat()-pSmall.lat()));
			var lngBig = Math.abs((p0.lng()-pBig.lng()));
			var lngSmall = Math.abs((p0.lng()-pSmall.lng()));

			var pIndex = smallmarkers[index].getLatLng();

			for(var i = 0; i < indexlist.length; i++){
				if(indexlist[i] != index){
					if(smallmarkers[indexlist[i]] != undefined){
						var pI = smallmarkers[indexlist[i]].getLatLng();
						var dLat = pI.lat() - pIndex.lat();
						var dLng = pI.lng() - pIndex.lng();
						if(dLat < 0){
							dLat = Math.abs(dLat) < latSmall ? true:false;
						}else{
							dLat = Math.abs(dLat) < latBig ? true:false;
						}
						if(dLng < 0){
							dLng = Math.abs(dLng) < lngSmall ? true:false;
						}else{
							dLng = Math.abs(dLng) < latBig ? true:false;
						}
						if(dLat && dLng){
							smallmarkers[indexlist[i]].hide();
						}
					}
				}
			}
		}else{
			for(var i = 0; i < indexlist.length; i++){
				if(smallmarkers[indexlist[i]] != undefined)smallmarkers[indexlist[i]].show();
			}
			/*//this is to hide smallmarkers nearby smallmarkers[index].
			var pSmall = map.fromDivPixelToLatLng(new GPoint(smallMarkerBgrndWidth,smallMarkerBgrndHeight));

			var latSmall = Math.abs((p0.lat()-pSmall.lat()));
			var lngSmall = Math.abs((p0.lng()-pSmall.lng()));

			var pIndex = smallmarkers[index].getLatLng();

			for(var i = 0; i < indexlist.length; i++){
				if(indexlist[i] != index){
					if(smallmarkers[indexlist[i]] != undefined){
						var pI = smallmarkers[indexlist[i]].getLatLng();
						var dLat = pI.lat() - pIndex.lat();
						var dLng = pI.lng() - pIndex.lng();
						dLat = Math.abs(dLat) < latSmall ? true:false;
						dLng = Math.abs(dLng) < lngSmall ? true:false;
						if(dLat && dLng){
							smallmarkers[indexlist[i]].hide();
						}
					}
				}
			}*/
		}
	}
}

function updatePhoto(result){
	if(isInitializing == true) return;
	var index = tab == 'public' ? result.ItemOwnerID[0]:""+result.ItemID[0];
	index += result.ItemType[0];

	if(smallmarkers[index] == undefined){
		if(markerCount >= defaultnUser){
			if(bigMarkerPopupIndex == infopaneimglist[0].id.substring(14)){
				clearTimeout(closebigMarkerTimer);
				ensureMarkerIsVisible(bigMarkerPopupIndex,'normal');
				closebigMarkerTimer = 0;
				if(effectmove) effectmove.cancel();
				var length = isNormalMap==true ? (parseInt($("map").getStyle('left')) + $("map").getWidth() + parseInt($("map_wrapper").getStyle('borderLeftWidth')) - parseInt($("infopane_wrapper").getStyle('left'))) : getDocumentWidth() - parseInt($("infopane_wrapper").getStyle('left'))
				effectmove = new Effect.Move("infopane_wrapper",{x:length,y:0,duration:0.5});
			}
			$('infopane_imgcontainer').removeChild(infopaneimglist[0]);
			infopaneimglist.shift();

			var tobeRemovedIndex = indexlist[0];
			indexlist.shift();
			map.removeOverlay(smallmarkers[tobeRemovedIndex]);
			smallmarkers[tobeRemovedIndex] = undefined;
			map.removeOverlay(bigmarkers[tobeRemovedIndex]);
			bigmarkers[tobeRemovedIndex] = undefined;

			if(preloaditemlist[tobeRemovedIndex]) preloaditemlist[tobeRemovedIndex] = null;
			if(preloadthumblist[tobeRemovedIndex]) preloadthumblist[tobeRemovedIndex] = null;

			markerCount--;
		}
	}else{
		for(var i = 0; i < indexlist.length; i++){
			if(indexlist[i] == index){
				for(var j = 0; j < infopaneimglist.length; j++){
					if(index == infopaneimglist[j].id.substring(14)){
						if(index == bigMarkerPopupIndex){
							clearTimeout(closebigMarkerTimer);
							ensureMarkerIsVisible(bigMarkerPopupIndex,'normal');
							closebigMarkerTimer = 0;
							if(effectmove) effectmove.cancel();
							var length = isNormalMap==true ? (parseInt($("map").getStyle('left')) + $("map").getWidth() + parseInt($("map_wrapper").getStyle('borderLeftWidth')) - parseInt($("infopane_wrapper").getStyle('left'))) : getDocumentWidth() - parseInt($("infopane_wrapper").getStyle('left'));
							effectmove = new Effect.Move("infopane_wrapper",{x:length,y:0,duration:0.5});
						}
						$('infopane_imgcontainer').removeChild(infopaneimglist[j]);
						infopaneimglist.splice(j,1);
						break;
					}
				}

				indexlist.splice(i,1);
				map.removeOverlay(smallmarkers[index]);
				smallmarkers[index] = undefined;
				map.removeOverlay(bigmarkers[index]);
				bigmarkers[index] = undefined;

				if(preloaditemlist[index]) preloaditemlist[index] = null;
				if(preloadthumblist[index]) preloadthumblist[index] = null;

				markerCount--;
				break;
			}
		}
	}

	usernamelist[index] = result.ItemUserDisplayName[0];
	owneridlist[index] = result.ItemOwnerID[0];
	itemidlist[index] = result.ItemID[0];
	itemtitlelist[index] = result.ItemTitle[0]!='' ? result.ItemTitle[0]:'&nbsp';
	itemdescriptionlist[index] = result.ItemDescription[0]!='' ? result.ItemDescription[0]:'&nbsp';
	itemlocationnamelist[index] = result.ItemLocationName[0];
	itemlatlnglist[index] = new GLatLng(Number(result.ItemLat[0]),Number(result.ItemLng[0]));
	itemtypelist[index] = result.ItemType[0];
	itemdatetimelist[index] = result.ItemDateTime[0];
	itemtagslist[index] = result.ItemTags[0]!='' ? result.ItemTags[0]:'&nbsp';
	itemfilenamelist[index] = itemtypelist[index]=="photo" ? result.ItemFilename[0]:result.ItemFilename[0].substring(0,result.ItemFilename[0].lastIndexOf("."));
    itemuseravatarfilenamelist[index] = result.ItemUserAvatarFilename[0];

	preloaditemlist[index] = new Image();
	preloaditemlist[index].id = 'preloaditemlist'+index;
	preloaditemlist[index].onload = function(){addPhotoMarker(this.id.substring(15));this.onload = function(){};}
	preloaditemlist[index].src = itemtypelist[index]=="photo" ? photopath_mini+getPhotoPath(owneridlist[index])+"/"+itemfilenamelist[index]:videopngpath_mini+owneridlist[index]+"/"+itemfilenamelist[index]+".png";
	srcthumblist[index] = itemtypelist[index]=="photo" ? photopath_thumb+getPhotoPath(owneridlist[index])+"/"+itemfilenamelist[index]:videopngpath_thumb+owneridlist[index]+"/"+itemfilenamelist[index]+".png";
	preloadthumblist[index] = new Image();
	preloadthumblist[index].onload = function(){};
	preloadthumblist[index].src = srcthumblist[index];

	var infopane_imgcontainer = $('infopane_imgcontainer');
	var img = new Image();
	img.id = "infopane_imgid" + index;
	img.className = "normal";
	img.onclick = function(){
		var index = this.id.substring(14);
		for(var i = 0; i < infopaneimglist.length; i++){
			infopaneimglist[i].className = "normal";
		}
		this.className = "selected";
		panTo(index);
		openInfoPane(index,60000);
	}
	img.src = itemtypelist[index]=="photo" ? photopath_30x30+getPhotoPath(owneridlist[index])+"/"+itemfilenamelist[index]:videopngpath_30x30+owneridlist[index]+"/"+itemfilenamelist[index]+".png";
	img.onload = function(){};

	if(getdatetime == 0){
		indexlist.splice(0,0,index);
		infopane_imgcontainer.insertBefore(img,infopane_imgcontainer.lastChild);
		infopaneimglist.splice(0,0,img);
	}else{
		indexlist.push(index);
		randomItemlist.shift();
		randomItemlist.push([index,itemtypelist[index]]);
		infopane_imgcontainer.insertBefore(img,infopane_imgcontainer.firstChild);
		infopaneimglist.push(img);
	}
	
	if(result.lastItemDateTime != 0){
		lastdatetime = result.lastItemDateTime
	}
	getdatetime = lastdatetime;
}

function setopacity(obj, value){
	var targetobject=obj;
	if(targetobject){
		if(value > 1){
			value = 1;
		}else if(value < 0){
			value = 0;
		}
		var ievalue = value < 0.01 ? 1 : value*100;

		targetobject.style.opacity = value;
		targetobject.style.filter  = "alpha(opacity=" + ievalue + ")";

		targetobject.currentopacity = value;
	}
}

function appendAllItemToInfoPane(){
	if(isInitializing == true) return;
	var infopane_imgcontainer = $('infopane_imgcontainer');

	for(var i = indexlist.length-1; i >= 0; i--){
		var img = new Image();
		img.id = "infopane_imgid" + indexlist[i];
		img.className = "normal";
		img.onclick = function(){
			var index = this.id.substring(14);
			for(var i = 0; i < infopaneimglist.length; i++){
				infopaneimglist[i].className = "normal";
			}
			this.className = "selected";
			panTo(index);
			openInfoPane(index,60000);
		}
		img.src = itemtypelist[indexlist[i]]=="photo" ? photopath_30x30+getPhotoPath(owneridlist[indexlist[i]])+"/"+itemfilenamelist[indexlist[i]]:videopngpath_30x30+owneridlist[indexlist[i]]+"/"+itemfilenamelist[indexlist[i]]+".png";
		img.onload = function(){};

		infopane_imgcontainer.appendChild(img);
		infopaneimglist.push(img);
	}
	var div = document.createElement('div');
	div.className = 'clear';
	infopane_imgcontainer.appendChild(div);
	infopaneimglist.reverse();
}
//begin comment
var loadingimg = new Image();
loadingimg.src = '/static/v2p/images/shadowbox_mac_loading.gif';

function commentsubmit(){
	if(isInitializing == true) return;
	if(viewerid !=0){
		var txtcomment = $('txtcomment');
		if(txtcomment.value=='') return;
		var posttext = encodeURIComponent(txtcomment.value);
		showElement("postingimg");
		if($('itemtype').innerHTML == 'photo'){
			var opt = {
					method: 'post',
					postBody: 'photoid=' + $('itemid').innerHTML + '&userid=' + viewerid + '&text=' + posttext,
					onSuccess: function(t) {
						$('commentresult').innerHTML = _('The comment is posted');
						$('txtcomment').value = "";
						hideElement("postingimg");
					},
					onFailure: function(t) {
						$('commentresult').innerHTML = _("Post comment fail");
						hideElement("postingimg");
					}
				  }
			new Ajax.Request('/photo/PostPhotoComment', opt);
		}else{
			var opt = {
					method: 'post',
					postBody: 'videoid=' + $('itemid').innerHTML + '&userid=' + viewerid + '&text=' + posttext,
					onSuccess: function(t) {
						$('commentresult').innerHTML = _('The comment is posted');
						$('txtcomment').value = "";
						hideElement("postingimg");
					},
					onFailure: function(t) {
						$('commentresult').innerHTML = _('Post comment fail');
						hideElement("postingimg");
					}
				  }
			new Ajax.Request('/video/PostVideoComment', opt);
		}
	}
}
//end comment

//begin place
var placeIcon = new GIcon();
placeIcon.iconSize = new GSize(0, 0);
placeIcon.iconAnchor = new GPoint(0, 0);
var placeOpts	= {icon: placeIcon, labelText: "", labelOffset: "", labelType: "place", title: "", id: "", width:"", height:"", clickable:false};

function parsePlaceInformation(result){
	placeidlist = result.PlaceID;
	lastPlaceID = placeidlist[placeidlist.length-1];
	getPlaceID = lastPlaceID + 1;
	for (i = 0; i < placeidlist.length; i++)
	{
		placeinfolist[placeidlist[i]] = "<b>"+result.PlaceTitle[i]+"</b>:<br/>"+result.PlaceDescription[i]+"<br/><a href='"+result.PlaceLink[i]+"' target='_blank'>readmore</a>";
		placelatlnglist[placeidlist[i]] = new GLatLng(Number(result.PlaceLat[i]),Number(result.PlaceLng[i]));
		placefilenamelist[placeidlist[i]] = result.PlaceFilename[i];
	}
}

function appendAllPlaceMarker(){
	for(var i = 0; i < placeidlist.length; i++){
		addPlaceMarker(placeidlist[i]);
	}
}

function handlePlaceChange() {
	pl = loadJSONDoc("/placeonmap",{getPlaceID: getPlaceID, r: Math.random()});
	pl.addCallback(handlePlaceCallback);
}

function handlePlaceCallback(result) {
	if(result.PlaceCount > 0){
		updatePlaceInformation(result);
	}
	updatePlaceTimer = setTimeout("handlePlaceChange()",60000);
}

function updatePlaceInformation(result){
	for (i = 0; i < result.PlaceCount; i++)
	{
		var placeid = result.PlaceID[i];
		placeidlist.push(placeid);

		placeinfolist[placeid] = "<b>"+result.PlaceTitle[i]+"</b>:<br/>"+result.PlaceDescription[i]+"<br/><a href='"+result.PlaceLink[i]+"' target='_blank'>readmore</a>";
		placelatlnglist[placeid] = new GLatLng(Number(result.PlaceLat[i]),Number(result.PlaceLng[i]));
		placefilenamelist[placeid] = result.PlaceFilename[i];

		addPlaceMarker(placeid);
		lastPlaceID = placeid;
	}
	getPlaceID = lastPlaceID + 1;
}

function addPlaceMarker(id){
	var img = document.createElement("img");
	img.id = 'placemarker'+id;
	img.src = "/static/images/marker/places/"+placefilenamelist[id];
	img.onload = function(){
		placeOpts.labelText	= this.src;
		placeOpts.title		= placefilenamelist[this.id.substring(11)];
		placeOpts.id		= this.id;
		placeOpts.labelOffset = new GSize(-this.width/2,-this.height*0.8);
		placeOpts.width = this.width;
		placeOpts.height = this.height;

		placemarkers[this.id.substring(11)] = new LabeledMarker(placelatlnglist[this.id.substring(11)],placeOpts);
		map.addOverlay(placemarkers[this.id.substring(11)]);

		this.onload = function(){}; // clear onload for IE
	}
}

function openPlaceInfoWindow(img){
	placeIcon.infoWindowAnchor = new GPoint(68, -img.height*0.6);//68=137/2
	placemarkers[img.id.substring(11)].openExtInfoWindow(
		map,
		"opacity_window",
		"<div>"+
		placeinfolist[img.id.substring(11)]+
		"</div>",
		{beakOffset: 3, paddingLeft: 20+img.width*0.6, paddingBottom: img.height*0.2, isNormalMap: isNormalMap}
	);
}
//end place
