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 googleFinishedLoading = false;
if(typeof(userinfo) === 'undefined'){
    userinfo = {};
}
if(typeof(otherinfo) === 'undefined'){
    otherinfo = {};
}
if(typeof(schmapit) === 'undefined'){
    schmapit = {};
}
var handlers = [];
var encode;
var log = function(r){
	if(typeof(console) !== 'undefined' && console.log){
		console.log(r);
	}
};
if (typeof(encodeURIComponent) != "undefined") {
	encode = encodeURIComponent;
} else {
	encode = unescape;
}

String.prototype.Trim = function () {   
    return this.replace(/^\s+|\s+$/g,'');   
};
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 cssjs(a,o,c1,c2){
	switch (a){
		case 'swap':
			o.className=!cssjs('check',o,c1)?o.className.replace(c2,c1):o.className.replace(c1,c2);
		break;
		case 'add':
			if(!cssjs('check',o,c1)){o.className+=o.className?' '+c1:c1;}
		break;
		case 'remove':
			var rep=o.className.match(' '+c1)?' '+c1:c1;
			o.className=o.className.replace(rep,'');
		break;
		case 'check':
			var found=false;
			var temparray=o.className.split(' ');
			for(var i=0;i<temparray.length;i++){
				if(temparray[i]==c1){found=true;}
			}
			return found;
	}
}

function addScript(url,callback){
	var s = document.createElement("script");
    s.type = "text/javascript";
    s.language = "javascript";
    s.src = url;
	document.body.appendChild(s);
	if(callback){callback(s);}
}

function addStyle(css){
	var style = document.createElement('style');
	style.setAttribute("type", "text/css");
	if(style.styleSheet){// IE
	    style.styleSheet.cssText = css;
	} else {// w3c
		var cssText = document.createTextNode(css);
		style.appendChild(cssText);
	}
	var head = document.getElementsByTagName('head')[0];
	head.appendChild(style);
}

function $(src){   
    if(typeof(src) == 'string'){
        src = document.getElementById(src);
	}
    return src;
}

function showElement(id){
    var elm = id;
    if(typeof id === 'string'){
	    elm = $(id);
	}
	if(elm){
        elm.style.display = 'block';
	}
}

function hideElement(id){
    var elm = id;
    if(typeof id === 'string'){
	    elm = $(id);
	}
	if(elm){
	    elm.style.display = 'none';
	}
}
function tn(tag,parent){
    var elm = parent || document.body;
	return elm.getElementsByTagName(tag);
}
function nextSibling(elm){
    var node = elm.nextSibling;
    return node ? ((node.nodeType === 1) ? node : nextSibling(node)) : null;
}
function prevSibling(elm){
    var node = elm.previousSibling;
    return node ? ((node.nodeType === 1) ? node : prevSibling(node)) : null;
}
function pageX(elem) {
// See if we're at the root element, or not
return elem.offsetParent ?
// If we can still go up, add the current offset and recurse upwards
elem.offsetLeft + pageX( elem.offsetParent ) :
// Otherwise, just get the current offset
elem.offsetLeft;
}
// Find the Y (Vertical, Top) position of an element
function pageY(elem) {
// See if we're at the root element, or not
return elem.offsetParent ?
// If we can still go up, add the current offset and recurse upwards
elem.offsetTop + pageY( elem.offsetParent ) :
// Otherwise, just get the current offset
elem.offsetTop;
}
function connect(src, sig, objOrFunc){
    src = $(src);
    if (src.addEventListener) {
       src.addEventListener(sig.substr(2), objOrFunc, false);
    }else if (src.attachEvent) {
        src.attachEvent(sig, function(e){objOrFunc.call(src,e);}); 
		handlers.push({elm:src,type:sig,fn:objOrFunc});
		//src.sig = objOrFunc;
    }else{
	    src.sig = objOrFunc;
	}
}

function cancelClick(e){
    if(window.event){
			window.event.cancelBubble = true;
			return;
		} else if (e && e.stopPropagation){
			e.stopPropagation();
	}
}
function getCookieVal(offset) {
    var endstr = document.cookie.indexOf (";", offset);
    if (endstr == -1){
        endstr = document.cookie.length;
	}
    return unescape(document.cookie.substring(offset, endstr));
}

function setCookie(name, value) {
    var expdate = new Date();
    var argv = setCookie.arguments;
    var argc = setCookie.arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var path = (argc > 3) ? argv[3] : null;
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
    if(expires != null) 
        expdate.setTime(expdate.getTime() + ( expires * 24 * 3600 * 1000 ));
    var cvalue = name + "=" + escape (value) + 
        ((expires == null) ? "" : ("; expires="+ expdate.toGMTString())) + 
         "; path=/"   +
        ((domain == null) ? "" : ("; domain=" + domain)) + 
        ((secure == true) ? "; secure" : "");
    document.cookie = cvalue;
}

function delCookie(name) {
    var exp = new Date();
  //  exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    document.cookie = name + "=" +cval + "; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=.schmap.it";
}

function getCookie(name) {
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
            return getCookieVal (j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return null;
}

function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ) 
	{
		return null;
	}
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function Set_Cookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
	if ( Get_Cookie( name ) ) document.cookie = name + "=" +
			( ( path ) ? ";path=" + path : "") +
			( ( domain ) ? ";domain=" + domain : "" ) +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
if(typeof XMLHttpRequest === 'undefined'){
	XMLHttpRequest = function(){
		return new ActiveXObject(
			navigator.userAgent.indexOf('MSIE 5') > 0?
			'Microsoft.XMLHTTP':'Msxml2.XMLHTTP'
		);
	};
}
function ajax( options ) {
    options = {
		formData: options.formData || false,
		method:options.method || "get",
        type: options.type || "POST",
        url: options.url || "",
        timeout: options.timeout || 30000,
        onComplete: options.onComplete || function(){},
        onError: options.onError || function(){},
        onSuccess: options.onSuccess || function(){},
		onTimeout:options.onTimeout || function(){
		    overlay.hide();
			topAlert.call('Sorry, some error happended, please try again later!');
		},
        data: options.data || null
    };
    var xml = new XMLHttpRequest();
    xml.open(options.method, options.url, true);
    //var timeoutLength = 5000;  NPF
    var requestDone = false;  
    setTimeout(function(){
         requestDone = true;
    }, options.timeout);  // NPF
    xml.onreadystatechange = function(){
        if ( xml.readyState == 4) {  
		    if(!requestDone){
				if ( httpSuccess( xml ) ) {
					options.onSuccess( httpData( xml, options.type ) );
				} else {
					options.onError(xml);
				}
			}else{
			    options.onTimeout(xml);
			}
            

            options.onComplete();

            xml = null;
        }
    };
	if(options.formData) {
		xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		if(options.data !== null) {xml.setRequestHeader("Content-length", options.data.length);}
		xml.setRequestHeader("Connection", "close");
	}
    xml.send(options.data);
    function httpSuccess(r) {
        try {
            return !r.status && location.protocol == "file:" ||
                ( r.status >= 200 && r.status < 300 ) ||
                r.status == 304 ||
                navigator.userAgent.indexOf("Safari") >= 0 && typeof r.status == "undefined";
        } catch(e){}
        return false;
    }
    function httpData(r,type) {
        var ct = r.getResponseHeader("content-type");
        var data = !type && ct && ct.indexOf("xml") >= 0;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        if ( type == "script" )
            eval.call( window, data );
        return data;
    }
}

var topAlert = {
	stay:7000,
	classname:'top-alert',
    gap: 4,
	t:20,
	h:51,
	opacity:97,
	sliding:false,
	staying:false,
	showing:false,
	hiding:false,
	defaultMsg: 'Twitter did not recognize your username',
	hideCallback:function(){},
	showCallback:function(){},
	inited: false,
	init: function(){
	        if(topAlert.inited){return;}
			var elm = document.createElement('div');
			elm.style.cssText = 'line-height:' + topAlert.h + 
			'px;top:-' + topAlert.h + 'px;';
			elm.className = topAlert.classname;
			elm.title = 'click to hide';
			document.body.appendChild(elm);
			topAlert.e = elm;
			topAlert.step = Math.ceil(topAlert.h/topAlert.gap);
			elm.onclick = function(){
			    if(topAlert.staying){topAlert.hide();}
			};
			this.startPoint = 0;
			if(isIE6){
			    elm.style.position = 'absolute';
				//this.startPoint 
			}
			topAlert.inited = true;
	     },
	call: function(msg,time){
			  msg = msg || topAlert.defaultMsg;
			  time = time || topAlert.stay;
			  topAlert.step = Math.ceil(topAlert.h/topAlert.gap);
			  if(!topAlert.inited){
			      topAlert.init();
			  }
			  topAlert.show(msg,time);
	      },
	show: function(msg,time){
			  var tl = this,
			      elm = tl.e,
				  i = 0,
				  l = tl.step;
			  elm.innerHTML = msg;
			  tl.showing = true;
			  if(tl.staying){
			      tl.e.innerHTML = msg;
				  if(tl.hideInterval){clearInterval(tl.hideInterval);}
				  tl.hideInterval = setTimeout(tl.hide,time);
				  tl.staying = true;
				  tl.showCallback();
				  return;
			  }
			  if(isIE6){
			      this.startPoint = document.documentElement.scrollTop || document.body.scrollTop;
				  this.e.style.top = (this.startPoint - this.h) + 'px';
				  window.onresize = window.onscroll = function(){
				      var tl = topAlert;
					  tl.hide();
					  window.onresize = window.onscroll = null;
				  };
				  //this.startPoint = this.startPoint - topAlert.h;
			  }
			  tl.sliding = true;
			  while(i < l){
			      setTimeout(function(){
				          var tl = topAlert,
						      a = parseInt(tl.e.style.top),
						      b = a + tl.gap;
						  if(b >= tl.startPoint){
						      tl.e.style.top = tl.startPoint + 'px';
							  tl.showing = false;
							  tl.staying = true;
							  tl.hideInterval = setTimeout(tl.hide,time);
							  tl.showCallback();
							  return;
						  }
						  tl.e.style.top = b + 'px';
					  },tl.t*i);
				  i += 1;
			  }
			  
		  },
	hide: function(){
	          var tl = topAlert;
			  if(tl.hideInterval){clearInterval(tl.hideInterval);}
	          var i = 0,
			      l = tl.step;
			  tl.staying = false;
			  tl.hiding = true;
	          while(i < l){
			      setTimeout(function(){
				          var tl = topAlert,
							  a = parseInt(tl.e.style.top),
						      b = a - tl.gap;
						  if(b <= tl.startPoint-tl.h){
						      tl.e.style.top = -tl.h + 'px';
							  tl.hiding =  tl.sliding = false;
							  tl.hideCallback(b);
							  return;
						  }
						  tl.e.style.top = b + 'px';
					  },tl.t*i);
				  i += 1;
			  }
	      }
};
function getWrapperHeight(){
    var doc = document,
	    docElm = doc.documentElement;
	if(docElm && docElm.scrollHeight){
	    return (docElm.scrollHeight - docElm.clientHeight > 0) ? docElm.scrollHeight : docElm.clientHeight;
	}
	return doc.body.scrollHeight;
}
function getViewPortHeight(){
    var doc = document;
	return window.innerHeight || 
	       (doc.documentElement && doc.documentElement.clientHeight) ||
		   doc.body.clientHeight;
}
var overlay = {
    hidecallback:null,
	showcallback:null,
	init: function(){
		if(!this.elm){
			var elm = document.createElement('div');
			elm.className = 'overlay';
			$('overlayparent').appendChild(elm);
			this.elm = elm;
		}
	},
	show: function(options){
		if(!this.elm){
			this.init();
		}
		if(this.showcallback){
			this.showcallback();
			this.showcallback = null;	
		}
		this.elm.style.cssText = 'height:' + getWrapperHeight() + 'px;';
		if(typeof(options) === 'undefined'){return;}
		var popup = options.elm;
		if(popup){
			this.pop = popup;
			var doc = document,
			    scrollTop = doc.documentElement.scrollTop || doc.body.scrollTop,
				top = scrollTop + (getViewPortHeight() - popup.clientHeight)/2;
			popup.style.cssText = 'visibility:visible;;z-index:10000;top:' + top + 'px;margin-left:-' + popup.clientWidth/2 + 'px;'; 
		}
		if(options.clickhide){
		    this.elm.onclick = function(){
			    overlay.hide();
			};
		}else{
		    this.elm.onclick = null;
		}
		if(options.callback){
			options.callback();
		}
		window.onresize = function(){
		    overlay.elm.style.cssText = 'height:' + getWrapperHeight() + 'px;';
		};
	},
	hide: function(callback){
		if(!this.elm){return;}
		this.elm.style.cssText = '';
		if(this.hidecallback){
			this.hidecallback();
			this.hidecallback = null;	
		}
		if(callback){
			callback();
		}
		if(this.pop){
			this.pop.style.cssText = ''; 
			delete this.pop;
		}
		window.onresize =null;
	}
};
var cancel = {isCanceling:false,inputs:[]};
if(typeof(schmap) === 'undefined'){
    schmap = {};
}
if(typeof(schmapit) === 'undefined'){
    schmapit = {};
}
otherinfo.zoomlevel = schmapit.zoomlevel || 14;
otherinfo.adcode = schmapit.adcode || 'edu161-01';
otherinfo.iconcode = schmapit.iconcode || 'A010';
otherinfo.maptype = schmapit.maptype || 'm';
otherinfo.latitude = 0;
otherinfo.longitude = 0;
if(typeof(schmapit.geopoint) !== 'undefined'){
    cancel.lat = otherinfo.latitude = schmapit.geopoint.latitude;
	cancel.lng = otherinfo.longitude = schmapit.geopoint.longitude;
}

schmap.maptypes = {'m': 'map', 's': 'satellite'};
schmap.currentIconIndex = 0;
schmap.cursorArray = ['zoomin', 'zoomout', 'mapview', 'satelliteview', 'mapimg'];
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;
var schmapMapType = {
    'map':['mapselected','satellite'],
    'satellite':['map','satelliteselected']
};

var tip = {
    title:$('tiptitle'),
	text:$('tiptext'),
	time:3000,
    twitter:['Setting up...','your Twitter background and colors'],
	search:['Searching...','for your address or venue <p class="google-logo hidetext">power by Google</p>'],
	map:['Almost there...','getting your schmap ready'],
	passed:false,
	timeout:[]
};
if(window.newIframe){
    var editIframe = window.newIframe;
}

function PNG_html(attrs) {
    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) {
        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="/image/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 getCsurrentGMapUrl() {
    return "http://maps.google.com/maps?file=api&v=2.151&hl=en&key=" +
        google_api_key + '&async=2&callback=loadedGMap';
}  

function loadGoogle(cursor) {
    if (!googleLoaded) {
        googleLoaded = true;
		if(cursor){
		    document.body.style.cursor = cursor;
            setCursor(schmap.cursorArray, cursor);
		}else{
		    document.body.style.cursor = "wait";
            setCursor(schmap.cursorArray, 'wait');
		}
        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) {
		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 (schmap.map) {
        schmap.map.setZoom(zoomLevel+delta);
		if(schmap.editable){
			window.newIframe.showEditing();
		}
		
    } else {  
        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;
            setTimeout("loadGoogle()", 200); 
        }
    }
}

function setCursor(objs,cursor){
    for(var i = 0; i < objs.length; i ++){
       obj = $(objs[i]); 
	   if(obj){
           obj.style.cursor = cursor;
	   }
    }
}

function loadedGMap(mapContainer) {
    googleFinishedLoading = true;
    var container = mapContainer || $('map');
    $('mapimg').style.cursor ="wait";
    schmap.map =  new GMap2(container);
    schmap.map.enableDoubleClickZoom();
    schmap.map.enableContinuousZoom();
    schmap.map.enableScrollWheelZoom();
    schmap.map.addControl(new GScaleControl());
	makeGMarker({iconcode:otherinfo.iconcode || 'A010'});
    if (delta !== 0) {
    schmap.map.setZoom(zoomLevel+delta);
    }
    var mt = schmap.map.getMapTypes();
    schmap._mt = {};
    var mtTypes = ['map', 'satellite', 'hybrid'];
    for(var i = 0; i < mt.length; i++){
        schmap._mt[mtTypes[i]] = mt[i];
    }
    if(schmap.mapview){
        schmap.map.setMapType(schmap._mt[schmap.mapview]);
    }
	
    var index = 7;
    if(isIE6) {index = 3;}
    var googlemapimg = container.firstChild.firstChild.childNodes[1].firstChild.childNodes[index];
	if(typeof(googlemapimg) === 'undefined'){
	    setTimeout(function(){showmap();},1000);
		return;
	}
    googlemapimg.onload = showmap;
    if(googlemapimg.complete) {
        showmap();
    }
}

function showmap(){
    if(tip.passed && userinfo.id && !cssjs('check',$('overlayparent'),'final-stage')){gotoFinalStage();}
	tip.maploaded = true;
    if(schmap.showmap) {return;}
	cssjs('add',$('mapouter'),'dynamic-map');
    $('map').style.visibility = "visible";
    document.body.style.cursor = "default";
    setCursor(schmap.cursorArray, 'pointer');    
    setTimeout(function(){
                    if (deltaX !== 0 || deltaY !== 0)    {
                        schmap.map.panBy (new GSize(deltaX,deltaY));
                    }}, 200);
    schmap.showmap = true;
}


function loadGoogleApi(){
    google.load("search", "1",{'language':'en','callback':setLocalSearch});
}

function showInitStage(){
    if($('flash')){
		if(typeof(queryurl) !== 'undefined'){
			if(!queryurl.flashAdded){
				$('flash').innerHTML = flashtext;
				$('flash2').innerHTML = flashtext2;
				queryurl.flashAdded = true;
			}
		}
	}
	cssjs('add',document.body,'initial');
	$('overlayparent').className = '';
	cssjs('add',editIframe.$('wrapper'),'homepage');
	editIframe.enableSearch();
}

var searchControl = null;
function retriveUserprofile(response){
    if(typeof(response) === 'string'){
	    response = evalJson(response);
	}log(response);
    if(response.error){
	    checkprofile();
		return false;
	}
    userinfo = {};
    schmap.twitterResponse = schmap.editable = true;
    var r = response;
    schmap[r.screen_name.toLowerCase()] = true;
	schmap.userLocation = r.location;
	doSearch();
	var fields = ['id','name','screen_name','location','profile_image_url','profile_background_color','profile_text_color','profile_link_color','profile_background_image_url','profile_background_tile'];
	var isRepeat = 'no-repeat';
	for(var i = 0; i < fields.length; i++){
	    var f = fields[i];
		var v;
		if(f === 'profile_background_tile'){
			if(r.profile_background_tile){
				v = 1;
				isRepeat = 'repeat';
			}else{
				v = 0;
			}
		}else{
			v = r[f];
		}
		if(f === 'id'){
		    userinfo.xid = v;
		}else{
		    userinfo[f] = v;
		}
		 
	}
	$('screenname').innerHTML = r.screen_name;
	$('twitter_username').innerHTML = r.name;
	$('profileImg').src = r.profile_image_url;
	$('profileImg').parentNode.href = $('screenname').href = 'http://www.twitter.com/' + r.screen_name;
	var css = 'a,a:link,a:hover,a:active,a:visited{color:#' + 
	        r.profile_link_color + ';}.mainText,.profile p,#text{color:#' +
			r.profile_text_color + ';}body{background:#' +
			r.profile_background_color + ' url(' + r.profile_background_image_url +
			') ' + isRepeat + ' 0 0;';
    addStyle(css);
}

function showSetupStage(){
    changeTipContent('twitter');
	$('overlayparent').className = 'setting-style';
	setupFirstStage();
}


function changeTipContent(stage){
    var a  = tip;
    a.title.innerHTML = a[stage][0];
	a.text.innerHTML = a[stage][1];
}

function setupLastStage(){
    changeTipContent('map');
	$('overlayparent').className = 'setting-style';
	tip.passed = false;
    tip.timeout[tip.timeout.length] = setTimeout(function(){
	        tip.passed = true;
			log('last stage :3 seconds passed');
	        if(tip.maploaded && userinfo.id){
			    gotoFinalStage();
			}log('tip.maploaded && userinfo.id is ' + (tip.maploaded && userinfo.id));
	    },tip.time);
}

function setupSecondStage(){
    changeTipContent('search');
	tip.passed = false;
	tip.timeout[tip.timeout.length] = tip.searchingInteval = setTimeout(function(){
	        //console.log('second stage: 3 seconds passed');
	        tip.passed = true;
            if(tip.searched){
			    if(!tip.oneresult){
				    $('overlayparent').className = 'search-result';
				}else{
				    setupLastStage();
				}
			}
	    },tip.time);
}

function setupFirstStage(){
    schmap.editable = false;
	tip.passed = false;
    tip.timeout[tip.timeout.length] = setTimeout(function(){
	        tip.passed = true;
			//console.log('first stage: 3 seconds passed');
	        if(schmap.editable){
				//console.log('change searching  text during timeout, changeTipContent("search")');
				setupSecondStage();
			}
	    },tip.time);
}

function flushTimeouts(ts){
    for(var i = 0; i <ts.length; i++){
	    clearTimeout(ts[i]);
	}
}

function doSearch(flag){
    tip.searched = false;
    var v = schmap.searchValue;
	if(schmap.ownEditing){
		cssjs('add',$('re_search_box'),'at-search-result');
	}
	if(v.indexOf(',') === -1){
	    if(!schmap.userLocation){
		    topAlert.call('Your search term needs to include a comma, followed by a city or town.');
			if(typeof(singlepage) !== 'undefined' && singlepage){
			    if(schmap.finalStage){cssjs('remove',document.body,'changing-location');}
			}else{
			    showInitStage();
			}
			return;
		}else{
			schmap.searchValue = v += ', ' + schmap.userLocation;
		}
	}
	if(tip.passed || flag){
	    setupSecondStage();
	}
	$('overlayparent').className = 'setting-style';
	overlay.hide();
	$('noResult').style.height = 'auto';
	if(schmap.localSearch){
	    schmap.localSearch.execute(v);
		schmap.shouldDoSearch = false;
	}else{
	    loadGoogleApi();
		schmap.shouldDoSearch = true;
	}
}

function setLocalSearch(){
    var s = new google.search.LocalSearch();
	schmap.localSearch = s;
	s.setResultSetSize(google.search.Search.LARGE_RESULTSET);
	s.setSearchCompleteCallback(window, onJasonLoad);
	//s.execute(schmap.searchValue);
	
	if(schmap.shouldDoSearch){
	    s.execute(schmap.searchValue);
	}
}
function onJasonLoad(){
    var search = schmap.localSearch;
    var s = search.results,
	    c = search.cursor,
	    list = $('resultList'),
		hoverBackground = '#f7f7f7';
	bbbbb = s;
	if(s.length === 0){
	    schmap.noResult = true;
	    if(tip.timeout){
		    flushTimeouts(tip.timeout);
		}
		$('searchValue1').innerHTML = schmap.searchValue;
		tip.noresulttimeout = setTimeout(function(){
		        if(schmap.noResult){
				    $('overlayparent').className = 'no-result';
					editIframe.enableSearch();
				}
		    },1000);
		return;
	}
	schmap.noResult = false;
	tip.searched = true;
	$('searchValue').innerHTML = schmap.searchValue;
	list.innerHTML = $('pages').innerHTML = '';
	if(tip.passed){
	    if(s.length > 1){
		   $('overlayparent').className = 'search-result';
		}else if(s.length === 1){
			setupLastStage();
		}
	}
	var l = s.length;
	for(var i = 0; i < l; i++){
	    var r =  s[i],
		    li = document.createElement('li');
		if(typeof(r.addressLines) === 'undefined' || typeof(r.title) === 'undefined'){
		    l --;
		}else{
			li.innerHTML = r.title +', '+  r.addressLines.toString().replace(/,/g, ', ');
			li.result = r;
			li.defaultColor = li.style.background = (i%2 != 1)?'#ffffff':hoverBackground;
			li.onmouseover = hightlightResult;
			li.onmouseout = delightResult;
			li.onclick = gotoForm;
			var resultNumberText = 'more than one result';
			if(l == 1){
			    if(!schmap.ownEditing){
				    tip.oneresult = true;
					gotoForm.apply(li);
					return;
				}
				resultNumberText = 'one result';
			}
			$('result_number').innerHTML = resultNumberText;
			list.appendChild(li);
		}
	}
	tip.oneresult = false;
	if(s.length < 8){
		return;
	}
	for(i = 0; i < c.pages.length; i ++){
	    var pageClass = ''
		if(i == c.currentPageIndex){
		    pageClass = 'active';
		}
	    var page = document.createElement('span');
		page.className = pageClass;
		page.innerHTML = c.pages[i].label;
		page.page = i;
		page.onclick = gotoPage;
		$('pages').appendChild(page);
	}
	
}
function gotoPage() {
    schmap.localSearch.gotoPage(this.page);
}

function gotoFinalStage(){
    tip.passed = false;
	schmap.finalStage = true;
    window.newIframe.showEditmode();
	$('overlayparent').className = 'final-stage';
	schmap.map.setMapType(schmap._mt[schmap.mapview]);
	cssjs('remove',document.body,'changing-location');
	$('wrapper').className = 'editing';
	setTimeout(function(){$('overlayparent').style.cssText = 'zoom:1;';},100);
	if(schmap.ownEditing){
	    cssjs('remove',$('re_search_box'),'at-search-result');
		return;
	}
	setTimeout(function(){
	        var msg = 'The link for your schmap is shown below, ready to tweet! (Or you can first add notes, title etc.)';
	        topAlert.call(msg,12000);
	   },1000);
}
function handleErrorResponse(r){
	topAlert.call('Sorry, this service is temporarily unavailable, please try again later.');
	$('overlayparent').className = 'search-result';
	editIframe.backToInitState();
	return;
}
function getUrl(){	
	storeMapinfo();
    var inputs = cancel.inputs;
	for(var i = 0; i < inputs.length; i++){
		var input = inputs[i];
		otherinfo[input.name] = input.value.Trim();
	}
	otherinfo.accountable = userinfo;
    var options = getOptions(otherinfo);
    options.onSuccess = getUrlCallback;
    options.onError = handleErrorResponse;
	options.onTimeout = handleErrorResponse;
    ajax(options);
}

function gotoForm(){
    $('footer').style.zIndex = '';
    if(tip.passed || !tip.oneresult){
	    setupLastStage();
	}
	lat = otherinfo.latitude = this.result.lat;
	lng = otherinfo.longitude = this.result.lng;
	$('direction').href = 'http://www.google.com/maps?daddr=' + lat + ',' + lng;
	if(!googleLoaded){
	    loadGoogle('default');
	}else{
	    var center = new GLatLng(lat,lng);
		//schmap.map.setCenter(center, zoomLevel);
		makeGMarker({iconcode:otherinfo.iconcode});
		tip.maploaded = true;
		schmap.iconOverlay.enableDragging();
	}
	otherinfo.address = this.result.addressLines.join(', ');
	setupInput(this.result);
	if(!schmap.ownEditing){
		getUrl();
	}
	var type = false;
	if(typeof(schmapit)!=='undefined'){
	    type = schmapit.maptype;
	}
	initViewButton(type);
}

function goBackToNormal(){
	$('wrapper').className = 'normal-state';
	var arr = ss.imgArr;
	if(arr && arr.length > 0){
	    if(singlepage){ss.doResize();}
		if(ss.medium && $('photosize_m')){
		    $('photosize_m').checked = 'checked';
		}else if($('photosize_s' && ss.length < 1)){
		    $('photosize_s').checked = 'checked';
		}
	}
	hideElement('re_search_box');
	if(schmap.iconOverlay){
	    schmap.iconOverlay.disableDragging();
	}
	if(typeof(gotoHub) !== 'undefined'){gotoHub();}
}

function gotoEditPage(){
	schmap.editable = schmap.editing = true;
	if(ss.imgArr && ss.imgArr.length > 0){ss.initDelete();}
	var b = $('gaddress').value;
	if(schmap.ownEditing){
	    if(b.indexOf(',') !== -1){
			b = b.split(',');
			b = b[0] +','+ b[1];
		}
		$('r_address').value = b;
		showElement('re_search_box');
	}
	//editIframe.$('schmapitlink').innerHTML = editIframe.$('schmapitlink').href = document.location.href;
	setupInput();
	$('wrapper').className = 'editing';
	if(!googleLoaded){
	    loadGoogle();
	}else if(googleFinishedLoading){
	    var center = new GLatLng(lat,lng);
		schmap.iconOverlay.enableDragging();
		showElement('mapswitch');
	}
	if(typeof(schmapit)!=='undefined'){
	    var type = schmapit.maptype;
		otherinfo.id = schmapit.id;
	}else{
	    var type = false;
	}
	initViewButton(type);
}

function storeMapinfo(savezoomandtype){
    var marker = schmap.iconOverlay;
    if(marker){
		var latlng = marker.getLatLng();
		otherinfo.iconcode = marker.iconcode;
		otherinfo.latitude = latlng.lat();
		otherinfo.longitude = latlng.lng();
	}
	cancel.lat = otherinfo.latitude;
	cancel.lng = otherinfo.longitude;
    if(savezoomandtype && schmap.map){
        otherinfo.zoomlevel = schmap.map.getZoom();
		otherinfo.maptype = schmap.map.getCurrentMapType().getName().substring(0,1).toLowerCase();
	}
}

function initSchmapit(){
    cssjs('remove',document.body,'initial');
    var inputs = cancel.inputs;
    for(var i = 0; i < inputs.length; i++){
	    inputs[i].value = '';
	}
	hideElement('infoLink');
	var arr = ['display_rsvp','display_comment','hashtag','infolink','id','photos'];
	for(var i=0; arr[i]; i++){
	    delete otherinfo[arr[i]];
	}
	if(userinfo.id){delete userinfo.id;}
	if(schmapit.addressable_id){delete schmapit.addressable_id;}
	if(schmapit.resource_id){delete schmapit.resource_id;}
	if(schmapit.url){delete schmapit.url;}
	if(schmapit.photos){delete schmapit.photos;}
	otherinfo.zoomlevel = 14;
	otherinfo.iconcode = 'A010';
	otherinfo.maptype = 'm';
}

function getOptions(json){
	var json1 = {
	    type: 't'
	};
	if(schmapit.addressable_id){json1.id = schmapit.addressable_id;}
	if(schmapit.resource_id){json1.resource_id = schmapit.resource_id;}
	if(schmapit.url){json1.url = schmapit.url;}
	return {
	    method:'post',
		data: 'addressable=' + convertJsonToString(json1) + '&resource=' + convertJsonToString(json),
	    url: '/sapp/addressable',
		formData: true
	};
}

function getLink(r){
	otherinfo.id = r.resource.id;
	var schmapitlink = window.newIframe.document.getElementById('schmapitlink');
	schmapitlink.innerHTML = 'http://schmap.it/' +  r.addressable.url;
	schmapit.url = r.addressable.url;
	var host = document.location.host;
	if(host.indexOf('www') !== -1){
	    host = 'schmap.it';
	}
    schmapitlink.href = schmap.userlink = 'http://' + host + '/' +  r.addressable.url;
	createLink(140);
}
function storeInputsValue(){
    var inputs = cancel.inputs,
	    l = inputs.length;
	while(l){
	    l--;
		var input = inputs[l];
		input.defaultValue = input.value;
		detectLabel(input);
	}
}
function getUrlCallback(response){
	try{delete otherinfo.adcode;}catch(e){}
	if(!response){
		handleErrorResponse();
		return;
	}
	var msg,
	    r = evalJson(response.Trim());
		log(r);
	if(r.error || !r.addressable){
	    handleErrorResponse();
		return;
	}else{
	    if(tip.noresulttimeout){
		    clearTimeout(tip.noresulttimeout);
		}
	    getLink(r);
		if(typeof(r.resource.accountable.id) !== 'undefined'){
		    userinfo.id = r.resource.accountable.id;
			if(tip.passed && tip.maploaded){gotoFinalStage();}
		}
	}
	schmapit.addressable_id = r.addressable.id;
	schmapit.resource_id = r.addressable.resource_id;
	schmap.editing = schmap.editable = true;
	if(ss.imgArr){
	    otherinfo.photos = schmapit.photos = '';
		ss.deleteAll();
	}
	storeInputsValue();
	try{
        var ref = window.opener;
		if(ref && typeof(ref.parent.addRow) === 'function'){
			var a = {
				url:r.addressable.url,
				gaddress:r.resource.gaddress,
				createat:r.resource.accountable.createtime.replace(/\//g,'-')
			};
			for(var n in a){
				a[n] = encode(a[n]);
			}
			ref.parent.addRow(a);
		}
	}catch(err){}
}
function handleUpdateUrlError(r){
    topAlert.call('Sorry, this service is temporarily unavailable, please try again later!');
	if(newIframe){
	    newIframe.handleUpdate();
	}
}
function updateUrlCallback(r){
	if(newIframe && !newIframe.saveChanges.passed){log('add callback');
	    newIframe.handleUpdate(function(){updateUrlCallback(r);});
		return;
	}
	newIframe.handleUpdate();
	if(!r){
		handleUpdateUrlError();
		return;
	}
	a = r = r.Trim();
	r = evalJson(r);log(r);a = r;
	if(r.error || !r.addressable){
	    handleUpdateUrlError();
		return;
	}
	createLink(140);
	var resource = r.resource;
	if($('retweetButton') && typeof(createRetweetLink) !== 'undefined'){
	    createRetweetLink(otherinfo.text);
	}
	storeInputsValue();
	schmap.editing = false;
	if(singlepage){
	    schmap.editable = false;
	    otherinfo.photos = schmapit.photos = resource.photos;
		ss.medium = resource.photos && (resource.photos.indexOf('@') !== -1);log('ss.medium is ' + ss.medium);
		//if(ss.medium){cssjs('add',this.slideBox,'medium');}
		cssjs('remove',$('wrapper'),'editing');
		var inputs = cancel.inputs,
		    l = inputs.length,
			i = 0;
	    for(; i < l; i ++){
		    var input = inputs[i];
			var v = input.value.Trim();
			var type = input.type;
			var elm = input.content;
			if(elm){
				if(type === 'textarea' && resource.decorated_text){
				    elm.innerHTML = resource.decorated_text;//v.replace(/\n/g,'<br />');
					var text = elm.textContent || elm.innerText;
					if(text.length > 200){
					     cssjs('add',elm,'more-than-200');
					}else{
					    cssjs('remove',elm,'more-than-200');
					}
				}else{
				    elm.innerHTML = v;
				}
			    if((elm.id === 'eventtime_text_content') || elm.id === ('placename_content')){
				    elm = elm.parentNode;
				}
				if(v){
					showElement(elm);
				}else{
					hideElement(elm);
				}
			}
		}
		var action;
		if(parseInt(resource.display_comment)){
		    action = 'add';
		}else{
		    action = 'remove';
		}
		cssjs(action,document.body,'show-comment');
		if(parseInt(resource.display_rsvp)){
		    action = 'add';
		}else{
		    action = 'remove';
		}
		cssjs(action,document.body,'show-rsvp');
		outputHashtag(r.resource.hashtag);
	    goBackToNormal();
		editIframe.backToInitState();
	}else{
	    editIframe.hideEditing();
	}
	var msg = 'Your changes have been saved.';
	topAlert.call(msg);
	if(updateUrlCallback.callback){
	    updateUrlCallback.callback();
		updateUrlCallback.callback = null;
	}
}

function update(json,onSuccess, onError){
	//var params = 'resolvedtweet=' + convertJsonToString(data) + '&format=ajax';
    var options = getOptions(json);
	options.onError = handleUpdateUrlError;
	options.onTimeout = handleUpdateUrlError;
	if(onSuccess){
	    options.onSuccess = onSuccess;
	}
	if(onError){
	    options.onError = onError;
	}
    ajax(options);
}
function addBackList(user,address){
    var status = address.split('=')[1];
	if(parseInt(status) === 1){
	    var desc = 'added to';
	}else if(parseInt(status) === 0){
	    var desc = 'removed from';
	}else{
	    topAlert.call('The address is not valid');
	    return;
	}
	data = {accountable:{'screen_name':user,'blacklist':parseInt(status)}};
	callback = function(){topAlert.call('The user ' + user + ' has been ' + desc +' the blacklist');}
	update(data,callback);
}
function getPhotoInfo(){
    var elm = $('photosize_m');
	var photos;
	if(elm){
	    if(elm.checked){
			if(otherinfo.photos.indexOf('@') === -1){
				photos = '@' + otherinfo.photos
			}
		}else{
			photos = otherinfo.photos.replace('@','');
		}
	}
	return photos;
}
function updateUrl(){
    storeMapinfo(true);
	var inputs = cancel.inputs;
	for(var i = 0; i < inputs.length; i++){
	    var input = inputs[i];
		otherinfo[input.name] = input.value.Trim();
		input.defaultValue = input.value;
	}
	var elm = $('photosize_m');
	if(elm){
	    if(elm.checked){
			if(otherinfo.photos.indexOf('@') === -1){
				otherinfo.photos = '@' + otherinfo.photos;
			}
		}else{
			otherinfo.photos = otherinfo.photos.replace('@','');
		}
	}
	otherinfo.accountable = {id:userinfo.id};
	update(otherinfo, updateUrlCallback);
}

function toggleMaptypeButton(){
    var elms = [$('mapview'),$('satelliteview')];
	for(var i = 0; i < elms.length; i++){
	    var elm = elms[i];
		var type = elm.id.replace('view','');
		if(elm.selected){
            var src = "/image/" + type + ".png";
			elm.selected = false;
		}else{
		    var src = "/image/" + type + "selected.png";
			elm.selected = true;
			schmap.mapview = type;
		}
		if(isIE6){
			var filter = PNG_style({src: src, width: 55, height: 18});
			elm.style.filter= filter;
		}else{
			elm.src = src;
		}
	}
}

function cancelChanges(){
	var gmap = schmap.map;
	var marker = schmap.iconOverlay;
    if(gmap){
	    var maptype = gmap.getCurrentMapType().getName().substring(0,1).toLowerCase();
	    if(maptype !== otherinfo.maptype){
			var mapview = schmap.maptypes[otherinfo.maptype];
			schmap.map.setMapType(schmap._mt[mapview]);
			toggleMaptypeButton();
		}
		lat = cancel.lat || otherinfo.latitude;
		lng = cancel.lng || otherinfo.longitude;
		zoomLevl = otherinfo.zoomlevel;
		if(marker){
		    var latlng = marker.getLatLng();
			$('direction').href = 'http://www.google.com/maps?daddr=' + lat + ',' + lng;
			if(marker.iconcode !== otherinfo.iconcode || latlng.lat() !== otherinfo.latitude || latlng.lng() !== otherinfo.longitude){
				makeGMarker({iconcode:otherinfo.iconcode});
			}
		}
	}
	var inputs = cancel.inputs;
	for(var i = 0; i < inputs.length; i++){
	    var input = inputs[i];
		input.value = input.defaultValue;
		detectLabel(input);
	}
	var link = otherinfo.infolink
	if(link && link !== $('infoLink').href){
	    $('infoLink').href = otherinfo.infolink;
		$('infoLink').style.display = 'inline';
	}
	if(cancelChanges.callback){
	    cancelChanges.callback();
		cancelChanges.callback = null;
	}
	schmap.editable = schmap.editing = schmap.ownEditing = false;
}

function evalJson() {
	return eval("(" + filterJSON(arguments[0]) + ")");
}
function filterJSON (s) {
	var m = s.match(/^\s*\/\*(.*)\*\/\s*$/);
	if (m) {
		return m[1];
	}
	return s;
}

function convertJsonToString(json){
	var h = [];
	for(var n in json){
	   var v = json[n];
	   if(typeof(v) === 'string'){
	       v = v.replace(/\\/g,'\\\\').replace(/"/g,'\\"').replace(/\n/g,'\\n');
		   v = '"' + encode(v) + '"';
	    }else if(v && typeof(v) === 'object'){
		    v = convertJsonToString(v);
		}
	   h.push('"' + n + '"' + ':' + v);
	}
	h = '{' + h.join(',') + '}';
    return h;
}

function setupInputLabel(){
    /*var inputs = [$('text'),$('pagetitle'),$('eventtime_text'),$('placename'),$('gaddress')],
	    defValue = {
		    'text': 
		};*/
	var inputs = document.getElementsByTagName('input'),
	    textareas = document.getElementsByTagName('textarea'),
		labels = document.getElementsByTagName('label'),
		labelCollection = {},
		elms = [],
		elm,label,name,type,i,j,k,l;
	for(i = 0; i< inputs.length; i += 1){
	    elms[elms.length] = inputs[i];
	}
	for(k = 0; k < textareas.length; k += 1){
	    elms[elms.length] = textareas[k];
	}
	for(j = 0; j < labels.length; j += 1){
		label = labels[j];
		name = label.getAttribute('for');
		if(!name){name = label.htmlFor}
		if(name){
			labelCollection[name] = label;
		}
	}
	for(l = 0; l< elms.length; l += 1){
	    elm = elms[l];
		type = elm.type;
		if(type === 'text' || type === 'textarea' || type === 'password'){
			name = elm.name;
			elm.defaultValue = elm.value;
			if(singlepage){
			    if($(name + '_content')){
					elm.content = $(name + '_content');
				}else if(name === 'text'){
				    var textNode = document.createElement('p');
					textNode.id = name + '_content';
					textNode.className = 'mainText';
					textNode.style.display = 'none';
					$('main').insertBefore(textNode, elm.parentNode);
				    elm.content = textNode;
				}
			}else{
			    elm.defaultValue = elm.value = '';
			}
			if(name && labelCollection[name]){
				elm.label = labelCollection[name];
				elm.onfocus = checkInput;
			    elm.onblur = checkOnblur;
			}
			detectLabel(elm);
		}
	}
}

function setupInput(result){
    var inputs = [$('pagetitle'),$('eventtime_text'),$('placename'),$('gaddress'),$('text')],
	    l = inputs.length;
	for(var i = 0; i< l; i += 1){
	    var input = inputs[i];
		var name = input.name;
		if(name && result){
			if(name === 'placename'){
				if(result.titleNoFormatting !== result.streetAddress){
					input.value = result.titleNoFormatting;
				}
			}else if(name === 'gaddress'){
				input.value = result.addressLines.join(', ');
			}
			detectLabel(input);
		}
		input.onkeyup = input.onchange = input.onpaste = window.newIframe.showEditing;
	}
	cancel.inputs = inputs;
	setTimeout(function(){
	        var inputs = cancel.inputs,
			    l = inputs.length;
			while(l){
			    l--;
				var input = inputs[l];
				input.label.style.zoom = '1';
				if(input.span){
				    input.span.style.zoom = '1';
				}
			}
	    }
	,100);
}

function checkOnblur(){
    detectLabel(this);
	if(this.onmouseup){
	    this.onmouseup = null;
	}
}
function checkInput(){
    if(this.value.Trim() === ''){
	    this.label.style.display = 'none';
	}
	if(this.name === 'pagetitle'){
	    this.className = 'showInput';
	}
	var that = this;
	this.onmouseup = function(e){
		e = e || window.event;
		if(e.button == 2){log(e);}
		if(that.value !== that.defaultValue){
			window.newIframe.showEditing();
		}
	}
}
function detectLabel(input){
    if(input.value.Trim() !== ''){
		hideElement(input.label);
		if(input.name === 'pagetitle'){
		    if(!input.span){
			   var span = document.createElement('span');
			   input.span = span;
			   input.parentNode.appendChild(span);
			}
			input.span.innerHTML = input.value;
			showElement(input.span);
			input.className = 'hideInput';
		}
	}else{
		if(input.label){
		    showElement(input.label);
		}
		if(input.name === 'pagetitle'){
		    input.className = 'showInput';
		}
	}
}

function hightlightResult(){
    this.style.backgroundColor = '#eeeeee';
}

function delightResult(){
	this.style.backgroundColor = this.defaultColor;
}

	
function getProfileScript(s){
    if(schmap.profileScript){
	    document.body.removeChild(schmap.profileScript);
		schmap.profileScript = null;
	}
    schmap.twitterResponse = false;
	schmap.profileScript = s;
	s.onerror = checkprofile;
	s.onreadystatechange = reportOnstatechange;
}

function reposrtOnerror(){
    topAlert.call(this.href);
	return;
}

function reportOnstatechange(){
    if(this.readyState === 'loaded'){
		    setTimeout(checkprofile,100);
	}
	return;
}

function checkprofile(){
	if(!schmap.twitterResponse){
	    topAlert.call();
		showInitStage();
	}
}

function getCurrentIconIndex(iconcode){
    var icons = icondata;
	for(var i = 0; i < icons.length; i++){
	    var icon = icons[i];
		if(icon.iconcode === iconcode){
		    schmap.currentIconIndex = i;
			break;
		}
	}
}

function switchMapView(event) {
    var target = this;
    var id = target.id;
    var oldview = schmap.mapview;
    if(schmap.mapview +'view' ==  id) return;
	schmap.mapview = id.replace('view','');
	var src = "/image/" + schmap.mapview + "selected.png";
    var othersrc = "/image/" + oldview + ".png";
	if(schmap.editable){
	    window.newIframe.showEditing();
	}
    if(isIE6){
	    var filter = PNG_style({src: src, width: 55, height: 18});
        var atherfilter = PNG_style({src: othersrc, width: 55, height: 18});
        $(oldview + 'view').style.filter = atherfilter;
        target.style.filter= filter;
    }else{
        $(oldview + 'view').src = othersrc;
        target.src = src;
    }
	this.selected = true;
	$(oldview + 'view').selected = false;
    if (schmap.map ) {
        schmap.map.setMapType(schmap._mt[schmap.mapview]);
    }else {
        setTimeout("loadGoogle()", 200); 
    }
}

function makeGMarker(options){
    var iconcode = options.iconcode || 'A010';
    var center = new GLatLng(lat, lng);
	getCurrentIconIndex(iconcode);
	var iconObj = icondata[schmap.currentIconIndex];
    if(iconObj.bigiconpath){
        var ic =new GIcon();
        ic.image = '/image/mapicons/' + iconObj.bigiconpath;
        ic.iconSize = new GSize(iconObj.bigiconwidth, iconObj.bigiconheight);
        ic.iconAnchor = new GPoint(iconObj.bigiconwidth*iconObj.bigiconanchorx/100, 
                                    iconObj.bigiconheight*iconObj.bigiconanchory/100);
        var marker = new GMarker(center,{icon:ic,clickable:false,draggable:true});
		marker.disableDragging();
    } else {
        var marker = new GMarker(center);
    }
	marker.iconcode = iconcode;
	if(schmap.searchValue || schmap.editing){
		if(schmap.iconOverlay){
			schmap.map.removeOverlay(schmap.iconOverlay);
		}
	    marker.enableDragging();
	    GEvent.addListener(marker, "dragend", onDragend);
	}
	schmap.map.addOverlay(marker);
	schmap.iconOverlay = marker;
    schmap.map.setCenter(center, zoomLevel);
}

function onDragend(){
    var latlng = this.getLatLng();
	lat = latlng.lat();
	lng = latlng.lng();
	$('direction').href = 'http://www.google.com/maps?daddr=' + lat + ',' + lng;
	editIframe.showEditing();
}

function initMapButton(){
    var zoomin = PNG_html({id: 'zoomin', src: '/image/zoomin.png', width: 18, height: 21});
	var zoomout = PNG_html({id: 'zoomout', src: '/image/zoomout.png', width: 18, height: 21});
	$('zoominout').innerHTML = zoomin + zoomout;
	$('zoomin').onclick = zoominout;
	$('zoomout').onclick = zoominout;
}

function initViewButton(maptype){
    var type = maptype || 'm';
    schmap.mapview = schmap.maptypes[type];
	var mapview =  PNG_html({id: 'mapview', src: '/image/'+schmapMapType[schmap.mapview][0]+'.png', width: 55, height: 18});
	var satelliteview =  PNG_html({id: 'satelliteview', src: '/image/'+schmapMapType[schmap.mapview][1]+'.png', width: 55, height: 18});
	$('mapswitch').innerHTML = mapview + satelliteview;
	$(schmap.mapview + 'view').selected = true;
	$('mapview').onclick = switchMapView;
	$('satelliteview').onclick = switchMapView;
}
function outputEncodedHashtag(){
    var hashtag = otherinfo.hashtag || schmapit.hashtag || '';
	if(hashtag){
	    hashtag = '+%23' + hashtag.replace(/#/g, '').replace(/\|/g, '+%23');
	}
	return hashtag;
}
function createLink(length,elm){
	if(schmap.userlink){
	    var link = schmap.userlink.Trim();
	}else{
	    var a = document.location;
        var link = 'http://' + a.host + a.pathname;
	}
	var hashtag = outputEncodedHashtag();
	length = length - link.length - hashtag.length;
	var s = '',
	    separator = ', ';
	var inputs = ['pagetitle','eventtime_text','placename','gaddress'];
	for(var i = 0; i < inputs.length; i++){
	    var input = $(inputs[i]);
		var v = input.value.Trim();
		if(v !== ''){
		    if(input.name === 'gaddress'){
				if(v.indexOf(',') !== -1){
					v = v.substr(0,v.indexOf(','));
				}
			}
		    if(i === (inputs.length -1)){
			    separator = ': ';
			}
		    var t = s + v + separator;
			if(t.length <= length){
				s = t;
			}
		}
	}
	schmap.tweetString = s + link;
	s = encode(s).replace(/%20/g,'+')
	var a = elm ? elm : editIframe.document.getElementById('tweet');
    a.href = 'http://twitter.com/home/?status=' + s + link + hashtag;
}
var truncate = function (s,length){
	var end = s.lastIndexOf(' ');
	var t = s.substring(0,end);
	if(t.length + 3 > length){
		s = t;
		return truncate(s,length);
	}else{
	    return t + '...';
	}
}
function truncatelink(text,length){
    var s = text.replace(/<br\s*\/?>/gi,' ').Trim();
	if(s.length > length){
        s = truncate(s,length);
	}
	s = encode(s).replace(/(%20)+/g,'+');
	return s;
}

function showCreatStage(anchor){
    overlay.showcallback = function(){
	    $('footer').style.zIndex = '5000';
	}
	overlay.hidecallback = function(){
	    $('footer').style.zIndex = '0';
	    editIframe.$('introtext').innerHTML = 'Share a place or event with your Twitter followers';
		editIframe.$('back').style.display = 'none';
	}
    overlay.show({clickhide:true});
    editIframe.gotoCreateStage(anchor);
}
function addOverlayCallback(){
    overlay.showcallback = function(){
	    $('footer').style.zIndex = '5000';
	}
	overlay.hidecallback = function(){
	    $('footer').style.zIndex = '0';
	    editIframe.introtext.backtoinit();
	}
}

function signinSuccess(r){
	//cancelSignin();
	if(typeof(r) === 'string'){
	    r = evalJson(r);
	}
	var code = r.code;
	if(0 < code && code < 4){
	    topAlert.call(r.message);
		//cssjs('remove',$('signinbox'),'processing');
		return;
	}
	var elm = $('signin'),
	    signinParent = elm.parentNode;
	    linkList = signinParent.parentNode;
	if(singlepage){
	    var homeLink = document.createElement('a'),
		    signoutParent = document.createElement('li'),
			signoutLink = homeLink.cloneNode(false),
			lis = linkList.getElementsByTagName('li'),
		    l = lis.length;
		cssjs('remove',lis[l-1],'last');
		homeLink.href = '/home';
		homeLink.id = 'home';
		homeLink.innerHTML = 'Home';
		signoutLink.id = 'signout';
		signoutLink.innerHTML = 'Sign out';
		signoutLink.onclick = handleHomepageSignout;
	    signinParent.replaceChild(homeLink,elm);
		signoutParent.appendChild(signoutLink);
		linkList.appendChild(signoutParent);
		cssjs('add',signoutParent,'last');
		cancelSignin();
	}else{
	    document.location.href = 'http://' + document.location.host + '/home';
	}
}

function showCheckingProcess(){
    var box = $('signinbox');
	cssjs('add',box,'processing');
}

function checkSignin(){
    showCheckingProcess();
    var u = $('username').value.Trim(),
	    p = $('password').value.Trim(),
		isValid = false;
	if (!(u && p)) {
        topAlert.call("Twitter username and password must be supplied.");
        return;
    }
	if(/^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(u)){
	    isValid =true; 
	}else{
	    if(/[a-zA-Z0-9_]+/.test(u)){
			isValid = true;
		}else{
		    if ($('uname').value.indexOf('@') >= 0) {
				topAlert.call("Twitter username is invalid (you cannot use your email address here)");
			}else{
			    topAlert.call('The username you entered is not valid.');
			}
			return false;
		}
	}
	
	if(isValid){
	    var data = 'username=' + encode(u) + '&password=' + encode(p);
	    var options = {
		    url: '/pyapp/login?' + data,
			method: 'get',
			onSuccess:signinSuccess,
			timeout:100,
			onTimeout:function(r){
			        topAlert.call('Sorry, some error happened, please try again');
					cssjs('remove',$('signinbox'),'processing');
					return;
				}
		}
		ajax(options);
	}
	return false;
}
function handleHomepageSignoutSuccess(){
    document.body.style.cursor = '';
	goBackToNormal();
	editIframe.backToInitState();
    var signoutLink = $('signout'),
        signoutParent = signoutLink.parentNode,
		linkList = signoutParent.parentNode,
		lis = linkList.getElementsByTagName('li'),
		l = lis.length;
	if($('home')){linkList.removeChild($('home').parentNode);}
	var liSibling = lis[0];
	var li = linkList.removeChild(signoutParent);
	li.innerHTML = '<a id="signin" href="/login">Sign in</a>';
	//li.innerHTML = '<a id="signin">Sign in</a>';
	cssjs('remove',li,'last');
	linkList.insertBefore(li,liSibling);
	//$('signin').onclick = handleSignin;
	cssjs('add',liSibling,'last');
	topAlert.call('You have successfully signed out.');
	if(typeof(gotoEducate) !== 'undefined' && educateIframe){
	    gotoEducate();
	}
	loggedin_username = false;
}
function handleSignin(){
	var inputs = ['username','password'],
	    l = inputs.length;
	while(l){
	    elm = $(inputs[l - 1]);
		if(elm){
		    elm.value = '';
			detectLabel(elm);
		}
		l--;
	}
	var box = $('signinbox');
	cssjs('remove',box,'processing');
	overlay.hidecallback = function(){
	    hideElement(box);
		hideElement('top_overlay');
		$('top').style.zIndex = '0';
	}
	showElement('top_overlay');
	$('top').style.zIndex = '10000';
	$('top_overlay').style.height = $('topconer').clientHeight + 'px';
	$('top_overlay').style.width = $('topconer').clientWidth + 'px';
	overlay.show({elm:box});
}
function cancelSignin(){
	overlay.hide();
}
function handleRememberme(){
    var checked = this.checked;
	if(checked){
	    cssjs('swap',$('rememberme').parentNode,'checked','unchecked');
	}else{
	   cssjs('swap',$('rememberme').parentNode,'unchecked','checked');
	}
}
function handleHomepageSignout(){
    //document.body.style.cursor = 'wait';
	delCookie('schmaptid');
	handleHomepageSignoutSuccess();return;
    ajax({url:'/pyapp/signout',onSuccess:handleHomepageSignoutSuccess});
}
function initLogin(){
    var signout = $('signout');
	if(signout){
	    signout.onclick = handleHomepageSignout;
	}
    /* var signout = $('signout'),
	     signin = $('signin');
    if(signin){
	    signin.onclick = handleSignin;
	}else if(signout){
	    signout.onclick = handleHomepageSignout;
	}
	$('cancel_signin').onclick = cancelSignin;
	$('rememberme').onchange = handleRememberme;
	cssjs('add',$('rememberme').parentNode,'checked','unchecked');
	document.login.onsubmit = checkSignin;
	*/
}
function hideIconPopup(){
    editIframe.$('IconsPopupDiv').style.visibility = 'hidden';
}
if(document.location.pathname.length < 2){
	window.onload = function(){
		if(typeof(queryurl) !== 'undefined'){
		   if(queryurl.user){
				editIframe.getmap();
				window.location.replace('#');
			} 
		}
		var a = document.location.search;
		if(a){
			if(a.indexOf('ownstaff') !== -1){
			    var staff = a.split('=')[1];
				if(staff){
				    setCookie('ownstaff',staff,365,'/','.schmap.it');
				}
			}
		}
	}
}
window.onunload = function(){
    var l = handlers.length;
	if(!l){return;}
	if(document.detachEvent){
	    while(l--){
		   var a = handlers[l];
           a.elm.detachEvent(a.type,a.fn);
		}
	}
	
}
function init(){
    //initImage();
    setupInputLabel();
	initMapButton();
	initLogin();
}
function showImage(elm,n){
    var imgs = initImage.imgs,
		l = imgs.length;
	while(l){
		l--;
		var img = imgs[l];
		if(img.style.display === 'block'){
		    img.style.display = '';
			initImage.imgPages[l].className = 'img-page';
			break;
		}
	}
    imgs[n].style.display = 'block';
	elm.className = 'current';
}
var ss = {
	bigImg: new Image(),
	slideMaxHeight: 575,
	oneImageHeight: (561 - 57),//57 is the thumbnail's height;
	names: [],
	thumbnail: '_thumbnail',
	init: function(arr,flag,validImageNum){
	    var i = 0,
		    j = 0,
			temp = document.createElement('div'),
			imgBox = document.createElement('div'),
			slideNav = document.createElement('div'),
			slideNavBox = document.createElement('div'),
			slideBox = document.createElement('div');
		slideNavBox.className = 'img-page-box';
		slideNav.className = 'slide-nav';
		imgBox.className = 'image-box zoomin';
	    slideBox.className = 'image-list-box';
		temp.className = 'inlineblock';
		this.cur = this.length = 0;
		this.imgArr = [];
		this.img2Arr = [];
		this.navAs = [];
		this.pop = false;
		this.nav = slideNav;
		this.slideBox = slideBox;
		this.navList = imgBox;
		if(flag === 'singlepage'){this.names = arr;}
		var l = arr.length;
		if(this.medium && !schmap.editing && singlepage){
		    cssjs('add',this.slideBox,'medium');
		}
		for(i; i < l; i++){
			if(arr[i]){
			    this.addImg(j,arr[i],flag);
				j++;
			}
		}
		if(this.imgArr.length < 1){return;}
		temp.appendChild(slideNav);
		slideNavBox.appendChild(temp);
		slideBox.appendChild(imgBox);
		slideBox.appendChild(slideNavBox);
		this.createPrevNext();
		this.showImg(0);
		var nextSibling = $('screenname').parentNode.parentNode;
		cssjs('add',document.body,'photoing');
		nextSibling.parentNode.insertBefore(slideBox,nextSibling);
		if(schmap.editing || !singlepage){
		    ss.initDelete();
		}else{
		    this.startAutoSlide();
		}
	},
	addImg: function(i,name,flag){
	    var l = this.length;
		if(l > 7){return;}
	    if(this.imgArr){
			var tab = document.createElement('span'),
				url = schmapit.url,
				img = new Image(),
				postfix = '',
				format = name.substring(name.lastIndexOf('.'));

			if(!singlepage || (!ss.medium && flag !=='edit') || flag === 'edit'){
				if(flag === 'edit'){
			        postfix = '?' + new Date().getTime();//this is for the cache bug
			    }
				name = name.replace(format,this.thumbnail + format + postfix);
			}
			img.style.cssText = 'position:absolute;top:8888px';
			img.onload = function(){
				this.removeAttribute('width');
				this.removeAttribute('height');
				this.loaded = true;
				var s = ss;
				this.initWidth = this.clientWidth;
				this.initHeight = this.clientHeight;
				if(singlepage){
				    if(schmap.editing){
					    s.resizeImg(this, false, 130);
					}else if(ss.medium){
						s.resizeImg(this, 358, false);
						var h = s.navList.style.height;
						if(!h){
						    h = s.navList.clientHeight;
						}else{
						    h = parseInt(h);
						}
						if(h < this.clientHeight){
							s.navList.style.height = this.clientHeight + 'px';
						    s.navList.oldHeight = this.clientHeight + 'px';
						}
					}
				}
				img.style.cssText = '';
			}
			if(ss.imgArr[i]){
				ss.navList.insertBefore(img,ss.imgArr[i]);
			}else{
				ss.navList.appendChild(img);
			}
			img.src = '/home2/' + url.substring(0,2) + '/' + url + '/photos/' + name;
			ss.imgArr.splice(i,0,img);
			tab.id = ss.length;
			this.length++;
			tab.innerHTML = this.length;
			img.rel = name;
			this.nav.appendChild(tab);
			this.navAs.push(tab);
			img.title = 'click to view bigger image';
			tab.className = 'img-page';
			tab.onmouseover = function(that){
				return function(){
					that.showImg(this.id);
					that.stopAutoSlide();
				}
			}(this);
            if(singlepage){			
			    img.onmouseout = tab.onmouseout = function(){
					if(!ss.popup){ss.startAutoSlide();}
				}
				img.onmouseover = function(){
					ss.stopAutoSlide();
					if(ss.length < 2 && ss.medium && (this.clientHeight>=430 || (this.initHeight && this.initHeight<=this.clientHeight))){
						this.onclick = null;
						this.title = '';
						cssjs('remove', this.parentNode, 'zoomin');
					}else{
						if(!this.onclick){
							this.onclick = function(){
								ss.initSlide(ss.cur);
							}
						}
						cssjs('add', this.parentNode, 'zoomin');
					}
				}
			}	
			if(this.length > 1){
				cssjs('add',ss.slideBox,'more-than-1');
			}
			if(this.length > 7){
				cssjs('add',this.slideBox,'more-than-7');
			}
		}else{
		    this.init([name],flag);log('init the ss');
		}	
	},
	doDelete: function(index){
	    var s = ss,
			img = s.imgArr.splice(index,1)[0],
			name = img.rel;log('delete image and the index is ' + index);
		img.parentNode.removeChild(img);	
		if(s.imgArr.length > 0){
			s.length--;	
			try{
			    var img2 = s.img2Arr.splice(index,1)[0];
			    img2.parentNode.removeChild(img2);
			}catch(e){}
			var numNode = s.navAs[s.length];
			numNode.parentNode.removeChild(numNode);
			s.navAs.pop();
			if(index > 0){
				s.showImg(0);
			}else{
				s.showImg(0);
			}
			if(s.length < 8){
				cssjs('remove',this.slideBox,'more-than-7');
			}
			if(s.length === 1){
				cssjs('remove',this.slideBox,'more-than-1');
			}
		}else{
			s.deleteAll();
		}
		var photoIframe = window.frames['photoiframe'];
		if(photoIframe){
		    photoIframe.initIframe();
		}
	},
	deleteImg: function(){
	    if(topAlert.staying){topAlert.hide();}
		var r = confirm('are you sure you want to delete this image?');
		if(r){
		    var index = ss.cur;
		    this.names[parseInt(ss.imgArr[index].rel) - 1] = '';log('this.names is ' + this.names.join(','));log("s.imgArr[index].rel is " + parseInt(ss.imgArr[index].rel));
			cssjs('add',ss.slideBox,'deleting');
			updatePhotoInfo('delete',index);
		}
	},
	getSide: function(e,elm){
		return ((e.layerX || e.offsetX) - elm.parentNode.clientWidth/2 > 0) ? 'right' : 'left';
	},
	prev: function(){
	    if(this.cur > 0){
		    this.showImg(this.cur-1);
		}else{
		    this.showImg(this.length - 1);
		}
	},
	next: function(){
	    if(this.cur + 1 < this.length){
		    this.showImg(this.cur+1);
		}else{
		    this.showImg(0);
		}
	},
	startAutoSlide: function(){
	    if(schmap.editing || this.popup || !singlepage){this.stopAutoSlide();return;}
	    this.interval = setInterval(function(){
			ss.next();
		},8000);
	},
	stopAutoSlide: function(){
	      clearInterval(this.interval);
	},
	showImg: function(n){
	    n = parseInt(n);
		if(this.img2Arr.length > 0){
		    try{
			var thubmnail = this.img2Arr[n];
			this.img2Arr[this.cur].className = '';
			thubmnail.className = 'current-thubmnail';
			if(this.popup){
				if(!thubmnail){
					throw new Error('n is ' + n);
				}
				$('big_img_td').innerHTML = '<img style="position:absolute;top:-8888px;" onload="this.style.cssText=\'\';ss.resizeImg(this,false,430);" src="' + thubmnail.src.replace('_thumbnail','') + '" />';
			}
			}catch(e){}
		}
		try{
		    for(var i=0; this.imgArr[i]; i++){
			    this.imgArr[i].className = '';
			}
			this.navAs[this.cur].className = 'img-page';
		}catch(e){log(e);}
		this.imgArr[n].className = 'current-img';
		//this.navList.parentNode.parentNode.style.left =  -n*358 + 'px';
		//if(ss.imgOverlay){ss.imgOverlay.style.left = n*358 + 'px';}
		this.navAs[n].className = 'current';
		this.cur = n;
	},
	deleteAll: function(){log('delete all');
	    this.slideBox.parentNode.removeChild(this.slideBox);
		cssjs('remove',document.body,'photoing');
		this.length = this.uploadCallback.length = this.names.length = 0;
	    this.imgArr = this.img2Arr = this.cur = this.navAs = this.popup = this.medium = this.nav = this.slideBox = this.navList = this.srcArr = null;
	},
	initDelete: function(){
		if(singlepage){
		    cssjs('remove',this.slideBox,'medium');
			this.navList.style.height = '';
			this.doResize('s');
			this.stopAutoSlide();
		}
		if(!$('photo_overlay_div')){
		    var imgOverlay = document.createElement('div');
			ss.imgOverlay = imgOverlay;
			imgOverlay.className = 'image-overlay';
			imgOverlay.innerHTML = '<div id="photo_overlay_div" class="overlay-div"><a title="delete this image" onclick="ss.deleteImg();" class="delete-image"></a></div><p class="delete-tip">deleting...</p>';
			this.slideBox.appendChild(imgOverlay);
			if(this.length > 1){
				cssjs('add',this.slideBox,'more-than-1');
			}
			if(this.length > 7){
				cssjs('add',this.slideBox,'more-than-7');
			}else{
				cssjs('remove',this.slideBox,'more-than-7');
			}
			showUploadLink();
		    var div = document.createElement('div');
			div.className = 'photo-size';
			div.innerHTML = '<h4>Photo size on<br />final schmap:</h4>' + 
			                '<p><label><input ' + (this.medium ? '' : 'checked="checked" ') + 'type="radio" onclick="newIframe.showEditing();" id="photosize_s" name="photosize" value="s" />small (like this)</label></p>' + 
							'<p><label><input ' + (this.medium ? 'checked="checked" ' : '') + 'type="radio" onclick="newIframe.showEditing();" name="photosize" id="photosize_m" value="m" />medium</label></p>';
			ss.slideBox.appendChild(div);
			ss.photosizeAdded = 1;
		}
	},
	createPrevNext: function(){
	    var prev = document.createElement('a'),
			next = document.createElement('a'),
			prevDiv = document.createElement('div'),
			nextDiv = document.createElement('div'),
			nav = document.createElement('div');
		prevDiv.className = 'prev';
		nextDiv.className = 'next';
		prevDiv.appendChild(prev);
		nextDiv.appendChild(next);
		prev.title = 'click to view the previous image';
		next.title = 'click to view the next image';
		prev.onclick = function(){ss.prev();return false;};
		next.onclick = function(){ss.next();return false;};
		nav.appendChild(prevDiv);
		nav.appendChild(nextDiv);
		prev.onmouseout = next.onmouseout = function(){
			ss.startAutoSlide();
		};
		prev.onmouseover = next.onmouseover = function(){
			ss.stopAutoSlide();
		};
		var elm = this.nav;
		elm.parentNode.insertBefore(prevDiv,elm);
		elm.parentNode.appendChild(nextDiv);
	},
	initSlide: function(n){
	    if(schmap.editing || !singlepage){return;}
	    this.popup = true;
		var elm1 = $('mainContent'),
			elm2 = $('overlayparent');
		if(this.img2Arr.length === 0){
			var l = this.imgArr.length,
				i = 0,
				div = document.createElement('div'),
				nav = document.createElement('div'),
				slide = div.cloneNode(false),
				bigImgBox = div.cloneNode(false),
				close = document.createElement('a');
			close.className = 'slide-back';
			close.innerHTML = 'back...';
			close.onclick = function(){
				var s = ss;
				s.slide.style.display = 'none';
				s.popup = false;
				$('schmapitform').style.cssText = '';
				cssjs('remove', document.body, 'slide-displaying');
				s.startAutoSlide();
			}
			for(; i < l; i++){
				var img = new Image(),
				    thumbnial = this.imgArr[i];
				img.src = thumbnial.src;
				img.navid = i;
				img.style.height = '53px';
				//ss.resizeImg(img,false,53,true);
				img.style.width = (thumbnial.clientWidth*53)/thumbnial.clientHeight + 'px';
				img.onclick = function(){
					ss.showImg(this.navid);
				};
				div.appendChild(img);
				this.img2Arr.push(img);
			}
			var titleElm = $('pagetitle_content');
			if(titleElm && titleElm.innerHTML){
			    nav.innerHTML = titleElm.innerHTML;
			}else{
			    nav.innerHTML = 'Photos';
			}
			nav.className = 'slide-title';
			div.className = 'slide-thumbnail';
			slide.className = 'slide-box round';
			bigImgBox.className = 'big-image';
			bigImgBox.innerHTML = '<table width="100%" border="0"><tbody><tr><td id="big_img_td"></td></tr></tbody></table><div title="click to view the previous image" onclick="ss.prev();" class="slide-cursor" id="cursor_left"></div><div class="slide-cursor" title="click to view the next image"onclick="ss.next();" id="cursor_right"></div>';
			slide.appendChild(nav);
			slide.appendChild(close);
			slide.appendChild(bigImgBox);
			slide.appendChild(div);
			this.slide = slide;
			elm1.appendChild(slide);
		}
		var x = pageX(elm1),
			y = pageY(elm1),
			h = elm2.clientHeight - y - 15;//15 is the paddingBottom of the elm2	
		if(this.length < 2){
		    cssjs('add', document.body, 'no-thumbnail');
			if(h - this.oneImageHeight > 20){h = this.oneImageHeight;}
		}else{
		    cssjs('remove', document.body, 'no-thumbnail');
			if(this.slideMaxHeight - h > 0 || 1){h = this.slideMaxHeight;}
		}
		cssjs('add', document.body, 'slide-displaying');
		$('schmapitform').style.height = (h - 36) + 'px';
		this.slide.style.cssText = 'display:block;height:' + (h-10) + 'px;';//15 is the paddingBottom of the elm2	
		this.showImg(n?n:0);
		//scrollTo(0,0);
		//this.slide.style.display = 'block';
		this.stopAutoSlide();
		if(singlepage && !ss.medium && preloadImages !== undefined){
		    preloadImages();
		}
	},
	uploadCallback: [],
	addUploadCallback: function(index,name){
	    var fn = function(index,name){
			return function (){
				ss.addImg(index,name,'edit');
			}
		}(index,name);
		this.uploadCallback.push(fn);
	},
	callUploadCallback: function(){
		for(var i=0, l=this.uploadCallback.length; i < l; i++){
		    this.uploadCallback[i]();
		}
		if(ss.length < 2){
		    $('photosize_m').checked = 'checked';
		}
		this.uploadCallback.length = 0;
	},
	resizeImg: function(img,w, h, force){
	    var w1 = img.initWidth || img.width,
		    h1 = img.initHeight || img.height,
			w2,h2;
		if(w && !h){
		    if(w1 > w || force){
				h2 = w*h1/w1;
				w2 = w;
				img.setAttribute('width', w);
				img.setAttribute('height', h2);
			}else{
			    img.setAttribute('width', w1);
				img.setAttribute('height', h1);
			}
			if(ss.names.length > 1 && img.height > 352){
			    ss.resizeImg(img,false,352);
			}
			cssjs('add',this.slideBox,'medium');
			if(this.navList.oldHeight){
			    this.navList.style.height = this.navList.oldHeight;
			}
		}else if(h && !w){
		    if(h1 > h || force){
				w2 = w1*h/h1;
				img.setAttribute('width', w2);
				img.setAttribute('height', h);
			}else{
			    img.setAttribute('width', w1);
				img.setAttribute('height', h1);
			}
		}
	},
	resize: function(img,flag){
	    if(flag === 's' && img.loaded && !img.src.match(/'_thumbnail'/)){
			ss.resizeImg(img,false,130);
		}else if(singlepage && ss.medium){
			if(img.src.match(/_thumbnail/)){
				img.removeAttribute('width');
				img.removeAttribute('height');
				img.style.cssText = 'position:absolute;top:8888px';
				img.src = img.src.replace('_thumbnail','');
			}else if(img.loaded){
				ss.resizeImg(img,352);
			}
		}else if(!img.src.match(/_thumbnail/)){
		    ss.resizeImg(img,false,130);
		}
	},
	doResize: function(flag){
	    var s = this;
		if(!(s.imgArr && s.imgArr.length > 0)){return;}
		for(var i=0; ss.imgArr[i]; i++){
		    var img = s.imgArr[i];
		    ss.resize(img,flag);
		}
	}
}
function updatePhotoInfo(action,index){
	for(var i=0, j=0, l = ss.names.length; i<l; i++){
	    if(ss.names[i]){
		    j++;
		}
	}
	var data = {
	    photos: (j > 0) ? ss.names.join(',') : '',
		id: otherinfo.id,
		accountable: {
		    id:userinfo.id
		}
	}
	//data.photos = getPhotoInfo();
	var elm = $('photosize_m');
	if(elm && ((j===1 && !elm.checked) || elm.checked && data.photos)){
		data.photos = '@' + data.photos;
	}else if(!elm && j===1){
	    data.photos = '@' + data.photos;
	}
	if(action === 'delete'){
	    var msg = 'The photo has been successfully deleted.';
	}else{
	    var msg = 'The photos you selected have been successfully uploaded';
	}
	update(data,
	       (function(msg,action,index){
		       return function(response){
			       var r = evalJson(response.replace('\r\n',''));
				   if(r.error){
				       handleUpdatePhotoInfoError();
					   return;
				   }
				   var s = ss;
				   if(action === 'delete'){
				       cssjs('remove',s.slideBox,'deleting');
					   s.doDelete(index);
				   }else{
				       s.callUploadCallback();
				   }
				   var photos = r.resource.photos;
				   otherinfo.photos = schmapit.photos = photos;
				   if(photos.indexOf('@') !== -1){
				       s.medium = true;
				   }
				   //ss.doResize();
			       topAlert.call(msg,4000);
	               overlay.hide();
			   };
		   })(msg,action,index),
		   handleUpdatePhotoInfoError
	    );
}
function handleUpdatePhotoInfoError(){
	topAlert.call('Sorry, some error happended. Please try again later.');
	ss.names = schmapit.photos ? schmapit.photos.replace('@','').split(',') : [];
	if(ss.slideBox){cssjs('remove',ss.slideBox,'deleting');}
	overlay.hide();
}
function showIframe(){
    showIframe.loaded = true;
	if(showIframe.timePassed){
	    cssjs('add',$('upload_container'),'loaded');
	}
}
function showUploadBox(){
    showIframe.loaded = showIframe.timePassed = false;
	if(!this.inited){
		var div = document.createElement('div');
		div.id = 'upload_container';
		div.innerHTML = '<div class="round photo-iframe-loading-box"><img class="photo-iframe-loading" src="/image/loading.gif" /></div><iframe id="photoiframe" name="photoiframe" frameborder="0" onload="showIframe()" src="/views/upload.html">';
		document.body.appendChild(div);
		this.inited = true;
	}
	var photoIframeElm = $('photoiframe');
	cssjs('remove',photoIframeElm.parentNode,'loaded');
	photoIframeElm.src = '/views/upload.html?' + new Date().getTime();
	setTimeout(function(){
			showIframe.timePassed = true;
			if(showIframe.loaded){
				cssjs('add',$('upload_container'),'loaded');
			}
		},800);
	overlay.show({elm:$('upload_container')});
}	
function showUploadLink(){
    var a = document.createElement('a');
	a.innerHTML = 'Add photos';
	a.className = 'add-more-link';
	a.inited = false;
	a.onclick = showUploadBox;
	ss.nav.parentNode.appendChild(a);
}
init();
