 var delta = 0;
 var mdownXPos = -1;
 var mdownYPos = -1;
 var deltaX = 0;
 var deltaY = 0;
 var loading = false;
 var panning = false;
 var endedDrag = false;
 var googleLoaded = false;
 var opacity= 1;
 var schmapme = {};
 schmapme.maptypes = {'m': 'map', 's': 'satellite'}
 schmapme.userType = 't';
 var b_version = navigator.appVersion;
 var isIE6 = b_version.search(/MSIE 6/i) != -1;
 var isIE = b_version.search(/MSIE/i) != -1;
 var isSafari = b_version.search(/applewebkit/i) != -1;
 schmapme.cursorArray = ['zoomin', 'zoomout', 'mapview', 'satelliteview', 'mapimg'];
 schmapMapType = {
      'map':['mapselected','satellite'],
	 'satellite':['map','satelliteselected']
 }
 schmapme.intervalprocess = true;
 function $(id){   
    return document.getElementById(id);   
}

function getElement(src) {
    if(typeof(src) == 'string')
    src = $(src);
    return src;
}

function getFlashMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}
function addScript(url) {
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.language = "javascript";
    s.src = url;
    document.getElementsByTagName("head")[0].appendChild(s);    
}

function getCsurrentGMapUrl() {
    return "http://"+mapdomain+".google.com/maps?file=api&v=21&key=" +
        google_api_key + '&async=2&callback=loadedGMap';
}  

function connect(src, sig, objOrFunc){
    src = getElement(src);
    if (src.addEventListener) {
       src.addEventListener(sig.substr(2), objOrFunc, false);
    } else if (src.attachEvent) {
        src.attachEvent(sig, objOrFunc); 
    }
}

function loadGoogle() {
    if (!googleLoaded) {
        googleLoaded = true;
      //  $('map').innerHTML = '<img id="maploading" src="/images/loading-map.gif" />';
        addScript(getCsurrentGMapUrl());
    }
}

function getMWheelDelta(event) {
   
    if (!event) { // For IE.
        event = window.event;
    }
    if (event.wheelDelta) { // IE/Opera.
        delta += event.wheelDelta/120;
        // In Opera 9, delta differs in sign as compared to IE.
        if (window.opera)
            delta = -delta;
    } else if (event.detail) { // Mozilla case.
        // In Mozilla, sign of delta is different than in IE. Also, delta is multiple of 3.
        delta += (-event.detail/3);
    }
    if (!loading) {
      document.body.style.cursor = "wait";
    setCursor(schmapme.cursorArray, 'wait');
    setTimeout("loadGoogle()", 500); 
    loading = true;
    }
}

function zoominout(event) {
    if (!event) { // For IE.
        event = window.event;
    }
    var target = event.target || event.srcElement;
    var id = target.id;
    if(id =="zoomin"){
        delta++;
    }else {
        delta--;
    }
    if (schmapme.map) {
        schmapme.map.setZoom(zoomLevel+delta);
    } else {  
    document.body.style.cursor = "wait";
    setCursor(schmapme.cursorArray, 'wait');
        setTimeout("loadGoogle()", 500); 
    }
}

function handleMouseDown(event) {
    if (!panning) {
        mdownXPos = event.screenX;
        mdownYPos = event.screenY;
        panning = true;
    }
    
}

function handleDragStart(event) {
    if (!panning) {
        mdownXPos = event.screenX;
        mdownYPos = event.screenY;
        panning = true;
    }
}

function handleDragEnd(event) {
    endedDrag = true;
}

function handleDragEndIE(event) {
    endedDrag = true;
}

function handleMouseMove(event) {
    if (endedDrag) {
        if (mdownXPos >= 0 && mdownYPos >= 0) {
            deltaX = event.screenX - mdownXPos;
            deltaY = event.screenY - mdownYPos;
            document.body.style.cursor = "wait";
            setCursor(schmapme.cursorArray, 'wait');
            setTimeout("loadGoogle()", 200); 
        }
    }
}

function switchMapView(event) {
    var target = event.target || event.srcElement;
    var id = target.id;
    var oldview = schmapme.mapview;
    if(schmapme.mapview +'view' ==  id) return;
    var othersrc = "/images/" + localLangDir + schmapme.mapview + ".png";
    schmapme.mapview = id.replace('view','');
    var src = "/images/" + localLangDir + schmapme.mapview + "selected.png";
    var filter = PNG_style({src: src, width: 55, height: 18});
    atherfilter = PNG_style({src: othersrc, width: 55, height: 18});
    if(isIE6){
        $(oldview + 'view').style.filter = atherfilter;
        target.style.filter= filter;
    }else{
        $(oldview + 'view').src = othersrc;
        target.src = src;
    }
    if (schmapme.map ) {
        schmapme.map.setMapType(schmapme._mt[schmapme.mapview]);
    }else {
        document.body.style.cursor = "wait";
        setCursor(schmapme.cursorArray, 'wait');
        setTimeout("loadGoogle()", 200); 
    }
}

function setCursor(objs,cursor){
    for(var i = 0; i < objs.length; i ++){
       obj = $(objs[i]); 
       obj.style.cursor = cursor;
    }
}

function loadedGMap() { 
    $('mapimg').style.cursor ="wait";
    schmapme.map =  new GMap2($('map'));
    schmapme.map.enableDoubleClickZoom();
    schmapme.map.enableContinuousZoom();
    schmapme.map.enableScrollWheelZoom();
    schmapme.map.addControl(new GScaleControl());
    var center = new GLatLng(lat, lng);
    schmapme.map.setCenter(center, zoomLevel);    
    if(schmapme_bigIconPath && schmapme_bigIconPath.toLowerCase() != '(none)'){
        var ic =new GIcon();
		if(schmapme_useradded == 'y'){
		    var icondir = '/usericons/';
		}else {
		    var icondir = '/images/mapicons/';
		}
        ic.image = icondir + schmapme_bigIconPath;
        ic.iconSize = new GSize(schmapme_bigIconWidth, schmapme_bigIconHeight);
        ic.iconAnchor = new GPoint(schmapme_bigIconWidth*anchorX/100, 
                                    schmapme_bigIconHeight*anchorY/100);
        var marker = new GMarker(center,{icon:ic});
    } else {
        var marker = new GMarker(center);
    }
    schmapme.map.addOverlay(marker);
    if (delta != 0) {
    schmapme.map.setZoom(zoomLevel+delta);
    }
    var mt = schmapme.map.getMapTypes();
    schmapme._mt = {};
    var mtTypes = ['map', 'satellite', 'hybrid'];
    for(var i = 0; i < mt.length; i++){
        schmapme._mt[mtTypes[i]] = mt[i];
    }
    if(schmapme.mapview){
        schmapme.map.setMapType(schmapme._mt[schmapme.mapview]);
    }
    var index =7;
    if(isIE6) index = 3;
    var googlemapimg = $('map').firstChild.firstChild.childNodes[1].firstChild.childNodes[index];
    googlemapimg.onload = showmap;
    if(googlemapimg.complete) {
        showmap();
    }
}

function showmap() {
    if(schmapme.showmap) return;
	$('mapouter').style.visibility = "visible";
    $('staticmap').style.display = 'none';
    $('mapicon').style.display = 'none';
    $('map').style.visibility = "visible";
    document.body.style.cursor = "default";
    setCursor(schmapme.cursorArray, 'pointer');    
    setTimeout(function(){
                    if (deltaX != 0 || deltaY != 0)    {
                        schmapme.map.panBy (new GSize(deltaX,deltaY));
                    }}, 200);
    schmapme.showmap = true;
}

function setup() {
    if(localLang && localLang =='zh'){
	    localLangDir = 'zh/';
		loadGoogle();
	}else {
	    localLangDir = '';
	}
    schmapme.mapview =maptype;
	if(lat != '0.0' && lng !== '0.0'){
    var zoomin = PNG_html({id: 'zoomin', src: '/images/zoomin.png', width: 18, height: 21});
    var zoomout = PNG_html({id: 'zoomout', src: '/images/zoomout.png', width: 18, height: 21});
    var mapview =  PNG_html({id: 'mapview', src: '/images/' + localLangDir +schmapMapType[schmapme.mapview][0]+'.png', width: 55, height: 18});
    var satelliteview =  PNG_html({id: 'satelliteview', src: '/images/' + localLangDir +schmapMapType[schmapme.mapview][1]+'.png', width: 55, height: 18});
    if(schmapme_useradded == 'y'){
		    var icondir = '/usericons/';
		}else {
		    var icondir = '/images/mapicons/';
		}
    var mapicon =  PNG_html({src: icondir + schmapme_bigIconPath, width: schmapme_bigIconWidth, height: schmapme_bigIconHeight});
    $('zoominout').innerHTML = zoomin + zoomout;
    $('mapswitch').innerHTML = mapview + satelliteview;
    if(schmapme_bigIconPath && schmapme_bigIconPath.toLowerCase() != '(none)'){
		$('mapicon').innerHTML = mapicon;
		$('mapicon').style.top = (191 - schmapme_bigIconHeight*anchorY/100) + 'px';
		$('mapicon').style.left = (191  - schmapme_bigIconWidth*anchorX/100) + 'px'
	}
    connect('mapimg', 'onmousedown', handleMouseDown);
    connect('mapimg', 'ondragstart', handleDragStart);
    connect('mapimg', 'onmousemove', handleMouseMove);
    connect('mapimg', 'onmouseup', handleDragEnd);
    connect('mapimg', 'ondragend', handleDragEndIE);
    connect('mapimg', 'ondragexit', handleDragEnd);
    connect('mapview', 'onclick', switchMapView);
    connect('satelliteview', 'onclick', switchMapView);
    connect('zoomin', 'onclick', zoominout);
    connect('zoomout', 'onclick', zoominout);
    if ($('mapimg').addEventListener)
        $('mapimg').addEventListener('DOMMouseScroll', getMWheelDelta, false);
    else {
        connect('mapimg', 'onmousewheel', getMWheelDelta);
    }
	}
  if($('activeflash')) {
  document.body.style.overflow = 'hidden';
  //$('overlay').style.height = document.body.clientHeight + "px";
  }

 }
function getTextFromFlash(n){
alert(n);
}
function closePage(){
	$('overlay').style.display = "none";
}
function flashDelete(){
	alert('Deleted');
}
 
 function gotoCustomizeBadge(){
    if(schmapme_bigIconPath !=="(none)"){
     var iconcode = schmapme_bigIconPath.substr(0,4).toUpperCase();
	 }else {
	 var iconcode = "G000";
	 }
    var url = 'http://' + document.location.host  + '/present/index_badge.html?url=' + userUrl + '&lat=' + lat + '&long=' + lng + '&icon=' + iconcode + '&zoom=' + zoomLevel + '&maptype=' + maptype;
    // alert(url);
 
	
	 //var fl = getFlashMovie('schmapme').callFlashFunction(url);
	return url;
 
 }


function nobigphoto(evt){
    evt.style.display = 'none';
}

function bigphotoloaded(evt){
    schmapme.intervalinitws = $('smalphoto').clientWidth;
	schmapme.intervalinitwb = evt.clientWidth;
	schmapme.intervalw = schmapme.intervalinitws
    evt.style.width = schmapme.intervalinitws + 'px';
	evt.parentNode.style.width = schmapme.intervalinitws + 'px';
   // 
	schmapme.intervalprocess = false;
	//
 
	schmapme.intervalele =evt;

	if (isIE6) {
	var cursor = '/images/zoom.cur';
	 
	}else if(isSafari || isIE){
	var cursor = 'url(/images/zoomsafari.cur)';
	} else {
	var cursor = '-moz-zoom-in';
	}
	$('smalphoto').style.cursor = cursor;
}

 function enlargephoto(evt){
	if(schmapme.intervalprocess) return;
	if (isIE6) {
	var cursor = 'default';
    $('smalphoto').style.cursor = cursor;
	schmapme.intervalele.style.cursor = cursor;
	}
	if(schmapme.enlarged ){

	schmapme.interval = setInterval(scalephotos,10);
	$('infotext').style.display = 'block';

	}else {
	schmapme.interval = setInterval(scalephoto,10);	
	 schmapme.intervalele.parentNode.style.visibility = 'visible';
	 schmapme.intervalele.parentNode.style.top = '24px';
    $('smalphoto').style.visibility = 'hidden';

	}
	schmapme.intervalprocess = true;
}

function scalephoto(){
    schmapme.intervalw +=6
	if(schmapme.intervalw >= schmapme.intervalinitwb){
	    schmapme.intervalw = schmapme.intervalinitwb;
		clearInterval(schmapme.interval);
		schmapme.enlarged = true;
		$('infotext').style.display = 'none';
		schmapme.intervalprocess = false;
 		if (isIE6) {
		var cursor = '/images/zoomout.cur';
		schmapme.intervalele.style.cursor = cursor;
		} 
	}
	opacity-=0.06
	try{
	$('infotext').filters.alpha.opacity = opacity*100;
	$('infotext').style.opacity = opacity;
	
	}catch(e){}
    schmapme.intervalele.style.width = schmapme.intervalw +'px';
    schmapme.intervalele.parentNode.style.width = schmapme.intervalw +'px';
}
function scalephotos(){
    schmapme.intervalw -=6
	//console.log(schmapme.intervalw);
	if(schmapme.intervalw <= schmapme.intervalinitws){
	    schmapme.intervalw = schmapme.intervalinitws;
		clearInterval(schmapme.interval);
		schmapme.enlarged = false;
		schmapme.intervalprocess = false;
		$('smalphoto').style.visibility = 'visible';
		schmapme.intervalele.parentNode.style.visibility = 'hidden';
		if (isIE6) {
		var cursor = '/images/zoom.cur';
		$('smalphoto').style.cursor = cursor;
		}else if(isSafari){
		var cursor = 'url(/images/zoomsafari.cur)';
		$('smalphoto').style.cursor = cursor;
		}

	} 
	opacity+=0.06
	try{ 
	$('infotext').filters.alpha.opacity = opacity*100
    $('infotext').style.opacity = opacity;
   
	}catch(e){
	}
  schmapme.intervalele.style.width = schmapme.intervalw +'px';
  schmapme.intervalele.parentNode.style.width = schmapme.intervalw +'px';
}
function PNG_html(attrs) {9
    var img = new StringBuffer();
    var src = attrs.src;
    if(isIE6)
        attrs.src = '/common/spacer.png';
    img.append('<img ');
    if(attrs.id)
        img.append('id="').append(attrs.id).append('" ');
    if(attrs.thisClass)
        img.append('class="').append(attrs.thisClass).append('" ');
    img.append('src="').append(attrs.src);
    img.append('" width="').append(attrs.width).append('" height="').append(attrs.height).append('"/>');
    if(isIE6) {
        var img = new StringBuffer();
        img.append('<IMG ');
        if(attrs.id)
            img.append('id="').append(attrs.id).append('" ');
        img.append(' style="').append("FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='");
        img.append(src).append("',sizingMethod='scale'); WIDTH: ").append(attrs.width);
        img.append("px; HEIGHT: ").append(attrs.height).append("px");
        if(attrs.thisClass)
            img.append('" class="').append(attrs.thisClass);
        img.append('" src="/images/spacer.png">');
    }
    return img.toString();
}

function PNG_style (attrs){
    var style = new StringBuffer();
    style.append("FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='");
        style.append(attrs.src).append("',sizingMethod='scale'); WIDTH: ").append(attrs.width);
        style.append("px; HEIGHT: ").append(attrs.height).append('px');
        return style.toString();
}

function StringBuffer() { 
    this.buffer = []; 
}

StringBuffer.prototype.append = function(str) {
    this.buffer.push(str);
    return this;
}

StringBuffer.prototype.toString = function() {
    return this.buffer.join("");
}

StringBuffer.prototype.getLength = function() {
    return this.buffer.length;
}
function loadDefaultimage(){
$('photo').src="/images/default_img_" + schmapme.userType + ".png";
}

function gettwitterUser(twitterprofile){
try{
    $('photo').src = twitterprofile.profile_image_url;
	$('profile').style.display = "block";
}catch(e){
    
}
}

function FacebookRestClient(serverAddr, sessionKey, apiKey, secret){
  this._secret=     secret,
  this._sessionKey=   sessionKey,
  this._apiKey=    apiKey,
  this._serverUrl=  serverAddr;      
  this.callMethod = function(method, params){
    var currentTime = new Date();
    var time = currentTime.getTime();
    params.push("method="+method);
    //params.push("session_key="+this._sessionKey);
    params.push("api_key=" + this._apiKey);
    params.push("call_id=" + time);
    params.push("sig=" + this.generateSig(params));
    this.postRequest(this, params);
  }
  
  this.generateSig = function(params){
    var request = "";
    params.sort();
    for(var i=0; i<params.length; i++){
      request+=params[i];
    }
    request+=this._secret;
    return hex_md5(request);
  }
  
  this.postRequest= function(sender, params){
    var requests = "";
    params.sort();
    requests+=params.join('&');
    var sss = this._serverUrl+ '?' + requests;
    var src = '<script src=" '+ sss + '" ><\/script>'
    document.write(src);
   }
  return this;
}

function checkFaceBook(uid){
	var api_key = 'b60af6a0bff69c00024a2255f392cdb7';
	var secret = 'd7fffe5040c75759369ee62b6375aa08';
	var method = "Users.getInfo"

	var arguments  =['uids='+uid,'fields=name,pic_small','v=1.0','format=json','callback=facebookCallBack'];
	var serverAddr = "http://api.facebook.com/restserver.php"
	var facebook = new FacebookRestClient(serverAddr, '', api_key, secret);
	facebook.callMethod(method, arguments);
}
function getUserProfile(name, type,xid){
    schmapme.userType = type.toLowerCase();
    if(schmapme.userType == 't'){
	    if(name !== 'None' && name != "(none)"){
			var url = "http://twitter.com/users/show/"+name+".json?callback=gettwitterUser";
			addScript(url);
		}
	} else if(schmapme.userType == 'f'){
	    if(xid !== 'None' && xid != "(none)" ){
		    checkFaceBook(xid);
		}
	}
}
function facebookCallBack(facebookUser){
    AAA = facebookUser;
    $('photo').src = facebookUser[0].pic_small || "/images/default_img_f.png";
    $('profilename').innerHTML = facebookUser[0].name
	var url = "http://www.facebook.com/profile.php?v=info&edit_info=all#/profile.php?id=" + facebookUser[0].uid+ "&ref=name";
	$('profilename').href = url;
	$('photo').parentNode.href = url;
	$('profile').style.display = "block";
}
function shareTo(web){
	var href = document.location.href.replace(/\/#\w*/,'');
	var name = $('placeName').innerHTML || '';
	//if($('tmsg')){
	//	var d = $('tmsg').innerHTML;
	//}else{
		var d = '';
	//}
	//d = d.replace(/<br\s*\/?>/gi,'\n');
	//d = encodeURIComponent(d);
	name = encodeURIComponent(name);
	var shareToUrl;
	switch(web){
		case 'twitter':
			shareToUrl ="http://twitter.com/home/?status=" + href + '+' + name;
			break;
		case 'facebook':
			shareToUrl = "http://www.facebook.com/share.php?u="+href;
			break;
		case 'xiaonei':
			shareToUrl = "http://share.xiaonei.com/share/ShareOperate.do?action=sharelink&weblink="+href;
			break;
		case 'fanfou':
			shareToUrl = "http://fanfou.com/sharer?u=" + href + "&t=" + name + "&d=" + d+ "&s=bm";
			break;
		case 'jiwai':
			shareToUrl = "http://jiwai.de/wo/share/s?u="+ href + "&t=" + name;
			break;
		case 'kaixin':
			shareToUrl = "http://www.kaixin001.com/repaste/share.php?rurl="+ href + "&rtitle=" + name + "&rcontent=" + href;
			break;
		case 'douban':
			shareToUrl = " http://www.douban.com/recommend/?url="+ href + "&title=" + name + "&sel=" + d + "&v=1";
			break;
		case 'mail':	
			var subject = encodeURIComponent(name + 'µç×ÓµØÍ¼');
			var body = '%0D%0D' + href;
			shareToUrl = 'mailto:?subject=' + subject + '&body=' + body;
			break;
	}
	$(web).parentNode.href = shareToUrl;
}
//window.onload = setup;
