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 fb_login_url = '';
if(!window.schmap){window.schmap = {};}
schmap.cursorArray = ['zoomin', 'zoomout', 'mapview', 'satelliteview', 'mapimg'];
schmap.types = {'m': 'ROADMAP', 's': 'SATELLITE'};
var schmapMapType = {
    'm':['mapselected','satellite'],
    's':['map','satelliteselected']
};
var msgs = {
    makeschmapSucess: 'Your schmap is ready to tweet! (Or you can first add a title, notes, photos etc.)'
};
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:[]
};
schmap.inputs = 'text pagetitle eventtime_text placename gaddress'.split(' ');
function setCursor(arr,cursor){
    for(var i = 0, l = arr.length; i < l; i++){
       var elm = $(arr[i]); 
	   if(elm){
           elm.style.cursor = cursor;
	   }
    }
}
function loadGoogle(callback, cursor) {
    if (!googleLoaded) {
        googleLoaded = true;
		cursor = cursor || 'wait';
		document.body.style.cursor = cursor;
        setCursor(schmap.cursorArray, cursor);
		loadedGMap.callback = callback;
        addScript('http://maps.google.com/maps/api/js?sensor=false&callback=loadedGMap');
    }
}

function getMWheelDelta(event) {
    event = 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) {
		loadGoogle();
		loading = true;
    }
}

function zoominout(n) {
	delta += n;
	loadGoogle();
}

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 = mdownXPos - event.screenX ;
            deltaY = mdownYPos - event.screenY;
            loadGoogle();
        }
    }
}
var gotoFinalStage = function(){
    var inited = false;
    return function(){
        if(inited){return;}
	textInputs.init(schmap.inputs);
	infolink.init();
	hashtag.init();
    ads.init();
    edit.gotoEditStage();
    if(!schmap.ownEditing){
	    edit.set(resource);
	    setTimeout(function(){
	        topAlert.call(msgs.makeschmapSucess, 12000);
	        updateReachNum(-2);
	   },1000);	
	}else{
    edit.showEditing();
}
	tip.passed = false;
	schmap.finalStage = true;
	$('overlayparent').className = 'final-stage';
	cssjs('remove',document.body,'changing-location');
        inited = true;
    }
}();
function showmap(){
    if(tip.passed){gotoFinalStage();}
	tip.maploaded = true;
    
    if(schmap.showmap) {return;}
	schmap.showmap = true;
	if(schmap.editing){gmap.init();}
	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(deltaX,deltaY);
                    }}, 200);
    schmap.showmap = true;
}
var marker = (function(){
    var gmarker = null, code;
	function getIconData(iconcode){
	    var data = icondata.getItem(function(item){
		        return item.iconcode === iconcode;
		    });
		if (data != null)
			return data.item;
	}
	function getMakerImage(icondata){
	    var size = new google.maps.Size(icondata.bigiconwidth, icondata.bigiconheight),
		    anchor = new google.maps.Point(icondata.bigiconwidth*icondata.bigiconanchorx/100, icondata.bigiconheight*icondata.bigiconanchory/100);
		return new google.maps.MarkerImage('/image/mapicons/' + icondata.bigiconpath, size, null, anchor)
	}
	function make(options){
	    if(gmarker){return gmarker;}
		var iconcode = options.iconcode || 'A010',
			latlng = new google.maps.LatLng(options.lat, options.lng);
		gmarker = new google.maps.Marker({
		        position: latlng,
				icon: getMakerImage(getIconData(iconcode)),
				map: schmap.map,
				title: 'drag this icon to pan the map'
		    });
		code = iconcode;
	}
	function setIconcode(iconcode){		
		iconcode = iconcode || 'A010';
		gmarker.setIcon(getMakerImage(getIconData(iconcode)));
		code = iconcode;
	}
	function set(o){
	    if(!gmarker){
		    if(schmap.map){
			    make(Object.extend(o, {iconcode: resource.iconcode}));
			}else{
			    log('no marker aa');
				return null;
			}
		}
	    if(o.iconcode){
		    setIconcode(o.iconcode);
		}
		if(o.latitude && o.longitude){
		    gmarker.setPosition(new google.maps.LatLng(o.latitude, o.longitude));log('set ', o);
		}
		if('draggable' in o){
		    gmarker.setDraggable(o.draggable);
		}log(gmarker);window.hugo = gmarker;
		return true;
	}
	function get(){
	    if(!gmarker){return null;}
		var latlng = gmarker.getPosition();
		return {latitude: latlng.lat(), longitude: latlng.lng(), iconcode: code};
	}
	function cancel(o){
	    set(o);
	}
        function addListener(type, fn){
            if(!gmarker){log('no gmarker');return;}
            google.maps.event.addListener(gmarker, type, fn);
        }
	return {addListener: addListener, make: make, set: set, get: get, cancel: cancel, getIconData: getIconData}
})();
function loadedGMap(lat, lng) {log('loadedgmap called');
    lat = lat || resource.latitude;
    lng =	lng || resource.longitude;
	function callback(){
        var latlng = new google.maps.LatLng(lat, lng),
			mapOptions = {
				zoom: (+resource.zoomlevel || 14)+delta,
				center: latlng,
				mapTypeId: google.maps.MapTypeId[schmap.types[resource.maptype]],
				mapTypeControl: false,
				navigationControl: false
			};
		var map = new google.maps.Map($('map'), mapOptions);
		schmap.map = map;
		google.maps.event.addListenerOnce(map, 'tilesloaded', showmap);
		if(loadedGMap.callback){loadedGMap.callback();loadedGMap.callback = null;}		
		initViewButton(resource.maptype);
		initMapButton();
		google.maps.event.addDomListener($('zoomin'), 'click', function(){schmap.map.setZoom(schmap.map.getZoom() + 1);});
		google.maps.event.addDomListener($('zoomout'), 'click', function(){schmap.map.setZoom(schmap.map.getZoom() - 1);});
		marker.make({iconcode: resource.iconcode, lat: lat, lng: lng});
		'icon_changed dragstart'.split(' ').forEach(function(item){marker.addListener(item, edit.showEditing);});
        icon.updateIconPosition(resource.iconcode);
        if(schmap.editing){marker.set({draggable: true});}
	}
	if(!resource.latitude){
		getUrlCallback.callback = callback;
		makeFacebookEventCallback.callback = callback;
	}else{
		callback();
	}
}

function loadGoogleApi(){log('load google api');
    var id = 'googleloadapi',
    interval = setInterval(function(){
    if(!$(id)){
       addScript('http://www.google.com/jsapi?key=' + gkey).id= id;
    }else  if(window.google && google.load){
			    clearInterval(interval);
				google.load("search", "1",{'language':'en','callback':setLocalSearch});
			}
	    }, 50);
}

function showInitStage(){
	cssjs('add',document.body,'initial');
	$('overlayparent').className = '';
	toggleSearch(1);
}

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 doSearch(flag){
    cssjs('remove', document.body, 'initial');
    tip.searched = false;
    var v = schmap.searchValue;
	if(schmap.ownEditing){
		cssjs('add',$('re_search_box'),'at-search-result');
	}
	toggleSearch(0);
	if(v.indexOf(',') === -1){
	    if(!schmap.userLocation){
		    topAlert.call('Your search term needs to include a comma, followed by a city or town.');
			flushTimeouts(tip.timeout);
			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 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';
					toggleSearch(1);
				}
		    },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 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);
	}
}
var searchControl = null;
function retriveUserprofile(response){
    if(typeof(response) === 'string'){
	    response = evalJson(response);
	}
    if(response.error){
	    checkprofile();
		return false;
	}
    userinfo = {};
    schmap.twitterResponse = schmap.editable = true;
    schmap[response.screen_name.toLowerCase()] = true;
	schmap.userLocation = response.location;
	response.xid = response.id;//the user's twitter id is accountable_xid
	delete response.id;
	profile.set(response);
	doSearch();
}
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 changeTipContent(stage){
    var a  = tip;
    a.title.innerHTML = a[stage][0];
	a.text.innerHTML = a[stage][1];
	$('overlayparent').className = 'setting-style';log('changeTipContent' + stage);
}
function showSetupStage(){
    changeTipContent('twitter');
	setupFirstStage();
}
function setupLastStage(){
    changeTipContent('map');
	tip.passed = false;
    tip.timeout[tip.timeout.length] = setTimeout(function(){
	        tip.passed = true;
			log('last stage :3 seconds passed');
	        if(tip.maploaded && resource.id){
			    gotoFinalStage();
			}log('tip.maploaded && resource.id is ' + (tip.maploaded && resource.id));
	    },tip.time);
}

function flushTimeouts(ts){
    for(var i = 0; i <ts.length; i++){
	    clearTimeout(ts[i]);
	}
}

function hightlightResult(){
    this.style.backgroundColor = '#eeeeee';
}

function delightResult(){
	this.style.backgroundColor = this.defaultColor;
}

var getUrl = function(){
	var defaultOptions = {
		adcode: 'edu161-01',
		zoomlevel: 14,
		iconcode: 'A010',
		maptype: 'm',
		display_comment: 1,
		display_rsvp: 1,
		source: 'Schmapit',
		source_type: 'Web'
	};
	function set(o){
	    o = o || {};
		for(var n in o){
		    if(o.hasOwnProperty(n) && defaultOptions.hasOwnProperty(n)){
			    defaultOptions[n] = o[n];
			}
		}
	}
	function get(o){	
		Object.extend(o, defaultOptions);
		if(schmap.batch){o.batch = schmap.batch;}
		// Are we inporting from a Facebook event? If so, need to get the details from facebook now.
		var fb_eid = '';
		var isFacebook = false;
		if(typeof queryurl !== 'undefined'){
			if(queryurl.fb_eid != null){
				isFacebook = true;
				fb_eid = queryurl.fb_eid;
			}
		}

		if (isFacebook)
		{
			var options = {
				url: '/pyapp/facebook/import_event?ajax=true&eid=' + fb_eid + '&lat=' + o.latitude + '&lng=' + o.longitude,
				onSuccess: makeFacebookEventCallback,
				onError: handleErrorResponse,
				onTimeout: handleErrorResponse
				};
			ajax(options);
		} else {
		    if(userinfo.id){
			    o.accountable = {id: userinfo.id, xid: userinfo.xid};
			}else{
			    o.accountable = userinfo;
			}
			o.reachNum = -1;
			var options = getOptions(o);
			options.onSuccess = getUrlCallback;
			options.onError = handleErrorResponse;
			options.onTimeout = handleErrorResponse;
			ajax(options);
		}
	}
	return {get: get, set: set};
}();

function toggleMaptypeButton(){
	var imgs = [$('mapview'),$('satelliteview')], postfix = 'selected', src, type = 'm';
	for(var img, l = imgs.length; l--;){
	    img = imgs[l];
            src = '/image/' + img.id.replace('view', '') + '.png';
		if(img.src.indexOf(postfix) !== -1 || (isIE6 && img.style.filter.indexOf(postfix) !== -1)){
		    src = src.replace(postfix, '');
		}else{
		    var pos = src.lastIndexOf('.');
		    src = src.substring(0, pos) + postfix + src.substring(pos);
			type = img.id.charAt(0);
		}
		if(isIE6){
		    src = PNG_style({src: src, width: 55, height: 18});
		    img.style.filter = src;
                }else{
		    img.src = src;
                }
	}
	return type;
}
function switchMapView(e) {
	if(e.target.parentNode.id !== 'mapswitch'){return;}
	var type = toggleMaptypeButton();
    if (schmap.map) {
        schmap.map.setMapTypeId(google.maps.MapTypeId[schmap.types[type]]);
    }else {
        loadGoogle();
    }
}
function initViewButton(maptype){
    var type = maptype || 'm', buttonParent = $('mapswitch');
	var mapview =  PNG_html({id: 'mapview', src: '/image/'+schmapMapType[maptype][0]+'.png', width: 55, height: 18});
	var satelliteview =  PNG_html({id: 'satelliteview', src: '/image/'+schmapMapType[maptype][1]+'.png', width: 55, height: 18});
	buttonParent.innerHTML = mapview + satelliteview;
	Handler.add(buttonParent, 'click', switchMapView);
}
function gotoForm(){
    $('footer').style.zIndex = '';
    if(tip.passed || !tip.oneresult){
	    setupLastStage();
	}
        schmap.showmap = false;	
	var r = this.result,
	    lat = r.lat,
	    lng = r.lng,
		o = {
		   latitude: lat,
		   longitude: lng,
		   address: r.addressLines.join(', ')
		};
	loadedGMap = loadedGMap.bind(null, lat, lng);
	o.gaddress = o.address;	log('bind ' + lat + ', ' + lng);
	if(r.titleNoFormatting !== r.streetAddress){
	    o.placename = r.titleNoFormatting;
	}
	$('direction').href = 'http://www.google.com/maps?daddr=' + lat + ',' + lng;
	
	if(schmap.map){
	    o.draggable = true;
		marker.set(o);log('marker is ' + hugo);
	    schmap.map.setCenter(new google.maps.LatLng(lat, lng));
	}else{
	    loadGoogle(false, 'default');
	}
	if(schmap.ownEditing && window.singlepage){
		textInputs.set(o);
	}else{
	    getUrl.get(o);
	}
}

function gotoPage() {
    schmap.localSearch.gotoPage(this.page);
}

function handleErrorResponse(r){
	topAlert.call('Sorry, this service is temporarily unavailable, please try again later.');
	$('overlayparent').className = 'search-result';
	return;
}

var initMapButton = (function (){
    var inited = false;
	function init(){
	    if(inited){return;}
		inited = true;
		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;
		Handler.addOnce($('zoomin'), 'click', zoominout.bind(null, 1));
		Handler.addOnce($('zoomout'), 'click', zoominout.bind(null, -1));
	}
	return init;
})();


function goBackToNormal(){
	$('outestDiv').className = 'normal-state';
	var arr = ss.imgArr;
	if(arr && arr.length > 0){
	    if(singlepage && document.location.search==='?a'){ss.doResize();}
		if(ss.medium && $('photosize_m')){
		    $('photosize_m').checked = 'checked';
		}else if($('photosize_s') && ss.length < 1){
		    $('photosize_s').checked = 'checked';
		}
		var elm = $('text_content');
		if(elm.innerHTML.trim()){
		    cssjs('remove', elm, 'no-tweet-text');
		}else{
		    cssjs('remove', elm, 'no-tweet-text');
		}
		slideImgs.destory();
	}
	hideElement('re_search_box');
        marker.set({draggable: false});
	if($('educate')){
	    $('educate').className = '';
	    hideElement('state');
	}
}

function makeFacebookEventCallback(response) {
    if(!response){
        handleErrorResponse();
        return;
    }
    r = evalJson(response.trim());
    log(r);
    if(r.error){
        handleErrorResponse();
        return;
    }
    if(tip.noresulttimeout){
        clearTimeout(tip.noresulttimeout);
    }
    if(r.code === 0 && r.newurl && r.resource_id && r.addressable_id && r.accountable_id)
    {
        var arr = ['eventtime', 'eventtime_text', 'latitude', 'longitude', 'gaddress', 'hashtag', 'pagetitle', 'text', 'photos'];
        var a = {}, b = r.data;
        for(var i=0, l=arr.length; i<l; i++)
        {
            var item = arr[i];
            if(b[item])
            { 
                a[item] = b[item];
            }
        }
        resource = cloneObj(b);
        resource.id = r.resource_id;
        resource.accountable_id = r.accountable_id
        resource.maptype = 'm';
        resource.iconcode = 'A010';
        resource.zoomlevel = 14;
        a.url = r.newurl;
        addressable.url = a.url;
        addressable.id = r.addressable_id;
        resource.display_rsvp = 1;
        if (b['photos'] != '') {
            resource.photos = b['photos'];            
            var arr = resource.photos.replace('@','').split(',');
            ss.medium = resource.photos.indexOf('@') !== -1;
            if(arr && arr.length > 0){
                for(var i=0; i < arr.length; i++){
                    if(arr[i]){
                        ss.init(arr, 'singlepage');
                        break;
                    }
                }
            }
        }
        
        var inputs = [$('pagetitle'),$('eventtime_text'),$('placename'),$('gaddress'),$('text')];
        a.createat = new Date().toString4();
        if (r.accountable_id) {
            userinfo.id = r.accountable_id;
        }
        
        schmap.editing = schmap.editable = true;
        	    
        if(typeof makeFacebookEventCallback.callback === 'function'){
            makeFacebookEventCallback.callback();
            makeFacebookEventCallback.callback = null;
        }
        
        try
        {
            var ref = window.opener;
            if(ref)
            {
                if(typeof(ref.addRow) === 'function')
                {
                    for(var n in a)
                    {
                        if(a.hasOwnProperty(n))
                        {
                            a[n] = encode(a[n]);
                        }
                    }
                    ref.addRow(a);
                }
            }
        }
        catch(err){}

    }
    else
    {
        topAlert.call(r.message);
    }
}
function getUrlCallback(r){
	r = checkResp(r);
	if(!r || r.error || !r.addressable){
	    handleErrorResponse();
		return;
	}
	if(tip.noresulttimeout){
		clearTimeout(tip.noresulttimeout);
	}
	var url = r.addressable.url;
	resource = cloneObj(r.resource);log(resource);
	delete resource.accountable;
	JSON.update(addressable, r.addressable);
	JSON.update(userinfo, r.resource.accountable);
	schmap.editing = schmap.editable = true;
        if(typeof getUrlCallback.callback === 'function'){
        getUrlCallback.callback();
        getUrlCallback.callback = null;
    }
	try{
        var ref = window.opener;
		if(ref){
		    if(ref && typeof(ref.addRow) === 'function'){
				ref.addRow(Object.extend({url: url}, resource));
			}else{
			    if(ref.schmapcallback){ref.schmapcallback(r);}
			}	
		}
	}catch(err){}
}


function addBackList(user,address){
    var status = address.split('=')[1];
	status = parseInt(status, 10);
	if(status === 1){
	    var desc = 'added to';
	}else if(status === 0){
	    var desc = 'removed from';
	}else{
	    topAlert.call('The address is not valid');
	    return;
	}
	data = {accountable:{'screen_name':user,'blacklist':status}};
	callback = function(){topAlert.call('The user ' + user + ' has been ' + desc +' the blacklist');};
	update(data,callback);
}

var gmap = function(){
    var inited = false;
	function getMaytype(){
	    return schmap.map.getMapTypeId() === google.maps.MapTypeId.ROADMAP ? 'm' : 's';
	}
	function get(savezoomandtype){
	    var mapinfo = Object.extend({}, marker.get());
		if(schmap.map){
			mapinfo.zoomlevel = schmap.map.getZoom();
			mapinfo.maptype = getMaytype();
		}
		return mapinfo;
	}
	function set(o){log('set gmap');
		if(schmap.map && o.maptype){
			var maptype = getMaytype(); 
			if(maptype !== o.maptype){
				schmap.map.setMapTypeId(google.maps.MapTypeId[schmap.types[o.maptype]]);
				toggleMaptypeButton();
			}
			schmap.map.setZoom(o.zoomlevel);
			var lat = o.latitude,
				lng = o.longitude;
			$('direction').href = 'http://www.google.com/maps?daddr=' + o.latitude + ',' + o.longitude;
			marker.set(o);
			icon.updateIconPosition(o.iconcode);
		}
	}
	function cancel(o){
	    set(o);
	}
	function init(){
	    var callback = function(){
		    inited = true;
			'zoom_changed projection_changed dragstart maptypeid_changed'.split(' ').forEach(function(item){
					google.maps.event.addListener(schmap.map, item, edit.showEditing);
				});
			icon.init();
			showElement('mapswitch');
			edit.register('gmap');
		};
		if(!inited){
			loadGoogle(callback);
			if(schmap.showmap){
			    callback();
			}
		}
	}
	return {cancel: cancel, init: init, set: set, get: get};
}();

function reportOnstatechange(){
    if(this.readyState === 'loaded'){
		    setTimeout(checkprofile,100);
	}
	return;
}
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 checkprofile(){
	if(!schmap.twitterResponse){
	    topAlert.call('Twitter did not recognize your username');
		showInitStage();
	}
}


function onDragend(){
    var latlng = this.getLatLng();
	lat = latlng.lat();
	lng = latlng.lng();
	$('direction').href = 'http://www.google.com/maps?daddr=' + lat + ',' + lng;
	edit.showEditing();
}

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 handleUpdatePhotoInfoError(){
	topAlert.call(defaultErrMsg);
	ss.names = resource.photos ? resource.photos.replace('@','').split(',') : [];
	if(ss.slideBox){cssjs('remove',ss.slideBox,'deleting');}
	overlay.hide();
}
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(',') : ''};
	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';
	}log(data);
	update(data,
		   function(r){
			   var s = ss;
			   if(action === 'delete'){
				   cssjs('remove',s.slideBox,'deleting');
				   s.doDelete(index);
			   }else{
				   s.callUploadCallback();
			   }
			   if(r.resource.photos.indexOf('@') !== -1){
				   s.medium = true;
			   }
			   topAlert.call(msg,4000);
			   overlay.hide();
		   },
		   handleUpdatePhotoInfoError
	    );
}

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);
}
var ss = {
	bigImg: new Image(),
	slideMaxHeight: 575,
	oneImageHeight: (561 - 57),//57 is the thumbnail's height;
	names: [],
	thumbnail: '_thumbnail',
	init: function(arr,flag){
	    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 = addressable.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, 10);
						}
						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, 10) - 1] = '';log('this.names is ' + this.names.join(','));
			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, 10);
		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.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="edit.showEditing();" id="photosize_s" name="photosize" value="s" />small (like this)</label></p>' + 
							'<p><label><input ' + (this.medium ? 'checked="checked" ' : '') + 'type="radio" onclick="edit.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 || !window.singlepage){return;}
	    this.popup = true;
		Handler.add($('hideslide'), 'click', function(){
				ss.popup = false;
				ss.showImg(slideImgs.stop());
				$('overlayparent').className = 'single-page-start';
				ss.startAutoSlide();
			});
		var titleElm = $('pagetitle_content');
		if(titleElm && titleElm.innerHTML){
			$('slide_title').innerHTML = titleElm.innerHTML;
		}else{
			$('slide_title').innerHTML = '&nbsp;';
		}
		$('overlayparent').className = 'slide-show';
		if(isIE){setTimeout(function(){$('schmapitform').parentNode.style.zoom = '1';}, 10);}//fix ie6 layout bug
slideImgs.init(resource.photos, n);
	this.stopAutoSlide();
	},
	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 showPostToFacebook(fb_username) {

    fb_node = $('fb_post_area');
    while (fb_node.hasChildNodes()) {
        fb_node.removeChild(fb_node.firstChild);
    }
    var p = document.createElement('p');
    p.innerHTML = '<input type="checkbox" id="fb_checkbox" checked="true" />&nbsp;&nbsp;Also post to <strong>Facebook&nbsp;-&nbsp;</strong>';
    p.innerHTML += ('Connected as ' + fb_username);
    fb_node.appendChild(p);
}
function handleTweetLink(item){
    var ref = window.opener;
    if(ref)
    {
        if (ref.fb_user != null) {
            fb_user_name = ref.fb_user.name;
            showPostToFacebook(fb_user_name);
        }
    }

    var elm = $('tweet_popup');
	if(!item){
	    item = Object.extend(cloneObj(resource), {url: addressable.url});
	}log(item);
	createTweetText(item);
    overlay.show({elm: elm});
	set_pa_user_option();
}
function showCreatStage(anchor){
    overlay.showcallback = function(){
	    $('footer').style.zIndex = '5000';
		showElement('back');
	};
	overlay.hidecallback = function(){
	    $('footer').style.zIndex = '0';
		hideElement('back');
	    $('introtext').innerHTML = 'Share a place or event with your Twitter followers';
	};
    overlay.show({clickhide:true});
    $('introtext').innerHTML = 'Get a schmap for your ' + anchor + ':';
}

function toggleSearch(flag){
    var elm = $('tryitout'),
	    action = '';
	if(flag){
	    action = 'remove';
	    elm.removeAttribute('disabled');
	}else{
	    action = 'add';
		elm.setAttribute('disabled','true');
	}
	cssjs(action, $('initState'), 'disabled');
}
function gotoEdit(){
    edit.gotoEditStage();
	textInputs.init(schmap.inputs);
	infolink.init();
	hashtag.init();
	gmap.init();
	ads.init();
	if(resource.iconcode){
	    edit.set(resource);
    }
    if (!schmap.ownEditing) {
	    profile.setFromCookie();
	}
}
function getmap(user, address){
	user = user || window.loggedin_username;
	if(!user){
	    topAlert.call('Your Twitter username and an address/venue are both required');
	    return false;
	}
	if(!address){
	   topAlert.call('An address/venue is required');
	   return false;
	}
	address = address.replace(/\+/g,' ');
	if(address.charAt(0) === '#'){
	    var pos = address.indexOf(' ');
		schmap.batch = address.substring(0,pos);
	    address = address.substring(pos+1);
	}
	cssjs('remove', document.body, 'initial');
	edit.gotoEditStage();
	edit.showSearch();
	schmap.searchValue = address;
	if(!/\/views\/admin|demo|plugins/.test(document.location.pathname)){
	    profile.setFromCookie();
	    doSearch(1);
	}else{
		var url = 'http://twitter.com/users/show/' + user + '.json?callback=retriveUserprofile';
		addScript(url,getProfileScript);
		showSetupStage();
		toggleSearch(0);
	}
}
(function(){
	var address = FormElement('address'),
	    usernmae = FormElement('username'),
		loc = window.location;
	usernmae.addEvent('focus', function(){toggleSearch(1);});
	address.addEvent('focus', function(){toggleSearch(1);});
	document.schmapit.onsubmit = function(){
		if (document.location.search.match('u=')) {
			usern = document.location.search.split('u=');
			usern = usern[1].split('&');
			usern = (usern[0] != "")?usern[0]:usern;
			getmap(usern, address.getValue());
		}
		else
			getmap(usernmae.getValue(), address.getValue());
		return false;
	};
	if(loc.pathname.length < 2 || loc.pathname === '/new'){
		if(typeof(queryurl) !== 'undefined'){
		   if(queryurl.address){
				address.setValue(queryurl.address);
				usernmae.setValue(loggedin_username || '');
				getmap(loggedin_username, queryurl.address);
				loc.replace('#');
			}
		}
    }
    var a = loc.search;
	if(a && loc.pathname.indexOf('admin') !== -1){
		if(a.indexOf('ownstaff') !== -1){
			var staff = a.split('=')[1];
			if(staff){
				var offset = new Date().getTime() + 365*24*3600*1000;
				cookie.set('ownstaff', staff , new Date(offset), '/','.schmap.it');
			}
		}
	}
})();
