var schmapplet = {_loading: true, selected: 0, view: 'map',
                  IEquirks: b_version.search(/MSIE/i) != -1,
                  cycleTime: 6, mapIcons: {},
                  placesById: {}, _placesCount: 0
				  };
logTime('mini starting load this page');
var cycling_d = null;
var flash_d = null;
var Map_object = {};
var autoPlaying = true;
var autoPlayPaused = false;
var autoPlayStopped = false;
var autoPausedByParent = false;
var inMapRegion = false;
//var _global = this;
var settings = {};
var flashTime = 0.5;
var Placeall = [];
var colorset;
var xmlAccess = new XMLAccess();
var num = 0;
var DefaultIconCode = 'D000';
var mapiconspath = '';
var pageiconpath = '';
var beforSetupCalled = false;
var PlaceId = '';
var xmlHttpPhoto;
var gmapTime = 0.1;
var showed=false;
var guide_hotswap_showed=false;
var section_hotswap_showed=false;
var isPhotoView = false;
var isStatsView = false;
var photo_cc = null;
var subtitle = '';
var initPlaceId = '';
var sectionHtml = '';
var guideHtml = '';
var topleft;
var bottomright;
var loadingNewSchmapplet = false;
var loadingNewMap = false;
var tabs = [];
var tabViews = ['map', 'details', 'photos', 'stats', 'schedule'];
var minTemplate=true;
var schmappletBorder = 3;
var Panelborder = 4;
var stripBackgroundColor = 15;
var colorset_template;
var initialized = templateChanged = 0;
var citycode;
var placesChecked = 1;
var loadNewPlace = false;
var isPlaceOnly = false;
var noPhotosAtAll = true;
var photoTabSN = -1;
var isFishined = 0;
var countriesMenu = {};
var navMenu = {};
var sectionLoaded = 0; // add a flag to know the nav menu on guide-iframe loaded or not
var guideLoaded = 0 ;  // add a flag to know the city menu on guide-iframe loaded or not
var guideSrcXml = "/common/minicitiesmenu.html?/xml/mininavmenu.xml&Countries";
var sectionSrcXml;
// define them global,because more than 2 place use that;
var isGuideSchmapplet = false;
var loadSchmapPlacesFlag = true;
var showMyPlace = true;
var isCreatePhoto = false;
var changedUrl = '';
var loadingEmptyGuide = false;
var truncationNeeded = 1;  //for normal minimenu
var subTitleFromPlaces;
var hasTwoThumsInPlaceStrip = false;
var newDefaultDetailsStripColor = 'FFFFFF';
var defaultSchmapYellowColor = 'FAF5BB';
var fixedPlace = null;
schmapplet.hasStats = false;
var unbreakIERun = 0;
schmapplet.customizePage = '/templates/customize.html';
schmapplet.frameWidth = 200;
schmapplet.frameHeight = 380;
var guide_url;
var ShowMenus = null;
var showMenusFromUrl = null;
var showMenusFromMeta = null;
var showTwoMenus = [1,1];
var autoplayUrl = null;
var zoomLevel; // define  this to check this value is from xparam.sjs or the meta tag.
schmapplet.months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var showingOrigMap = false;
var mapLogo = [];
var getThisWidgetPauseTimerId = 0;
var iframeCode = '';
var removeLinks = false;
var analyticsHooks = {'widgetImpression': {text:'/%si%', isRegistered:false},
                     'getThisWidget': {text: '/events/%si%/mouseover/getthiswidget', isRegistered:false},
                     'getthiswidget5s': {text: '/events/%si%/mouseover/getthiswidget5s', isRegistered:false},
                     'belowTextClick': {text: '/events/%si%/click/outsidetext', isRegistered:false},
                     'belowTextOver': {text: '/events/%si%/mouseover/outsidetext', isRegistered:false},
                     'copyCodeLeft': {text: '/events/%si%/click/left/codetocopy', isRegistered:false},
                     'copyCodeRight': {text: '/events/%si%/click/right/codetocopy', isRegistered:false},
                     'customizeLink': {text: '/events/%si%/click/customize', isRegistered:false},
                     'placeGameLink': {text: '/events/%si%/follow/tabs/place', isRegistered:false},
                     'schedGameLink': {text: '/events/%si%/follow/tabs/sched', isRegistered:false},
                     'statsTabClick': {text: '/events/%si%/click/tabs/stats', isRegistered:false},
                     'schedTabClick': {text: '/events/%si%/click/tabs/sched', isRegistered:false},
                     'mapTabClick': {text: '/events/%si%/click/tabs/map', isRegistered:false},
                     'mapIconClick': {text: '/events/%si%/click/mapicon', isRegistered:false},
                     'topNavOver': {text: '/events/%si%/mouseover/menus/topmenu', isRegistered:false},
                     'topNavClick': {text: '/events/%si%/follow/menus/topmenu', isRegistered:false},
                     'secondNavOver': {text: '/events/%si%/mouseover/menus/secondmenu', isRegistered:false},
                     'secondNavClick': {text: '/events/%si%/follow/menus/secondmenu', isRegistered:false},
                     'textZoom': {text: '/events/%si%/click/zoomtostadiumtext', isRegistered:false},
                     'mapZoom': {text: '/events/%si%/click/zoomtostadiummap', isRegistered:false},
                     'forward': {text: '/events/%si%/click/buttons/forward', isRegistered:false},
                     'back': {text: '/events/%si%/click/buttons/back', isRegistered:false}
                     };
function tabOne() {
    this.tabType = '';
    this.tabRealView = '';
    this.tabText = '';
    this.tabDiv = null;
	this.displayedObj = [];
}

function Photo(attrs) {
    //this.prototype = attrs;
	if(settings['templateLayout']=='geotweet'){
	var prefix = attrs['path'].substr(0,3);
	}else {
	var prefix =  '';
	}
    this.abpath = attrs['abpath'];
    this.path = prefix + attrs['path'];
    this.link = attrs['link'];
    this.licenseurl = attrs['licenseurl'];
    this.licensecode = attrs['licensecode'];
    this.username = attrs['username'];
	this.t_path = prefix + attrs['t_path'];
}

function createUserPlace(uplace) {
	var place;
	try {
    	place = new PlaceObj();
	} catch (e) {}

    var m = uplace.match(/(.[^\|]+)[\|](.[^\|]+)[\|](.[^\|]+)[\|](.[^\|]+)/i);
    place.id = m[1];
    place.name = m[3];  
    place.sdesc = m[4];  
    place.ldesc = '';
    place.schmapIcon = m[1];
	place.normalMapIcon = m[1];
    place.geo = m[2].split(/,/);
    logDebug("place.geo:" + place.geo);
  
    place.photo_objs = [];
  
    // 2 - sticky places added by user via url
    place.stickyPlaceType = 2;

    place.zoomedIn = false;
	
    return place;
}

function setCurrentCounter (num,spanWidth) {
    if(num == ''){
			$('counter-current').innerHTML = ' ';
	}else if(typeof(settings.PlaceNumerText) != 'undefined'
            && settings.PlaceNumerText.length > 0) {
		if(typeof(spanWidth) == 'undefined' 
		   || typeof(spanWidth) == 'object'){
		     spanWidth = $('view-panel').clientWidth;
		   }
		if(spanWidth +6 <=160 && tabs.length >=3){
		   $('counter-current').innerHTML = "#"+num;
		   return;
	   }
	  var placeNum = settings.PlaceNumerText.replace('%1',num);
	  placeNum = placeNum.replace('%2',schmapplet.places.length);
	  $('counter-current').innerHTML = placeNum;
    } else {
	  var counterCurrentText = num + ' of  ' + schmapplet.places.length;
	  $('counter-current').innerHTML = counterCurrentText;
   }
}

function createPlace(placeNode) {
    var count = 0;
    var place = new PlaceObj(placeNode);
    var pathsrc;
    var username;
    var links;
    var licenseurl;
    var licensecode;
    var desc = '';
    if(place.schmapIcon.length == 0) {
        place.schmapIcon = DefaultIconCode;
    }

    if(place.normalMapIcon.length == 0) {
        place.normalMapIcon = DefaultIconCode;
    }

    if(settings.UseFirstNormalIcon) {
        if(schmapplet.firstNormalIcon) {
            place.normalMapIcon = schmapplet.firstNormalIcon;
        } else {
            schmapplet.firstNormalIcon = place.normalMapIcon;
        }
    }
 
	if((typeof(schmapplet.usingSTemplate) != 'undefined')
            && schmapplet.usingSTemplate == 1) {
	    if(place.tel.length){
		    place.sdesc = place.tel[0];
			
			if(place.url!=='' && settings['StripTitleLink'] !== 'true'){
				var content = new StringBuffer();
				if(schmapplet.disableLinks){
				content.append(place.sdesc);
				}else{
				content.append('<a href="').append(this.url).append('" target="blank">').append(place.sdesc).append('</a>');
				}
				place.sdesc = content;
			}
		}
	}
    var telnumber = xmlAccess.getSingleChildText(placeNode, 'vcard:TEL/rdf:value');
    place.telnumber = telnumber;
    var street = xmlAccess.getSingleChildText(placeNode, 'vcard:ADR/vcard:Street');
    place.street = street;
    place.zoomedIn = false;
    var photoNodes = xmlAccess.getChildren(placeNode, 'schmap:Photo');
    if(!photoNodes) {
        photoNodes = [];
    }
    place.photo_objs = [];
	place.photo_IMG = [];
	place.photo_thumb = IMG({src:''});
    var wcities_photos = [];
    var wcities_flag = true;
    place.zoomedIn = false;
	 forEach(photoNodes, function(photo_obj) {
        schmapplet.photos.push([place, count++]);
        links = xmlAccess.getSingleChildText(photo_obj, 'schmap:link');
        username = xmlAccess.getSingleChildText(photo_obj, 'dc:author');
        var path = xmlAccess.getSingleChildText(photo_obj, 'schmap:path');
		var t_path = xmlAccess.getSingleChildText(photo_obj, 'schmap:t_path') || path;
        var rights = xmlAccess.getFirstChild(photo_obj, 'dc:rights');
        //logDebug("rights.nodeName:" + rights);
        licenseurl = "";
        licensecode = "";
        if(rights) {
            licenseurl = xmlAccess.getSingleChildText(rights, 'cc:license');
            var lurlnode = xmlAccess.getFirstChild(rights, 'cc:license');
            licenseurl = xmlAccess.getAttributeNS(lurlnode, 'rdf', 'resource');
            licensecode = xmlAccess.getSingleChildText(rights, 'dc:licensecode');
        }
        if(licenseurl == document.location.href) {
            //if the license is not provided,
            //it displays here as the location.href
            licenseurl = "";
        }
        if(licensecode != 9){
            noPhotosAtAll = false;
        }

        var attrs = {'link': links, 'username': username,
                     'path': path, 'licenseurl': licenseurl,
                     'licensecode': licensecode, 't_path': t_path};
        var photo = new Photo(attrs);

		if(licensecode != 9){
		    wcities_flag = false;
            place.photo_objs.push(photo);
		} else {
            wcities_photos.push(photo);
		}
    });

    place.wcities_only = false;
    place.wcities_photos = [];
	if (wcities_flag) {
        place.wcities_only = true;
        place.wcities_photos = wcities_photos;
	}

    if(place.photo_objs.length > 0){
        links = (place.photo_objs[0].link);
    	licenseurl = (place.photo_objs[0].licenseurl);
    	licensecode = (place.photo_objs[0].licensecode);
    	username = place.photo_objs[0].username;
    }else{
        links='';
    	licenseurl='';
    	licensecode='';
    	username='';

	}

    var defaultImage = IMG(null);
    if(!place.photo_objs.length) {
        defaultImage = PNG({src: settings.DefaultPlace, width: 65, height: 48});
    }
    if( schmapplet.sportsSchedule){
		var reg = new regionObj();
		if(schmapplet.pcodeArray.length == 0){
			schmapplet.pcodeArray.push(place.zip);	
		schmapplet.regionArray.push(reg);
		schmapplet.regionArray[0].regionArray.push(place.region);
		schmapplet.regionArray[0].placeNum.push(schmapplet._placesCount+1);
		schmapplet.regionArray[0].url.push(place.url);
		schmapplet.regionArray[0].played.push(place.tel.length);
		}else{
			for(i=0;i<schmapplet.pcodeArray.length;i++){
			    if(place.zip == schmapplet.pcodeArray[i]){
                      schmapplet.regionArray[i].regionArray.push(place.region);
					  schmapplet.regionArray[i].placeNum.push(schmapplet._placesCount+1);
					  schmapplet.regionArray[i].url.push(place.url);
					  schmapplet.regionArray[i].played.push(place.tel.length);
					  break;
					}else if(i==(schmapplet.pcodeArray.length-1)){
					schmapplet.pcodeArray.push(place.zip);
					schmapplet.regionArray.push(reg);
					var k = i+1;
		            schmapplet.regionArray[k].regionArray.push(place.region);
					schmapplet.regionArray[k].placeNum.push(schmapplet._placesCount+1);
					schmapplet.regionArray[k].url.push(place.url);
					schmapplet.regionArray[k].played.push(place.tel.length);
					break;
					}
			}
		}
	}
	 schmapplet.placesById[place.id] = schmapplet._placesCount++;
    return place;
}

function repositionPlaceStripIcons (spanWidth){
    try{
        var bodyH = document.body.clientHeight;
        if($('schedule')&&$('scheduleborad')) {
            var temBottom = parseInt($('schedule').style.bottom) - 34;
            var temH = bodyH - 37 - 75 - temBottom - schmapplet.advertH;
			if(isGuideSchmapplet) {
                setStyle('scheduleborad',{'height':temH+ 'px'});
            } else {
			var temH = bodyH- 75 - 37- temBottom + $('subtitle-div').clientHeight - schmapplet.advertH;
                setStyle('scheduleborad',{'height':temH + 'px'});
            }
           jugdeArticle();
        }
        if($('stats')) {
            var temBottom1 = parseInt($('stats').style.bottom) - 34;
            setStyle('statsContent', {'height':bodyH - 37 - 75 - temBottom1 - schmapplet.advertH + 'px'});
        }
    }catch(e){}
    if (hasTwoThumsInPlaceStrip)
    {
        var marginLeft =  1;
        if (spanWidth <= 194)
        {
            marginLeft = (((spanWidth / 2) - 30) / 2) - 12;
        }
        else
        {
            marginLeft =  ((spanWidth - 194) / 2) + 21;
        }
        if(isIE6)
        {
            marginLeft = marginLeft / 2;
        }
        var leftMarginTxt = marginLeft + 'px';
        var rightMarginTxt = marginLeft + 'px';

        setStyle('place-thumb-left',{'margin-left':leftMarginTxt});
        setStyle('place-thumb',{'margin-right':rightMarginTxt});
    }else{
	    setStyle('place-thumb-left',{'margin-left':''});
        setStyle('place-thumb',{'margin-right':''});
	}
	logTime("repositionPlaceStripIcons, 3");
    if(!isGuideSchmapplet) {
       var titleWidth = getElementDimensions('title-div').w - 13;
       var myTitle = getTrunction('title',titleWidth,7);
       $('title').innerHTML = myTitle; 
    }
    var myTxt = getTrunction('TitleIn',spanWidth,9);
    $('TitleIn').innerHTML = myTxt;
	if($('place-thumb-left').style.display != 'none')
       var thrumbLeftW = getElementDimensions('place-thumb-left').w;
    else 
       var thrumbLeftW = 0;
	if($('place-thumb').style.display != 'none')
       var thrumbW = getElementDimensions('place-thumb').w;
    else
       var thrumbW = 0;
    var temW = spanWidth - thrumbLeftW - thrumbW -5;
	if(isIE6){
	   addElementClass('AddrLine1In','n-placeInfo');
	   var temLen = 11;
	} else 
	   var temLen = 9;
    var myTxt = getTrunction('AddrLine1In',temW,temLen);
    $('AddrLine1In').innerHTML = myTxt;
    var myTxt = getTrunctions('ShortDescIn',temW,6);
     $('ShortDescIn').innerHTML = myTxt;
    var myTxt = getTrunction('PhoneNoIn',temW,9);
    $('PhoneNoIn').innerHTML = myTxt;
    // Switch 'Schedule' to 'sch' for narrow sports schmapplets
	setCurrentCounter (schmapplet.selected + 1,spanWidth);
    if (schmapplet.sportsSchedule) {
	    var tabLen = tabs.length ;
		for (var i = 0; i < tabLen; i++ ){
		    var tab = tabs[i];
			var tabID = 'view-link' + i;
			if (spanWidth <= 180){
			    $(tabID).style.fontSize = '9px'; 
			}else{
				$(tabID).style.fontSize = '10px'; 
			}
		    for(var j=0;j<tab.displayedObj.length;j++){
				var thisObj = tab.displayedObj[j];
				//alert(spanWidth + '  '+thisObj.len);
				if(spanWidth +6 <= thisObj.len){
					tab.tabText = thisObj.name;
					$(tabID).innerHTML = tab.tabText;
					break;
				}
			}
		}	
    }
	
    if(schmapplet.map&&schmapplet.map.repositionLogos) {
        schmapplet.map.repositionLogos();
    }
}

function repositionPlaceStrip(spanWidth){
    if(typeof(spanWidth) == 'object' 
	   || typeof(spanWidth) == 'undefined'
	   || spanWidth == null)
        spanWidth = $('view-panel').clientWidth;
    repositionPlaceStripIcons (spanWidth);
    jugdeArticle();
	if($('scheduleborad'))
	jugdescroll($('schedule'));
    if(isStatsView){
		jugdescroll($('stats'));
	}
}

function regionObj(){
	this.regionArray = [];
	this.placeNum = [];
	this.url = [];
	this.played = [];
	}

function makeThumbPhotos() {
	if(schmapplet.photoMade) return;
    var spanWidth = $('place-info').clientWidth;
	var placePath = settings.SchmappletHome.replace('%uid%',schmapplet.uid);
	placePath = placePath.replace('%sid%',schmapplet.sid);
	var pngWidth = 24;
	var pngHeight = 24;
	
	if(settings['PngThumbnailSize']){
		var pngsize = settings['PngThumbnailSize'].split(',');
		pngWidth =  pngsize[0];
		pngHeight = pngsize[1];
		}
    for(var i=0; i < schmapplet.places.length; i++) {
        var place = schmapplet.places[i];
        hasTwoThumsInPlaceStrip = false;
        place.has_photos = false;
        if(!((typeof(settings.ThumbInPlaceStrip) != 'undefined')
             && settings.ThumbInPlaceStrip.match(/no/i))) {
            if((typeof(settings.UseAlternativeThumbs) != 'undefined')
               && settings.UseAlternativeThumbs.match(/true/i)
               && typeof(place.email) != 'undefined'
               && place.email.length > 0) {
                hasTwoThumsInPlaceStrip = true;
                var sportsImgs = place.email.split(' ');
				place.has_photos = true;
				if(sportsImgs.length == 2){
				   var sportImageLeft = sportsImgs[0];
				   var sportImageRight = sportsImgs[1];
				    
						place.photo_thumb = PNGck({src: placePath   + '/pictures_t/'
												 + sportImageRight,width: pngWidth, height: pngHeight});
						place.photo_thumb_left =  PNGck({src: placePath + '/pictures_t/'
												 + sportImageLeft,width: pngWidth, height: pngHeight});
				}
				
                place.photo_thumb.loaded = true;
            }else if(settings['SingleImageInDetailsStrip'] =='true' && place.email!==''){
				       place.photo_thumb =   PNGck({src: placePath + '/pictures_t/'
                                         + place.email,width: pngWidth, height: pngHeight});
					   place.has_photos = true;
					   place.photo_thumb.loaded = true;
			}else if(typeof(place.photo_objs) != 'undefined'
                      && place.photo_objs.length) {
                place.photo_thumb =   PNGck({src: placePath + '/pictures_t/'
                                         + place.photo_objs[0].path,width: pngWidth, height: pngHeight}); 
				if(schmapplet.placetweet){
					place.photo_thumb =   PNGck({src: '/me'+place.photo_objs[0].t_path,width: pngWidth, height: pngHeight});
					}
                place.photo_thumb.loaded = true;
           }
        }
	
        if(typeof(place.photo_objs) == 'undefined'
           || !place.photo_objs.length)
            continue;
        place.has_photos = true;
    }
}

function makeLargePhotos()
{
	if(schmapplet.photoMade) 
	    return;
	    
	var placePath = settings.SchmappletHome.replace('%uid%',schmapplet.uid);
	placePath = placePath.replace('%sid%',schmapplet.sid);
	
    for(var i=0; i < schmapplet.places.length; i++) 
    {
        var place = schmapplet.places[i];
        place.has_photos = false;

        if(typeof(place.photo_objs) == 'undefined'
     		|| !place.photo_objs.length)
            continue;
            
        place.has_photos = true;
        for(var j=0; j < place.photo_objs.length; j++) 
        {
            photo = place.photo_objs[j];
            var photoImg = IMG({id: 'photo', src: placePath + '/pictures/'+ photo.path});
			if(schmapplet.placetweet){
			var photoImg = IMG({id: 'photo', src:  '/me'+photo.path});
			}
			//var photoImgString =  placePath + '/pictures/'+ photo.path;
            place.photo_IMG.push(photoImg);
        }
    }
	schmapplet.photoMade = true;
}

function showPhoto() {
    var photo  =  schmapplet.places[schmapplet.selected].photo_IMG[schmapplet.selectedPhoto];
    settings['photo'] = photo;
    photo.lnk = schmapplet.places[schmapplet.selected].photo_objs[schmapplet.selectedPhoto].link;
	if(photo.lnk != ''){
	    photo.onclick = function()
	    {
	        window.open(this.lnk);
	    }
	}

	if ($('photo-p').childNodes.length > 0)
    	$('photo-p').removeChild($('photo-p').firstChild);
     if(isphotoComplete(photo)){
        $('photo-p').appendChild(photo);
     }
}

function showPhotoWhenDownloadComplete() {

    if (xmlHttpPhoto === undefined) {
    	try {// Firefox, Opera 8.0+, Safari
    		xmlHttpPhoto = new XMLHttpRequest();
    	} catch(e) {// Internet Explorer
    		try {
    			xmlHttpPhoto = new ActiveXObject("MSXML2.XMLHTTP.3.0");
    		} catch(e) {
    			try {
    				xmlHttpPhoto=new ActiveXObject("Microsoft.XMLHTTP");
    			} catch(e) {
    				logDebug("Your browser does not support AJAX!");
    				showPhoto();
    				return;
    			}
    		}
    	}
	}

    xmlHttpPhoto.onreadystatechange = function() {
        if(xmlHttpPhoto.readyState == 4) {
            if(xmlHttpPhoto.status == 200) {
                showPhoto();
            }
        }
    }

    var photo_src = '/' + schmapplet.uid + '/' + schmapplet.sid + '/pictures/' + schmapplet.places[schmapplet.selected].photo_objs[schmapplet.selectedPhoto].path;
	logDebug("1", photo_src);
	xmlHttpPhoto.open("GET", photo_src, false);
	xmlHttpPhoto.send(null);

}

function setSubtitle()
{
    if (schmapplet.uplace && showMyPlace) {
         subtitle = schmapplet.uplace.name;
    } else if (typeof(settings.MiniSubTitle) != 'undefined'
            && settings.MiniSubTitle != "undefined") {
        subtitle = settings.MiniSubTitle;
    } else {
        if (typeof(subTitleFromPlaces) != 'undefined'
                && subTitleFromPlaces.length > 0) {
            subtitle = subTitleFromPlaces;
        }
        else if (typeof(schmapplet.title) != 'undefined' && schmapplet.title.length > 0)
        {
            subtitle = schmapplet.title;
        }
        else if (typeof(schmapplet.subtitle) != 'undefined'
                && schmapplet.subtitle.length > 0)
        {
            subtitle = schmapplet.subtitle;
        } else {
            subtitle = ' ';
        }
    }
}

function loadPlaces() {
    schmapplet.firstNormalIcon = '';
    
    if (settings.HideInfoPanel != 'yes' ) {
	if(typeof(xparams) != 'undefined' 
		  &&typeof(xparams.infoIcon) != 'undefined'
	      && xparams.infoIcon.length > 0) {
	    $('infoEle').innerHTML = PNG_html({'src':xparams.infoIcon,'width':13,'height':13});
	}else{
		//if(schmapplet.IEquirks)
		   $('infoEle').innerHTML = PNG_html({'src':' /images/minitemplate/pageicons/info.png','width':13,'height':13});
	}
        connect('infoEle','onmouseover',showMyPanel);
        connect('infoEle','onmouseleave',hideMyPanel);
        connect('copyright-hotswap-div','onmouseover',showMyPanel);
        connect('copyright-hotswap-div','onmouseout',hideMyPanel);
    }

	if (typeof(settings.FeedbackLink) != 'undefined'
	&& settings.FeedbackLink.length > 0 && $('feedback')) {
	   showElement('feedback');
	    $('feedbackHref').onclick = function(){       
		   window.open(settings.FeedbackLink);
		   $('copyright-hotswap-div').style.visibility = 'hidden';
	    }
    }
      if (typeof(settings.isGuideSchmapplet) != "undefined"
               && settings.isGuideSchmapplet.match(/^true$/i)) {
         if(typeof(xparams) != 'undefined'
                 &&  typeof(xparams.topLogo) != 'undefined'
                 && xparams.topLogo != '') {
           var logoPath = xparams.topLogo ;
        } else {
           var logoPath = '/images/minitemplate/guidelogos/' + schmapplet.uid + '.png';
        }
        var mainTitleLogo = PNG({width: 122, height: 22, 'src': logoPath});
        $('title-link').removeChild($('title-link').lastChild);
        $('title-link').appendChild(mainTitleLogo);
         if(typeof(settings.DisableTitleLinks) == 'undefined'
                || settings.DisableTitleLinks == 'false' || settings['TitleLink'] == 'true') {
            disconnect(mainTitleLogo, 'onclick', mainTitlGo);
            connect(mainTitleLogo, 'onclick', mainTitlGo);
        } else {
           disconnect($('title-link').lastChild,'onmouseover',hideUnderline);
           connect($('title-link').lastChild,'onmouseover',hideUnderline);
        }
        hideElement('title');
        $('title-link').style.padding = '0px';
        $('title-button-span').innerHTML = '';
        $('subtitle-button-span').innerHTML = '';

        // #3010 [BEGIN]: Moved  this code so that it is executed whenever new template is loaded
        if(settings['GameVenueLink'] == 'true'){
            disconnectAll('TitleIn', 'onmouseover');
            connect('TitleIn', 'onmouseover', showUnderline);
            connect('TitleIn', 'onmouseout', hideUnderline);
            connect('TitleIn', 'onclick', stripTitleGo)
            setStyle('TitleIn', {'cursor': 'pointer'});
			

        } 
         // #3010 [END]

        var bodyWidth = document.body.clientWidth;
          if(showMenusFromUrl == null && typeof(xparams) != 'undefined'
              && typeof(xparams.showMenus) != 'undefined'
              && xparams.showMenus.length > 0) {
                 ShowMenus = xparams.showMenus;
          }else {
                ShowMenus = showMenusFromMeta;
          }
          if(ShowMenus != null) {
             for(var i = 0;i < ShowMenus.length;i++) {
               showTwoMenus[i] = ShowMenus.charAt(i);
             } 
          }
           if(showTwoMenus[0] == 1) {
            guideHtml = '<iframe id="guide-hotswap-frame" name="guide-hotswap-frame" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" allowTransparency="true" style="border-style:none; border-width:0px;" ></iframe>';
            $('guide-hotswap-div').innerHTML = guideHtml;
            if(isIE6) {
                  setStyle('guide-hotswap-frame', {'width': bodyWidth - 6 + 'px'});
             }
             if(typeof(xparams) != 'undefined'
                     &&  typeof(xparams.topButton) != 'undefined'
                     && xparams.topButton != '') {
                 var miniGuideBtn = xparams.topButton;
              } else {
                 var miniGuideBtn = '/images/minitemplate/pageicons/MiniGuidesMenuBtn.png';
             }
             showElement('title-button-span');
            appendChildNodes('title-button-span',
                    PNG({'width':50, 'height':16,id:'title-button',
                        src:miniGuideBtn}));
             if(settings.MiniMenuOverrideName != 'undefined'
                 && settings.MiniMenuOverrideName != null
                 && settings.MiniMenuOverrideName.length > 0) {
				 var MiniMenuOverrideName = settings.MiniMenuOverrideName
				if(!schmapplet.isiGoogle && schmapplet.lang&&schmapplet.lang!==""){
					if(schmapplet.lang!=='en'){
						MiniMenuOverrideName = settings.MiniMenuOverrideName.replace('.xml.var','') + "_" + schmapplet.lang + '.xml';
					}else{
						MiniMenuOverrideName = settings.MiniMenuOverrideName.replace('.var','');
					}
			    }
				var guidePath = '/xml/' +  MiniMenuOverrideName;
                guideSrcXml = '/common/minicitiesmenu.html?' + guidePath + '&Countries';
                truncationNeeded = 0;
             } else {
                 var guidePath = '/xml/mininavmenu.xml' ;
                 truncationNeeded = 1;
             }
            loadCountriesInfo(guidePath);
            guideLoaded = 0;
            if (BrowserDetect.browser === "Firefox") {
                $('guide-hotswap-frame').style.position = 'fixed';
                if ($('optionalBottomText')) {
                    var iframeH = document.documentElement.clientHeight ;
                    var temH = iframeH - schmapplet.advertH - 24 - 23;
                    // 24 is the height of title area
                    //23 is the height of "get Get this widget..."  area
                    setElementDimensions('guide-hotswap-frame', {h:temH});
                } else {
				    var iframeH = getElementDimensions('canvas').h;
					var iframeW = getElementDimensions('canvas').w;
					var temW = iframeW -6;
                    var temH = iframeH - 24 - 23;
                    setElementDimensions('guide-hotswap-frame', {h:temH,w:temW});
				}
                // Saving and restoring the guide html later prevents the Firefox 'never stops loading' bug
                guideHtml = $('guide-hotswap-div').innerHTML;
                $('guide-hotswap-div').innerHTML ='';
            }
            analyticsConnect ('title-button-span', 'onmouseover', showGuideHotSwap, analyticsHooks.topNavOver);
            analyticsConnect ('title-button-span', 'onclick', function(){}, analyticsHooks.topNavClick);
            connect('title-button-span', 'onmouseout', hideGuideHotSwap);
            connect('guide-hotswap-div', 'onmouseout', hideGuideHotSwap);
        } else {
            hideElement('title-button-span');
            $('guide-hotswap-div').innerHTML = '';
            disconnect('title-button-span', 'onmouseover', showGuideHotSwap);
            disconnect('title-button-span', 'onmouseout', hideGuideHotSwap);
            disconnect('guide-hotswap-div', 'onmouseout', hideGuideHotSwap);
        }
        if(showTwoMenus[1] == 1) {
            sectionHtml = '<iframe id="section-hotswap-frame" name="section-hotswap-frame"  frameborder="0" marginwidth="0" marginheight="0" scrolling="no" allowTransparency="true" style="border-style:none; border-width:0px;"></iframe>';
            $('section-hotswap-div').innerHTML = sectionHtml;
            if(isIE6) {
                   setStyle('section-hotswap-frame', {'width': bodyWidth - 6 + 'px'}); 
             }
             if(typeof(xparams) != 'undefined'
                     &&  typeof(xparams.sectionButton) != 'undefined'
                     && xparams.sectionButton != '') {
                 var miniSectionBtn = xparams.sectionButton;
              } else {
                 var miniSectionBtn = '/images/minitemplate/pageicons/MiniSectionMenuBtn.png';
             }
            appendChildNodes('subtitle-button-span',
                    PNG({'width':16, 'height':12,id:'subtitle-button',
                        src:miniSectionBtn}));
            $('subtitle-button-span').style.visibility = "visible";
            if (!settings.MiniMenu2OverrideName) {
               settings.MiniMenu2OverrideName = 'nav.xml';
            }
            if(templateChanged || !initialized){
                        if (!schmapplet.isiGoogle){
			    if(schmapplet.lang&&schmapplet.lang!==""){
					if(schmapplet.lang!=='en'){
						settings.MiniMenu2OverrideName = settings.MiniMenu2OverrideName.replace('.xml','') + "_" + schmapplet.lang + '.xml';
					}
			    }
            }
/*
else{
alert(settings.MiniMenu2OverrideName);
               settings.MiniMenu2OverrideName += config.get('negotiateSuffix');
alert(settings.MiniMenu2OverrideName);
			}
*/
		   }
            var navPath = ['', schmapplet.uid,
            settings.MiniMenu2OverrideName].join('/');
            loadNavInfo(navPath);
          if (BrowserDetect.browser === "Firefox") {
                $('section-hotswap-frame').style.position = 'fixed';
                if ($('optionalBottomText')) {
                    var iframeH = document.documentElement.clientHeight ;
                    var temH = iframeH - schmapplet.advertH - 24 - 23;
                    // 24 is the height of title area
                    //23 is the height of "get Get this widget..."  area
                    setElementDimensions('section-hotswap-frame', {h:temH});
                } else {
				   	var iframeH = getElementDimensions('canvas').h;
					var iframeW = getElementDimensions('canvas').w;
					var temW = iframeW -6;
                    var temH = iframeH - 24 - 23;
                    setElementDimensions('section-hotswap-frame', {h:temH,w:temW});

				}
                // Saving and restoring the section-hotswap-div html later prevents the Firefox 'never stops loading' bug
                sectionHtml = $('section-hotswap-div').innerHTML;
                $('section-hotswap-div').innerHTML ='';
	      }
            analyticsConnect ('subtitle-button-span', 'onmouseover', showSectionHotSwap, analyticsHooks.secondNavOver);
            analyticsConnect ('subtitle-button-span', 'onclick', function(){}, analyticsHooks.secondNavClick);
            connect('subtitle-button-span', 'onmouseleave', hideSectionHotSwap);
            connect('section-hotswap-div', 'onmouseout', hideSectionHotSwap);
        } else {
            hideElement("subtitle-button-span");
            $('section-hotswap-div').innerHTML = '';
            disconnect('subtitle-button-span', 'onmouseover', showSectionHotSwap);
            disconnect('subtitle-button-span', 'onmouseleave', hideSectionHotSwap);
            disconnect('section-hotswap-div', 'onmouseout', hideSectionHotSwap);
        }
        }
    if ((typeof(settings.ShowAllPlayButtons) != "undefined"
            && settings.ShowAllPlayButtons.match(/^false$/i))) {
		$('prev-button').innerHTML = '';
		$('next-button').innerHTML = '';
        if(typeof(xparams) != 'undefined'
                &&  typeof(xparams.prevButton) != 'undefined'
                && xparams.prevButton != '') {
           var back = xparams.prevButton ;
        } else {
           var back =  settings.Back;
        }
        if(typeof(xparams) != 'undefined'
                &&  typeof(xparams.nextButton) != 'undefined'
                && xparams.nextButton != '') {
           var forward = xparams.nextButton;
        } else {
           var forward =  settings.Forward;
        }
        appendChildNodes('prev-button',PNG({src:back,width:13,height:13}));
        appendChildNodes('next-button',PNG({src:forward,width:13,height:13}));
		if(typeof(settings.PrevButtonTxt)!='undefined'
		&& settings.PrevButtonTxt.length>0){
			$('prev-button').title = settings.PrevButtonTxt;   
		} else {
			$('prev-button').title = 'prev place';
		}
		if(typeof(settings.NextButtonTxt)!='undefined'
		&& settings.NextButtonTxt.length>0){
			$('next-button').title = settings.NextButtonTxt;   
		} else {
			$('next-button').title = 'next place';
		}
         if (!initialized) {
             disconnect('prev-button', 'onclick', prevPlace);
             analyticsConnect ('prev-button', 'onclick', prevPlace, analyticsHooks.back);
             disconnect('next-button', 'onclick', nextPlace);
             analyticsConnect ('next-button', 'onclick', nextPlace, analyticsHooks.forward);
         }
        }
    schmapplet.placesById = [];
    schmapplet._placesCount = 0;
    settings.myImg = IMG({'style':'visibility:hidden;position:absolute;'});
    appendChildNodes('canvas', settings.myImg);
    var myLogo = printLogoPath + schmapplet.uid + '.gif'   ;
    settings.myImg.src = myLogo;

    settings.NormalIconSize = settings.NormalIconSize.toString().split(',');
    settings.NormalIconAnchor = settings.NormalIconAnchor.toString().split(',');
    settings.OverIconSize = settings.OverIconSize.toString().split(',');
    settings.OverIconAnchor = settings.OverIconAnchor.toString().split(',');

    schmapplet.normalAnchorX = settings.NormalIconSize[0] * settings.NormalIconAnchor[0];
    schmapplet.normalAnchorY = settings.NormalIconSize[1] * settings.NormalIconAnchor[1];

    schmapplet.overAnchorX = settings.OverIconSize[0] * settings.OverIconAnchor[0];
    schmapplet.overAnchorY = settings.OverIconSize[1] * settings.OverIconAnchor[1];

    var xml = schmapplet.placesInfo.xml;
	xmlAccess.setXmlDoc(xml);
    schmapplet.placeslist = xmlAccess.getChildren(xml, '/rdf:RDF/schmap:Place');
    var shortdesc = schmapplet.description;
    var schmappletNode = xmlAccess.getFirstChild(xml, '/rdf:RDF/schmap:Schmapplet');
    var schmapplet_s = xmlAccess.getAttributeNS(schmappletNode,
            "rdf", 'about') || "";
    // var schmapplet_s = match(null, null, NS.rdf+'type', NS.schmap+'Schmapplet')[0].subject;
    //var guide = match(null, null, NS.rdf+'type', NS.schmap+'Guide')[0].subject;
    Map_object.schmapplet_path = schmapplet_s;
    Map_object.schmapplet_s = xmlAccess.getSingleChildText(
            schmappletNode, 'georss:box');
	Map_object.origGeoBox = Map_object.schmapplet_s;
    var created = xmlAccess.getSingleChildText(schmappletNode, 'dc:created');
    var title = xmlAccess.getSingleChildText(schmappletNode, 'dc:title');
    schmapplet.title = title;
    subTitleFromPlaces = xmlAccess.getSingleChildText(schmappletNode, 'dc:subtitle');
     if(initialized && typeof(schmapplet.applyColors) != 'undefined'
            && schmapplet.applyColors.match(/yes/i)) {
            
        if ((typeof(schmapplet.usingSTemplate) != 'undefined')
             && schmapplet.usingSTemplate == 1
             && typeof(xparams) != 'undefined'
             && typeof(xparams.colorString) != 'undefined'){
            colorset = xparams.colorString;
        } else {
            colorset = xmlAccess.getSingleChildText(schmappletNode, 'schmap:colors');
        }
       changingColor(colorset);
    }
    if(colorset.length < 1 || colorset.toLowerCase() == 'none'){
        var hashp = getHashParams();
        schmapplet.colorset = null;
        colorset = hashp.c || "";
        if (colorset.length < 0 || colorset.toLowerCase() == 'none') {
	    colorset = 'f6f6f6A72122A62122A62122FFF88FFAF5BBffffffFFF88Fd8d8d8A4A7A6A621226990ffECEBBD0000005C5A4E5C5A4E000000929292F0EFDA';
        }
        changingColor(colorset);
        
   }
   // add block of this code because we have no color data in place.xml
    var guideUrlNode = xmlAccess.getFirstChild(schmappletNode, 'schmap:guide');
    guide_url = xmlAccess.getAttributeNS(guideUrlNode, 'rdf', 'resource');
    var guideNode = xmlAccess.getFirstChild(xml, '/rdf:RDF/schmap:Guide');
    var loc = xmlAccess.getSingleChildText(guideNode, 'dc:title');
    citycode = xmlAccess.getSingleChildText(guideNode, 'dc:cityid');
    citycode = citycode.split('C');
    citycode = citycode[1];
    curCityName = loc;
    setSubtitle();

    if ((typeof(schmapplet.usingSTemplate) != 'undefined')
         && schmapplet.usingSTemplate == 1
         && typeof(xparams) != 'undefined'
            && typeof(xparams.bestFit) != 'undefined') {
        var geos = xparams.bestFit.split(',');
        var latN = geos[0];
        var longW = geos[1];
        var latS = geos[2];
        var longE = geos[3];
        Map_object.schmapplet_s = concat([latS," ",longW," ",latN," ",longE]);
		Map_object.origGeoBox =  Map_object.schmapplet_s;
    }
    else if (typeof(topleft) != "undefined"
            && topleft != "undefined"
            && typeof(bottomright) != "undefined"
            && bottomright != "undefined") {
        var tl = topleft.split(',');
        var br = bottomright.split(',');
        Map_object.schmapplet_s = concat([tl[0]," ",tl[1]," ",br[0]," ",br[1]]);
    } else if (typeof(schmapplet.topleft) != "undefined"
            && schmapplet.topleft != 'undefined'
            && schmapplet.topleft != null
            && typeof(schmapplet.bottomright) != "undefined"
            && schmapplet.bottomright != 'undefined'
            && schmapplet.bottomright != null) {
        var tl = schmapplet.topleft.split(',');
        var br = schmapplet.bottomright.split(',');
        Map_object.schmapplet_s = concat([tl[0]," ",tl[1]," ",br[0]," ",br[1]]);
    }

    subtitle = subtitle.replace(/^\s+|\s+$/g, "");
    logDebug("subtitle", subtitle);
    noPhotosAtAll = true;
    createPage();
}

function clickTitle() {
        var normalURL = Map_object.schmapplet_path.replace('www.schmap.com',document.location.host).replace('/latest','');
         window.open(normalURL);
}

function clickLogo() {
    
    try {

        if (typeof(settings.FooterType) != 'undefined'
                && settings.FooterType.match(/panel/i))
		return;

        if (typeof(settings.FooterLink) != 'undefined') {
            window.open(settings.FooterLink,
                    "LogoLink",
                    "width=950, height=650, scrollbars=no, resizable=no");
        } else {
            showCustomizePage();
        }
    } catch (err) {
        logDebug(err);
    }
}

function mouseIntoTextPanelFromBottom(evt, obj) {
  var mx = evt.mouse().client.x;
  var my = evt.mouse().client.y;
  var pos = getElementPosition(obj);
  var dim = getElementDimensions(obj);
  //logDebug("small y:", pos.y, "my:", my, "big y:", pos.y + dim.h, "small x:", pos.x, "mx:", mx, "big x:", pos.x + dim.w);
  //logDebug("evt type:" + evt.type + ",obj.id:" + obj.id + ",small y:"+ pos.y+ ",my:"+ my+ ",big y:"+ pos.y + dim.h+ ",small x:"+ pos.x + ",mx:"+ mx+ ",big x:"+ pos.x + dim.w);
  //if(34 < mx && 152 > mx && 18 < my) {
  if(schmapplet.IEquirks) {
      pos.y += 2;
      pos.x += 2;
  }
    if(isSafari) {
      my += 14;
  }

  if(mx == 0 || my == 0) return true;
  if(pos.x < mx && (pos.x + dim.w) > mx && pos.y < my && (pos.y + dim.h) > my) {
      ////logDebug("mouse in " + id);
      return true;
  }

  return false;
}

function createTopPhotoTable() {
    if(isCreatePhoto) return;
    var photos = $('photos');

	var mytable = document.createElement("table");
    //mytable.setAttribute("style", "margin: 0 auto;text-align:center;height:100%;");
    mytable.setAttribute("id", "photo-table");
    var mytablebody = document.createElement("tbody");

	var mycurrent_row = document.createElement("tr");
	mycurrent_cellTD = document.createElement("td");
	schmapplet.mycurrent_cellTD =mycurrent_cellTD;
  	var photo_p = document.createElement("p");
	photo_p.valign = "center";
    photo_p.setAttribute("id", "photo-p");

    mycurrent_cellTD.appendChild(photo_p);	

	mycurrent_row.appendChild(mycurrent_cellTD);
    mytablebody.appendChild(mycurrent_row);

	mycurrent_row = document.createElement("tr");
	mycurrent_cell = document.createElement("td");

	var author_p = document.createElement("p");
    author_p.setAttribute("align", "left");
    author_p.setAttribute("id", "photo-attr");
	author_p.valign = "middle";

    photo_cc = PNG({width: 12, height: 12,'class':'cc', 'src': settings.CC});
    photo_cc.align = "absmiddle";
    photo_cc.setAttribute("id", "photo-cc");

//	author_p.appendChild(photo_cc);

    mycurrent_cellTD.appendChild(author_p);

	mycurrent_row = document.createElement("tr");
	mycurrent_cell = document.createElement("td");
	var button_p = document.createElement("div");
    button_p.setAttribute("id", "photo-button");
    if(typeof(xparams) != 'undefined' 
	    &&  typeof(xparams.back) != 'undefined' ) {
       var back = xparams.back;
    } else {
       var back =  settings.Back;
    }
	if(typeof(xparams) != 'undefined' 
	   &&  typeof(xparams.nextButtonOver) != 'undefined') {
       var nextOver = xparams.nextButtonOver;
    } else {
       var nextOver =  '/images/iconsDir/prev-over.png';
    }
    if(typeof(xparams) != 'undefined' 
	   &&  typeof(xparams.forward) != 'undefined') {
       var forward = xparams.forward;
    } else {
       var forward =  settings.Forward;
    }
	if(typeof(xparams) != 'undefined' 
	   &&  typeof(xparams.prevButtonOver) != 'undefined') {
       var forwardOver = xparams.prevButtonOver;
    } else {
       var forwardOver =  '/images/iconsDir/next-over.png';
    }
    var back_button = PNG({id:'prev-photo', width: 13, height: 13, 'src': back});
    var overBack = PNG({id:'overPrev', width: 13, height: 13, 'src': nextOver});
	back_button.imgMouseover = overBack ;
	overBack.imgMouseout = back_button;
	hideElement(overBack);
	back_button.align = "absmiddle";
	overBack.align = "absmiddle";
    overBack.onclick = previousPhoto;
    overBack.setAttribute("title", "previous photo");
	button_p.appendChild(back_button);
	button_p.appendChild(overBack);
	connect(back_button,'onmouseover',changePhoto);
	connect(overBack,'onmouseout',changePhotoBack);
    button_p.appendChild(SPAN({'style':'width:2px'},' '));
    var prev_button = PNG({width: 13, height: 13, 'src': forward});
	var overNext = PNG({width: 13, height: 13, 'src': forwardOver});
	prev_button.imgMouseover = overNext ;
	overNext.imgMouseout = prev_button;
	hideElement(overNext );
    prev_button.align = "absmiddle";
	overNext.align = "absmiddle";
    overNext.onclick = nextPhoto;
	overNext.setAttribute("title", "next photo");
	button_p.appendChild(prev_button);
	button_p.appendChild(overNext);
    connect(prev_button,'onmouseover',changePhoto);
	connect(overNext,'onmouseout',changePhotoBack);
	button_p.valign = "middle";
    mycurrent_cellTD.appendChild(button_p);
    mytable.appendChild(mytablebody);
    photos.appendChild(mytable);
	if(schmapplet.placetweet)
	addElementClass("photo-p", "twieet-photo-p");
	var h=((document.body.clientHeight-160)-16-140)/2-11-9;
	if(h <= 0){
		h=2;
	}
  	//setStyle(button_p, {'bottom': h+'px'});
	//button_p.setAttribute("style", "bottom:"+h+"px");
   isCreatePhoto = true;
}

function adjustPhotoTab(){
	try{
        var spanWidth = $('view-panel').clientWidth +'px';
        if($('zoom-p')) {
		    if(settings['UseFunctionIcons'] =='false')
            setStyle('zoom-p',{width:spanWidth});
        }

		if(schmapplet.IEquirks
                || BrowserDetect.browser == 'Safari'){
			if(schmapplet.mycurrent_cellTD){
			    setStyle(schmapplet.mycurrent_cellTD,
		                {'height': ((document.body.clientHeight-160)-16)+'px'});
						
			setStyle('photo-button',
                {'width': (document.body.clientWidth- 22) + 'px'});}
	   }
			map(function(ele){
				setStyle(ele,{'margin-left':document.body.clientWidth/2 - 5+'px'});
				 },['upArrowStats','disupStats','downStats','disdownStats']); 
		if( schmapplet.sportsSchedule)
			map(function(ele){
				setStyle(ele,{'margin-left':document.body.clientWidth/2 - 5+'px'});
				 },['upArrow','disup','down','disdown']);
    }catch(err){
        errLog(err);
    }
}
function showTopPhoto() {
try{
	    $('loading-message-guide').style.visibility = 'visible';
		$('photo-table').style.visibility = 'hidden';
    var photos = $('photos');
    var photo_src = schmapplet.places[schmapplet.selected].photo_IMG[schmapplet.selectedPhoto];
    if(typeof(photo_src) == 'undefined') {
      return;  
    }

	settings['photo']= photo_src ;

    settings.photo.lnk = schmapplet.places[schmapplet.selected].photo_objs[schmapplet.selectedPhoto].link;
	if(settings.photo.lnk != ''){
	    settings.photo.onclick = function()
	    {
	        window.open(this.lnk);
	    }
	}

	if ($('photo-p').childNodes.length > 0)
    	$('photo-p').removeChild($('photo-p').firstChild);
     if(isphotoComplete(settings.photo)){
        $('photo-p').appendChild(settings.photo);
     }

//    showPhotoWhenDownloadComplete();
	     checkPhotoFinished();
    if (schmapplet.places[schmapplet.selected].photo_objs[schmapplet.selectedPhoto].username) {

      	var author = "Photo: " + schmapplet.places[schmapplet.selected].photo_objs[schmapplet.selectedPhoto].username;
		author=truncated(author,photos.offsetWidth/8);
		//authors=truncatWidth(author,photos.offsetWidth/7);

    	if (schmapplet.places[schmapplet.selected].photo_objs[schmapplet.selectedPhoto].licensecode
    	    && schmapplet.places[schmapplet.selected].photo_objs[schmapplet.selectedPhoto].licensecode >= 1
    	    && schmapplet.places[schmapplet.selected].photo_objs[schmapplet.selectedPhoto].licensecode <= 6) {

      		photo_cc.lnk = schmapplet.places[schmapplet.selected].photo_objs[schmapplet.selectedPhoto].licenseurl;
            photo_cc.onclick = function()
            {
                window.open(this.lnk);
            }

        	$('photo-attr').innerHTML = author + "&nbsp;";
      		$('photo-attr').appendChild(photo_cc);
    	} else {
	    	if ($('photo-attr').childNodes.length > 0)
	    		$('photo-attr').removeChild($('photo-attr').firstChild);
        	$('photo-attr').innerHTML = author + "&nbsp;";
    	}
	} else {
    	$('photo-attr').innerHTML = '';
	}

} catch (err) {
	logDebug(err);
}
}

function previousPhoto() {
    try {

    if(schmapplet.selectedPhoto <= 0) {

        schmapplet.selected -= 1;
        if(schmapplet.selected < 0)
            schmapplet.selected = schmapplet.places.length - 1;

        var initValue = schmapplet.selected;
        while (schmapplet.places[schmapplet.selected].photo_objs.length <= 0) {
            schmapplet.selected -= 1;
            if(schmapplet.selected < 0)
                schmapplet.selected = schmapplet.places.length - 1;
            if (initValue == schmapplet.selected) break;
		}
        schmapplet.places[schmapplet.selected].highlight(true);
        setCurrentCounter (schmapplet.selected + 1);
        schmapplet.selectedPhoto = schmapplet.places[schmapplet.selected].photo_objs.length - 1;
    } else {
	    schmapplet.selectedPhoto -= 1;
    }

	showTopPhoto();

    } catch (err) {
        logException(err, "4.");
    }
}
function previousStats() {
    try {


        schmapplet.selected -= 1;
        if(schmapplet.selected < 0)
            schmapplet.selected = schmapplet.places.length - 1;

        var initValue = schmapplet.selected;
        while (schmapplet.places[schmapplet.selected].ldesc == '') {
            schmapplet.selected -= 1;
            if(schmapplet.selected < 0)
                schmapplet.selected = schmapplet.places.length - 1;
            if (initValue == schmapplet.selected) break;
		}
        schmapplet.places[schmapplet.selected].highlight(true);
        setCurrentCounter (schmapplet.selected + 1);

    } catch (err) {
        logException(err, "previousStats");
    }
}
function showReviewLink() {
	if (typeof(settings.T000LinkInPlaceStrip)!='undefined'
            && settings.T000LinkInPlaceStrip.length > 0) {
        var links1 = $('reviewlink-url');
	    var url_ = new StringBuffer();
	    url_.append(schmapplet.url_prefix).append(schmapplet.uid).append("/");
        url_.append(schmapplet.sid).append("/#mapview=") ;
	    if (typeof(schmapplet.mapview) != "undefined"
                && schmapplet.mapview.length > 0)
	    	url_.append(schmapplet.mapview) ;
	    else
	    	url_.append("Map");

    	url_.append("&tab=Places&p=") ;

		var placeid = schmapplet.places[schmapplet.selected].id;
    	url_.append(placeid) ;

        var s = Map_object.schmapplet_s.split(" ");
    	url_.append("&topleft=") ;
    	url_.append(s[0]).append(",").append(s[1]);
    	url_.append("&bottomright=").append(s[2]).append(",").append(s[3]);

        if (schmapplet.places[schmapplet.selected].wcities_only
                && schmapplet.places[schmapplet.selected].wcities_photos.length > 0) {
        	url_.append("&i=");
            url_.append(schmapplet.places[schmapplet.selected].wcities_photos[0].path);
        } else if (schmapplet.places[schmapplet.selected].photo_objs.length) {
        	url_.append("&i=");
            url_.append(schmapplet.places[schmapplet.selected].photo_objs[schmapplet.selectedPhoto].path);
	    }

        var content = new StringBuffer();
	    content.append("<a id='reviewlink-url-bak' href='").append(url_.toString()) ;
	    content.append("' target='_blank'><i>").append(settings.T000LinkInPlaceStrip.toString());
	    content.append("</i></a>");

        $('reviewlink-a').innerHTML = content.toString();
        showElement('reviewlink-a');
        $('place-thumb').href = url_.toString();

	} else {
        hideElement('reviewlink-a');
	}
}


PlaceObj.prototype.highlight = function(noShowPhoto, noAutoPan) {
    try {
if(schmapplet.placetweet) showElement('expand'); 
        if ((typeof(settings.TitleInPlaceStrip) != 'undefined')
                && settings.TitleInPlaceStrip.match(/no/i)) {
            hideElement('TitleIn');
        } else {
            var spanWidth = $('place-info').clientWidth;
            if((schmapplet.usingSTemplate)&& this.zoomedIn) {
                $('TitleIn').initTxt = this.addr2;
                var myTxt = getTrunction('TitleIn',spanWidth,9);
                $('TitleIn').innerHTML = myTxt;
            } else {
                var content = new StringBuffer();
               $('TitleIn').initTxt = this.name;
			   if(settings['templateLayout']=='geotweet'){
			   $('TitleIn').initTxt = this.placedatetime;
			   }
               var myTxt = getTrunction('TitleIn',spanWidth,9);
                if(settings['StripTitleLink'] =='true' && this.url !==""){
			        content.append('<a href="').append(this.url).append('" target="blank">').append(myTxt).append('</a>');
				}else{
				   content.append(myTxt);
					}
                $('TitleIn').innerHTML = content.toString();
            }
            showElement('TitleIn');
        }
        if((typeof(settings.urlInPlaceStrip)!='undefined')
            && !(settings.urlInPlaceStrip.match(/no/i))
            && this.stickyPlaceType !== 2) {
            var links1 = $('place-url');
            if (this.url.length)
                links1.href=this.url;
            links1.innerHTML = this.urlText.toString();
            showElement('UrlIn');
        } else {
            hideElement('UrlIn');
        }
        if (this.has_photos) {
            showElement('photo-p');
            showElement('photo-attr');
            showElement('photo-button');
            if(((typeof(settings.ThumbInPlaceStrip) != 'undefined')
                    && settings.ThumbInPlaceStrip.match(/no/i))
                    || !this.photo_thumb.loaded) {
                hideElement('place-thumb');
            } else {
                    replaceChildNodes('place-thumb', this.photo_thumb);
                    showElement('place-thumb');
					
                    if(typeof(this.photo_thumb_left)!='undefined'){
                        replaceChildNodes('place-thumb-left', this.photo_thumb_left);
                        showElement('place-thumb-left');
                        }else{
                        hideElement('place-thumb-left');
                            }
                if(schmapplet.IEquirks) {
                    setStyle('TitleIn',{'margin-top':'0px'});
                    }

                }

            schmapplet.selectedPhoto = 0;
            if (noShowPhoto == null && isPhotoView) {
                showTopPhoto();
            }
        } else {
                hideElement('photo-p');
                hideElement('photo-attr');
                hideElement('photo-button');
                hideElement('place-thumb');
				hideElement('place-thumb-left');
         }

        if (schmapplet.usingSTemplate == 1)
        {
            if(settings['TopMargin']){
                var topBottom = settings['TopMargin'].split(',');
                var top = Number(topBottom[0]);
                var bottom = topBottom[1] + 'px'; 
				if(schmapplet.IEquirks){
					setStyle('TitleIn',{'margin-top':(top+5)+'px'});
				}else {
					setStyle('TitleIn',{'margin-top':topBottom[0] + 'px'});
				}
				setStyle('TitleIn',{'margin-bottom':bottom});
            }
           
        }
        
        if (settings['TopMarginShortDesc'])
        {
            var sdTopBottom = settings['TopMarginShortDesc'].split(',');
            var sdTop = sdTopBottom[0] + 'px';
            var sdBottom = sdTopBottom[1] + 'px';
            setStyle('ShortDescIn',{'margin-top': sdTop});
            setStyle('ShortDescIn',{'margin-bottom': sdBottom});
        }

        if (((typeof(settings.AddrLine1InPlaceStrip) != 'undefined')
                && settings.AddrLine1InPlaceStrip.match(/no/i))
                || (this.stickyPlaceType === 2)) {
            hideElement('AddrLine1In');
        } else {
            var spanWidth = $('place-info').clientWidth;
            $('AddrLine1In').initTxt = this.street ;
			if($('place-thumb-left').style.display != 'none')
                var thrumbLeftW = getElementDimensions('place-thumb-left').w;
			else 
				var thrumbLeftW = 0;
            if($('place-thumb').style.display != 'none')
                var thrumbW = getElementDimensions('place-thumb').w;
			else 
				var thrumbW = 0;
            var temW = spanWidth - thrumbLeftW - thrumbW - 5;
			if(isIE6){
			   addElementClass('AddrLine1In','n-placeInfo');
			   var temLen = 11;
	        } else 
	           var temLen = 9;
            var myTxt = getTrunction('AddrLine1In', temW,temLen);
            $('AddrLine1In').innerHTML = myTxt;
            showElement('AddrLine1In');
        }

        if (((typeof(settings.PhoneNoInPlaceStrip) != 'undefined')
                && settings.PhoneNoInPlaceStrip.match(/no/i))
                || (this.stickyPlaceType === 2)) {
            hideElement('PhoneNoIn');
        } else {
            var spanWidth = $('place-info').clientWidth;
             $('PhoneNoIn').initTxt = this.telnumber; ;
            if($('place-thumb-left').style.display != 'none')
                var thrumbLeftW = getElementDimensions('place-thumb-left').w;
			else 
				var thrumbLeftW = 0;
            if($('place-thumb').style.display != 'none')
                var thrumbW = getElementDimensions('place-thumb').w;
			else 
				var thrumbW = 0;
            var temW = spanWidth - thrumbLeftW - thrumbW - 5;
            var myTxt = getTrunction('PhoneNoIn', temW,9);
            $('PhoneNoIn').innerHTML = myTxt;
            showElement('PhoneNoIn');
        }

        var h = $('place-name-top');
        h.innerHTML = this.name;
        if (!autoPlaying) {
            updateParentIframeCode();
        }
        if ((typeof(settings.ShortDescInPlaceStrip) != 'undefined')
                && settings.ShortDescInPlaceStrip.match(/no/i)
                && this.stickyPlaceType !== 2) {
            hideElement('ShortDescIn');
        } else {
            var spanWidth = $('place-info').clientWidth;
             if($('place-thumb-left').style.display != 'none')
                var thrumbLeftW = getElementDimensions('place-thumb-left').w;
			else 
				var thrumbLeftW = 0;
            if($('place-thumb').style.display != 'none')
                var thrumbW = getElementDimensions('place-thumb').w;
			else 
				var thrumbW = 0;
            var temW = spanWidth - thrumbLeftW - thrumbW -5 ;
             $('ShortDescIn').initTxt = this.sdesc;
             var myTxt = getTrunctions('ShortDescIn',temW,6);
			 logDebug('mytext ',myTxt);
             $('ShortDescIn').innerHTML = myTxt;
             showElement('ShortDescIn');
        }
    if(this.stickyPlaceType === 2){
	   showElement('ShortDescIn');
	}
        

    if((typeof(settings.ShortDescInPlaceStrip)!='undefined')
            && settings.ShortDescInPlaceStrip.match(/no/i) 
            && this.stickyPlaceType !== 2) {
        showReviewLink();
    }
    else {
        hideElement('reviewlink-a');
    }
	if(schmapplet.hasHtml1Tab){
       $('statsContent').innerHTML=this.ldesc;
	   if(isStatsView){
		jugdescroll($('stats'));
	   }
	}
	if (this.stickyPlaceType != 2 && schmapplet.hasDetailTab) {
    
	    //replaceChildNodes('detail-street', this.addr1);
	    var addr = this.addr1 + ', ' + this.city;
	    if (addr == (this.addr1 + ', '))
	        $('detail-street').innerHTML = this.addr1;
	    else
	        $('detail-street').innerHTML = this.addr1 + ', ' + this.city;
	
	    if(this.addr2.length) {
	      //  replaceChildNodes('detail-ext', this.addr2);
				  $('detail-ext').innerHTML=this.addr2;
	
	        showElement('detail-ext');
	    } else
	        hideElement('detail-ext');
	    if(this.zip.length) {
	       // replaceChildNodes('detail-pcode', this.zip);
			$('detail-pcode').innerHTML=this.zip;
	        showElement('detail-pcode');
	    } else
	        hideElement('detail-pcode');
	    if(this.tel.length) {
	       //replaceChildNodes('detail-tel', this.tel);
			$('detail-tel').innerHTML=this.tel;
	        showElement('detail-tel');
	    } else
	        hideElement('detail-tel');
	    if(this.url.length) {
	        var links = $('html-url');
			links.href=this.url;
	        links.innerHTML = this.urlText;
	        if (this.extra_url == false) {
	            var desc = $('detail-desc');
	            if (desc.clientWidth > 16) {
	                setTextTrimmed('html-url', this.urlText, desc.clientWidth - 16);
	            }
	        }
	        showElement('detail-url');
	    } else
	        hideElement('detail-url');
	
	    if(this.ldesc.length) {
	       // replaceChildNodes('detail-desc', this.ldesc);
			$('detail-desc').innerHTML=this.ldesc;
	
	        showElement('detail-desc');
	    } else
	        hideElement('detail-desc');
    } else {
        hideElement('detail-street');
        hideElement('detail-ext');
        hideElement('detail-pcode');
        hideElement('detail-tel');
        hideElement('detail-url');
        hideElement('detail-desc');        
    }   
        
    if(schmapplet.view != 'map') return;
	logDebug(schmapplet.view);
	   this.maphighlight(noAutoPan);
    } catch (err) {
		  logException(err, "3.");
    }
};

PlaceObj.prototype.maphighlight = function(noAutoPan) {
	if(schmapplet.noAutoPan){
	noAutoPan = schmapplet.noAutoPan;
	}
    if(schmapplet.map.provider == 's'  &&
       (noAutoPan == null)){
        if(schmapplet.actualOrigBounds.contains(this.geocode)) 
        {
            if (!showingOrigMap) 
            {
                schmapplet.map.setDisplay(schmapplet.origbounds.getCenter());
                showingOrigMap = true;
            }
        }
        else 
        {
            try 
            {
                schmapplet.map.setDisplay(this.geocode);
                showingOrigMap = false;
            } 
            catch (e) 
            { if(e instanceof MochiKit.Maps.OutOfBounds)
                logDebug('Point out of bounds, not displaying');
                return;
            }
        }
    }
    if(!(schmapplet.marker && this.marker)) return;
    this.markerbig.show();
    this.marker.hide();
    if(!(schmapplet.marker && this.Gmarker)) return;
    this.Gmarkerbig.show();
    this.Gmarker.hide();
};

PlaceObj.prototype.unhighlight = function() {
   // if(schmapplet.view != 'map') return;
    if(!(schmapplet.marker && this.marker)) return;

    this.markerbig.hide();
    this.marker.show();
	if(!(schmapplet.marker && this.Gmarker)) return;

    this.Gmarkerbig.hide();
    this.Gmarker.show();
};

function prevPlace() {
    stopCycling();
    if (autoPlaying) {
        autoPlayPaused = true;
    }
   if(isStatsView){
	    previousStats();
	}else{
        var place = schmapplet.places[schmapplet.selected];
        var zoomedIn = place.zoomedIn;
        if(typeof(schmapplet.selected) != 'undefined') {
            if(zoomedIn) {
                if(settings.ZoomOutOnChange == 'no') {
                    place.zoomedIn = false;
					if(schmapplet.places[schmapplet.selected].gmarkerbig)
		                schmapplet.places[schmapplet.selected].gmarkerbig.hide();

                } else {
                    zoomInOut();
                    zoomedIn = false;
                }
            }
        } else {
            schmapplet.selected = 0;
        }
        place.unhighlight();
        schmapplet.selected -= 1;
        if(schmapplet.selected < 0)
            schmapplet.selected += schmapplet.places.length;
        place = schmapplet.places[schmapplet.selected];
       if(isPhotoView) {
           while(place.photo_objs.length < 1) {
               schmapplet.selected -= 1;
               if(schmapplet.selected < 0)
                   schmapplet.selected += schmapplet.places.length;
               place = schmapplet.places[schmapplet.selected];
           }
       }
        place.zoomedIn = zoomedIn;
        place.highlight();
        setCurrentCounter (schmapplet.selected + 1);
        if(zoomedIn) {
			setDisplay(place.geocode,place.gpoint,zoomLevel);
			if(schmapplet.needGoogle)
			    createGMarker(schmapplet.map2,schmapplet.places[schmapplet.selected]);
		}

        if (!autoPlaying) {
            schmapplet.placeid = place.id;
        }
    }	    
	if(schmapplet.view == 'schedule' && typeof(schmapplet.gameDayArray)!='undefined'){
			if(schmapplet.selected==(schmapplet.places.length-1)){
			var lastone = 0;
			}else{
			var lastone = schmapplet.selected+1;
			}
			changeBGback.apply(schmapplet.gameDayArray[lastone]); 
			changeBG.apply(schmapplet.gameDayArray[schmapplet.selected]); 
	}
}

function nextPhoto() {
    try {
    if(typeof(schmapplet.selected) == "undefined") schmapplet.selected = 0;
	schmapplet.places[schmapplet.selected].unhighlight();
    if( (schmapplet.selectedPhoto + 1) >= schmapplet.places[schmapplet.selected].photo_objs.length) {

        schmapplet.selected += 1;
        if(schmapplet.selected == schmapplet.places.length)
            schmapplet.selected = 0;

        var initValue = schmapplet.selected;
            while (schmapplet.places[schmapplet.selected].photo_objs.length <= 0) {
            schmapplet.selected += 1;
            if(schmapplet.selected == schmapplet.places.length)
                schmapplet.selected = 0;

            if (initValue == schmapplet.selected) break;
		}
		schmapplet.selectedPhoto = 0;
		schmapplet.places[schmapplet.selected].highlight();
		setCurrentCounter (schmapplet.selected + 1);

    } else {
        schmapplet.selectedPhoto += 1;
		showTopPhoto();
   	}

    } catch (err) {
        logException(err, "44.");
    }
}

function nextStats() {
    try {
        schmapplet.places[schmapplet.selected].unhighlight();
        schmapplet.selected += 1;
        if(schmapplet.selected == schmapplet.places.length)
            schmapplet.selected = 0;

        var initValue = schmapplet.selected;
            while (schmapplet.places[schmapplet.selected].ldesc == '') {
            schmapplet.selected += 1;
            if(schmapplet.selected == schmapplet.places.length)
                schmapplet.selected = 0;

            if (initValue == schmapplet.selected) break;
		}
		schmapplet.places[schmapplet.selected].highlight();
		setCurrentCounter (schmapplet.selected + 1);
    } catch (err) {
        logException(err, "nextStats");
    }
}


function nextPlace(evt) {
    try {
    stopCycling();
    if (autoPlaying) {
        autoPlayPaused = true;
    }
    if(isStatsView){
	  nextStats();
	 }else {
       if(typeof(schmapplet.selected) == 'undefined') {
           schmapplet.selected = 0;
       }
        var place = schmapplet.places[schmapplet.selected];
        var zoomedIn = schmapplet.zoomedIn;
        if(zoomedIn) {
            if(settings.ZoomOutOnChange == 'no') {
                place.zoomedIn = false;
				if(schmapplet.places[schmapplet.selected].gmarkerbig)
		           schmapplet.places[schmapplet.selected].gmarkerbig.hide();
            } else {
                zoomInOut();
                zoomedIn = false;
            }
         }
        place.unhighlight();
        schmapplet.selected += 1;
        if(schmapplet.selected == schmapplet.places.length)
            schmapplet.selected = 0;
        place = schmapplet.places[schmapplet.selected];
        if(isPhotoView) {
            while(place.photo_objs.length < 1) {
              schmapplet.selected += 1;
              if(schmapplet.selected == schmapplet.places.length)
                 schmapplet.selected = 0;
              place = schmapplet.places[schmapplet.selected];
           }
       }
        place.zoomedIn = zoomedIn;
        place.highlight();
        setCurrentCounter (schmapplet.selected + 1);
        if(zoomedIn) {
            setDisplay(place.geocode,place.gpoint,zoomLevel);
			if(schmapplet.needGoogle)
			    createGMarker(schmapplet.map2,schmapplet.places[schmapplet.selected]);
        }

        //if (!autoPlaying && evt) {
            schmapplet.placeid = schmapplet.places[schmapplet.selected].id;
      //  }
    }
	    if(schmapplet.view == 'schedule'
                && typeof(schmapplet.gameDayArray)!='undefined'){
			if(schmapplet.selected==0){
				lastone = schmapplet.places.length;
			}else{
				lastone = schmapplet.selected - 1
			}
			changeBGback.apply(schmapplet.gameDayArray[lastone]);
			changeBG.apply(schmapplet.gameDayArray[schmapplet.selected]);
	    }
    } catch (err) {
        logException(err, "444.");
    }
}

function setDisplay(geo,gpoint,zoom){
	var point =  geo;
	var zoom = Math.abs(zoom);
	if(schmapplet.needGoogle){
		var map = schmapplet.map2;
		if(gpoint === undefined) {
	    		point = new MochiKit.Maps__Google.Point(point.latitude,
									point.longitude);
		} else {
		point =  gpoint;
		}   
	}else{
		map = schmapplet.map;
		}
	
	map.setDisplay(point, zoom);
}
function startPlay() {
    try {
		schmapplet.pauseClick = false;
    if (autoPlaying) {
        if (autoPlayPaused || autoPlayStopped) {
		   // nextPlace();
	        autoPlayPaused = false;
			if (!flash_d) {
			    num = 0;
				flashPlayButton();
			}
        }
  	} else {
		autoPlaying = true;
	    //nextPlace();
		autoPlayPaused = false;
		if (!flash_d) {
    	    num = 0;
			flashPlayButton();
		}
	}
    autoPlayStopped = false;
	} catch (err) {
		logException(err, "5.");
	}
}

function stopPlay() {
	pausePlay();
    schmapplet.places[schmapplet.selected].unhighlight();
    schmapplet.selected = 0;
    schmapplet.places[schmapplet.selected].highlight();
    setCurrentCounter (schmapplet.selected + 1);
    autoPlayStopped = true;
    autoPlaying = false;
}

function pausePlay() {
    stopCycling();
    if (autoPlaying) {
		autoPlayPaused = true;
	}
}

function stopCycling() {
	stopFlashPlayButton();
   // if(cycling_d) {
//        cycling_d.cancel();
//        cycling_d = null;
//    }
}

function cyclePlace() {
    try {
    if (isPhotoView) {
        nextPhoto();
    }else if(isStatsView){
	    nextStats();
	}else {
        if((settings.ZoomOutOnChange != 'no') ||
           !schmapplet.places[schmapplet.selected].zoomedIn) {
            nextPlace();
            }
        }
    if (autoPlaying)
        autoPlayPaused = false;
//	if (!flash_d)
//		flashPlayButton();

    //cycling_d = callLater(schmapplet.cycleTime, cyclePlace);
	} catch (err) {
		logException(err, "6.");
	}
}

function isMouseInsideSection(evt) {
	var mx = evt.mouse().client.x;
    var my = evt.mouse().client.y;
    if(isSafari20){
	if(mx == 0&&my < 650) return false;
	return true;
	}
//  var pos_lower = getElementPosition('title-button');
//  var dim_lower = getElementDimensions('title-button');
//  logDebug("upper:", pos_upper.x, pos_upper.y, dim_upper.w, dim_upper.h);
  //dim_upper.h = pos_upper.y + dim_upper.h - getElementPosition('map').y;
 // pos_upper.y = getElementPosition('map').y;
  var pos=getElementPosition('guide-hotswap-div');
  var dim=getElementDimensions('guide-hotswap-div');
  if(schmapplet.IEquirks) {
      mx+= 1;
      my+= 1;
  }
  if(!guide_hotswap_showed && !section_hotswap_showed) {
      return false;
  }

  //  if(isSafari20){
	//  my += 1;
//	  mx += 2;
//	  }
	  if(my < (pos.y + dim.h) && my > pos.y && mx < (pos.x + dim.w) && mx > pos.x){
		  return true;
		 }
		  return false;
}
function isMouseOutsideSchmappletText(evt) {
  var mx = evt.mouse().client.x;
  var my = evt.mouse().client.y;
  var pos_lower = getElementPosition('whatsthis');
  var dim_lower = getElementDimensions('whatsthis');
//  var pos_upper = getElementPosition('place-info');
//  var dim_upper = getElementDimensions('place-info');
//  logDebug("upper:", pos_upper.x, pos_upper.y, dim_upper.w, dim_upper.h);
  //dim_upper.h = pos_upper.y + dim_upper.h - getElementPosition('map').y;
 // pos_upper.y = getElementPosition('map').y;
  var pos=getElementPosition('GetSchmappletText');
  var dim=getElementDimensions('GetSchmappletText');
  if(schmapplet.IEquirks) {
      mx+= 1;
      my+= 1;
  }

  if (showed) {
    if( mx <= pos_lower.x || mx >= (pos_lower.x + dim_lower.w) || my >= (pos_lower.y + dim_lower.h) ) {
        //logDebug("not showed:", mx, my, pos_lower.x, pos_lower.y, pos_lower.x + dim_lower.w, pos_lower.y + dim_lower.h);
        return true;
    }
  } else {
    if( mx <= pos_lower.x || mx >= (pos_lower.x + dim_lower.w) ||  my <= pos_lower.y || my >= (pos_lower.y + dim_lower.h) ) {
        //logDebug("not showed:", mx, my, pos_lower.x, pos_lower.y, pos_lower.x + dim_lower.w, pos_lower.y + dim_lower.h);
        return true;
    }
  }
  return false;

  //logDebug("upper:", (pos.y+dim.h), my, pos_lower.x, mx,dim_lower.h,dim_lower.w);
  if(my>=(pos.y+dim.h)){
	  if(my<(pos_lower.y+dim_lower.h) && mx>pos_lower.x && mx<(pos_lower.x+dim_lower.w)){
		  return true;
		  }

	  }else{
		    if(my>pos.y && mx>pos.x && mx<(pos.x+dim.w)){
		  return true;
		  }

		  }
		  return false;

}

function checkForHideSchmappletTextPanel(evt) {
  if (!showed) return;

    if (isMouseInsideContainer(evt,'whatsthis','GetSchmappletText')) return;
    // if (!isMouseOutsideSchmappletText(evt)) return;

  $('GetSchmappletText').style.visibility='hidden';
  showed = false;
  autoPlay();
  try {
  schmapplet.delay.cancel();
  schmapplet.delay = null;
  } catch (err) {
  }

  return false;
}

function hideSchmappletTextPanel(evt){ //logDebug("dsdfasdfasdf");
    if (isMouseInsideSchmappletText(evt)) return;
    $('GetSchmappletText').style.visibility='hidden';
    clearTimeout (getThisWidgetPauseTimerId);
    showed = false;
    autoPlay();

    try {
    schmapplet.delay.cancel();
    schmapplet.delay = null;
    } catch (err) {
    }
}

function hideGuideHotSwap(evt){

    if (isMouseInsideContainer(evt,'title-button','guide-hotswap-div') 
	   || loadingNewSchmapplet) return;
    try{
        if($('guide-hotswap-frame').contentWindow.document.getElementById('leftMenu').style.display == 'none') {
            $('guide-hotswap-frame').contentWindow.goBack(true);
        }
    }catch(e){}
    if($('guide-hotswap-frame'))
    $('guide-hotswap-frame').style.visibility='hidden';
    $('guide-hotswap-div').style.visibility='hidden';
    guide_hotswap_showed = false;
    section_hotswap_showed = false;
    autoPlay();

    try {
    schmapplet.delay.cancel();
    schmapplet.delay = null;
    } catch (err) {
    }
}


function hideSectionHotSwap(evt){

   if (isMouseInsideSection(evt) || loadingNewSchmapplet) return;
   try{
        if($('section-hotswap-frame').contentWindow.document.getElementById('leftMenu').style.display == 'none') {
            $('section-hotswap-frame').contentWindow.goBack(true);
        }
    }catch(e){}
      $('section-hotswap-frame').style.visibility='hidden';
      $('section-hotswap-div').style.visibility='hidden';
      guide_hotswap_showed = false;
      section_hotswap_showed = false;
     autoPlay();
    try {
    schmapplet.delay.cancel();
    schmapplet.delay = null;
    } catch (err) {
    }
}


function clickHere() {

    var pagePath = window.location.pathname;
    var pageName = pagePath.substring(pagePath.lastIndexOf('/') + 1).replace('.html', '');
    if(schmapplet.map){
		var mapProvider = schmapplet.map.provider;
	}else{
		var mapProvider = map_api_order[0].substr(0,1).toLowerCase();
		}
    var normalURL = new StringBuffer();
	if(schmapplet.needGoogle) {
	schmapplet.customizePage = '/templates/customize_sports.html';
	}
	normalURL.append(schmapplet.customizePage).append("?width=").append(schmapplet.frameWidth).append("&height=").append(schmapplet.frameHeight).append("&tid=");
    var pageTid = template.ident;
    var pageFullId = pageName.substr(pageName.length-1);
	if(mapProvider =="c"){
		mapProvider = pageFullId;
	}
    normalURL.append(pageTid).append("&tname=").append(pageTid).append(mapProvider) ;
    normalURL.append("&uid=").append(schmapplet.uid).append("&sid=") ;
    normalURL.append(schmapplet.sid);
    if (schmapplet.si)
    {
        normalURL.append("&sit=").append(schmapplet.si);  // Use temporary 'sit' parameter to avoid SSI inclusion of 'below widget text' on customization page
    }

	  if (!schmapplet.isiGoogle &&  schmapplet.lang){
        normalURL.append("&lang=").append(schmapplet.lang);
    }
    if (schmapplet.schmapmap)
    {
        normalURL.append("&schmapmap=").append(schmapplet.schmapmap);
    }
    normalURL.append("#mapview=").append(schmapplet.mapview);
    normalURL.append("&tab=").append(tabs[schmapplet.tabOrder].tabRealView) ;
    if(fixedPlace != null) {
	    normalURL.append("&placeid=");
	    normalURL.append(fixedPlace);
    }
    normalURL.append("&c=").append(colorset) ;
    var s = Map_object.schmapplet_s.split(" ");
    normalURL.append("&topleft=").append(s[0]).append(",").append(s[1]);
    normalURL.append("&bottomright=").append(s[2]).append(",").append(s[3]);
    if(autoplayUrl != null)
        normalURL.append("&autoplay=").append(schmapplet.autoplay);
    if(showMenusFromUrl != null) {
        normalURL.append("&showMenus=").append(showMenusFromUrl);
    }

    window.open(normalURL.toString(), '',
            "width=1010, height=790, scrollbars=yes, menubar=no, resizable=yes,status=no");
	$('GetSchmappletText').style.visibility = 'hidden';

}
function showSchmappletTextPanel(evt){
    if (showed) return;
	var delayTime = 0.3;
    if(schmapplet.getWidgetPanel && schmapplet.getWidgetPanel.length>20 &&templateChanged){
        $('GetSchmappletText').innerHTML = schmapplet.getWidgetPanel;
		templateChanged = 0;
                analyticsConnect ('code', 'onclick', clickselect, analyticsHooks.copyCodeLeft);

	    if($('GetSchmappletText').firstChild.nodeType ==3) //nodeType is 3 means blank line or space
	        removeElement($('GetSchmappletText').firstChild);
    }
    schmapplet.delay = callLater(delayTime, function(){
									  if (!schmapplet.delay) return;

									  getThisWidgetPauseTimerId = setTimeout ("pausedOverGetTHisWidgetPanel()", 5000);
									  getThisWidgetPauseTimerId = setTimeout ("pausedOverGetTHisWidgetPanel()", 5000);
									  showed = true;

								      if(isIE6){
							            var ct = $('codetext');
							            // logDebug(ct.clientWidth + ";" + $('GetSchmappletText').clientWidth);
								        if (ct.clientWidth > $('GetSchmappletText').clientWidth)
									        setElementDimensions('code',{w: ct.clientWidth - 21});
									    else
									        setElementDimensions('code',{w: ct.clientWidth - 5});
                                      }

									  autoPause();

									   if(typeof(xparams) != 'undefined' &&  typeof(xparams.urlCode) != 'undefined' && xparams.urlCode != ''){
										   iframeAnchor='<a href="http://www.schmap.com/widgets/'+xparams.urlCode+'">'+xparams["iframeUrlText"]+'</a>';
										   }else{
											iframeAnchor='';
										   }
        iframeCode = getiFrameSrc();
									if($('code'))
									  $('code').value = concat(['<iframe id="schmapplet" frameborder="0" scrolling="no" marginwidth="0" marginheight="0" allowTransparency="true" style="border-style:none; border-width:0px;" width="',
                                                                document.body.clientWidth,'" height="',document.body.clientHeight,'" src="',
                                                                iframeCode,'">',iframeAnchor,'</iframe>']);
          $('GetSchmappletText').style.visibility = 'visible';
          analyticsConnect ('custom-link', 'onclick', function(){}, analyticsHooks.customizeLink);
   })
}

function pausedOverGetTHisWidgetPanel()
{
   if(trackPage) 
   {
       pageTracker._trackPageview(analyticsHooks.getthiswidget5s.text);
   }
}

function showGuideHotSwap(evt){
	// remove all codes about callLater, that cause loading slowly

    // NPF - DON'T REMOVE callLater CODE!! It is needed so that the guide menu does not flash up
    //       when the cursor is moved very quickly over the dropdown arrow.
    var delayTime = 0.2;

    // Saving and restoring the guide-hotswap-div html prevent the Firefox 'never stops loading' problem
    if ($('guide-hotswap-div').innerHTML == '') {
        $('guide-hotswap-div').innerHTML = guideHtml;
    }

    if(settings.MiniMenuOverrideName != 'undefined'
            && settings.MiniMenuOverrideName != null
            && settings.MiniMenuOverrideName.length > 0) {
        var guidePath = '/xml/' + settings.MiniMenuOverrideName;
        guideSrcXml = '/common/minicitiesmenu.html?'+guidePath+'&Countries';
        truncationNeeded = 0;
    } else {
        var guidePath = '/xml/mininavmenu.xml' ;
        truncationNeeded = 1;
    }
    schmapplet.delay =
        callLater (delayTime,
                   function() {
                       if (!schmapplet.delay) return;
                       //if (guide_hotswap_showed) return;
                       if(guideLoaded == 0)
                       {
                           loadCountriesInfo(guidePath);
                           $('guide-hotswap-frame').contentWindow.location.replace(guideSrcXml);
                           guideLoaded = 1;
                       }
					    if(isSafari) {
                            changeIframe();
                         }
	                   guide_hotswap_showed = true;
                       section_hotswap_showed = false;
                       $('guide-hotswap-div').style.visibility='visible';
                       $('guide-hotswap-frame').style.visibility='visible';
                       $('section-hotswap-div').style.visibility='hidden';
                       if($('section-hotswap-frame'))
                           $('section-hotswap-frame').style.visibility='hidden';
                       $('loading-message-guide').style.visibility='hidden';

                    if(!(BrowserDetect.browser === "Firefox" || isSafari)){
	   	           // firefox don't no the this iframe ,so can't use for firfox;
		              try{  //every time when call the function which is in other page like iframe or parent, we need use try catch
                          window.frames["guide-hotswap-frame"].window.mainAlign();
		              }catch(e){ }
	               } else{
				    var iframeH = getElementDimensions('canvas').h;
					var iframeW = getElementDimensions('canvas').w;
					var temW = iframeW -6;
                    var temH = iframeH - 24 - 23;
                    setElementDimensions('guide-hotswap-frame', {h:temH,w:temW});
					window.frames["guide-hotswap-frame"].window.mainAlign();
				   }
	           });
     autoPause();
}

function showSectionHotSwap(evt){
	// remove all codes about callLater, that cause loading slowly

    // NPF - DON'T REMOVE callLater CODE!! It is needed so that the guide menu does not flash up
    //       when the cursor is moved very quickly over the dropdown arrow.

    var delayTime = 0.2;

    if (section_hotswap_showed)
        return;

    if ($('section-hotswap-div').innerHTML == '') {
        $('section-hotswap-div').innerHTML = sectionHtml;
    }

    schmapplet.delay = callLater (delayTime,
                                  function() {
                                      if (!schmapplet.delay) return;
                                          if(sectionLoaded == 0) {
                                          sectionSrcXml = getSectionSrcXml(schmapplet.uid,
                                          settings.MiniMenu2OverrideName);
                                          $('section-hotswap-frame').contentWindow.document.body.innerHTML = '';
                                          $('section-hotswap-frame').contentWindow.location.replace(sectionSrcXml);
                                          sectionLoaded = 1;
                                      }

	                              section_hotswap_showed = true;
                                  if(isSafari) {
                                      changeIframe();
                                  }
	                              guide_hotswap_showed = false;
	                              $('section-hotswap-div').style.visibility = 'visible';
                                  $('section-hotswap-frame').style.visibility='visible';
                                  $('guide-hotswap-div').style.visibility='hidden';
	                              if(!(BrowserDetect.browser === "Firefox" || isSafari)){
		                          // firefox don't no the this iframe ,so can't use for firfox;
                                    try{
		                              window.frames["section-hotswap-frame"].window.mainAlign();
		                            } catch(e){ }
	                              } else{
								    var iframeH = getElementDimensions('canvas').h;
									var iframeW = getElementDimensions('canvas').w;
									var temW = iframeW -6;
				                    var temH = iframeH - 24 - 23;
				                    setElementDimensions('section-hotswap-frame', {h:temH,w:temW});
				                    window.frames["section-hotswap-frame"].window.mainAlign();
								 }
	                          });
     autoPause();
}

function flashPlayButton(evt) {
	try {
		if(!evt) num++;
		if (num%2) {
			hideElement(settings.playb);
		 	showElement(settings.playf);
		} else {
     		hideElement(settings.playf);
			showElement(settings.playb);
    	}
		if(num==schmapplet.cycleTime){
			cyclePlace();
			num=0;
		}
    	flash_d = callLater(flashTime, flashPlayButton);
   	} catch (err) {
        logException(err, "7.");
    }
}
function stopFlashPlayButton() {
    try {
    if(flash_d) {
        flash_d.cancel();
        flash_d = null;
        showElement(settings.playb);
		hideElement(settings.playf);
        }
    }catch (err) {
		logException(err, "8.");
	}
}

function spotRestore() {
    try {
        schmapplet.places[schmapplet.selected].unhighlight();
        if (typeof(schmapplet.placeid) != "undefined"
                && schmapplet.placeid.length > 0) {
            var placeIndex = schmapplet.placesById[schmapplet.placeid];

            if (placeIndex !== undefined) {
                // restore original place
                schmapplet.selected = placeIndex;
                schmapplet.places[schmapplet.selected].highlight(null,true);
                setCurrentCounter(schmapplet.selected + 1);
            }
        }
    } catch (err) {
        logException(err, "9.");
    }
}

function placeClick(evt) {
    if(typeof(schmapplet.selected) == 'undefined') {
        schmapplet.selected = schmapplet.placesById[this.placeid] - 1;
    }
    if(isPlaceOnly) {
       var placeid = 0;
       schmapplet.selected = 0;
    } else {
       var placeid = schmapplet.places[schmapplet.selected].id;
    }
    if (zoomLevel > 0) {
        zoomInOut.apply('zoom-p');
       if (schmapplet.places[schmapplet.selected].marker)
            schmapplet.places[schmapplet.selected].marker.hide();
	   if (schmapplet.places[schmapplet.selected].Gmarker)
            schmapplet.places[schmapplet.selected].Gmarker.hide();
    }else{
        if (fixedPlace === placeid) {
		ifAutoPlay(schmapplet.autoplay);
           fixedPlace = null;
          // schmapplet.placeid = schmapplet.places[0].id;
           if (autoPlaying) {
               autoPlayPaused = false;
            }
           if (schmapplet.places[schmapplet.selected].markerbig) {
             schmapplet.places[schmapplet.selected].markerbig.hide();
             schmapplet.places[schmapplet.selected].marker.show();
           } 
		   if (schmapplet.places[schmapplet.selected].Gmarkerbig) {
             schmapplet.places[schmapplet.selected].Gmarkerbig.hide();
             schmapplet.places[schmapplet.selected].Gmarker.show();
           }
       } else {
            ifAutoPlay(false);
            if(schmapplet.uplace && placeid == schmapplet.uplace.id) {
               fixedPlace = null;
            } else {
               fixedPlace = placeid ; 
            }
            schmapplet.placeid = placeid;
            if (schmapplet.places[schmapplet.selected].marker) {
                schmapplet.places[schmapplet.selected].marker.hide();
                schmapplet.places[schmapplet.selected].markerbig.show();
             }
			 if (schmapplet.places[schmapplet.selected].Gmarker) {
                schmapplet.places[schmapplet.selected].Gmarker.hide();
                schmapplet.places[schmapplet.selected].Gmarkerbig.show();
             }
       }
    }
    updateParentIframeCode();
}

function spotClick(evt) {
    try {
    if(schmapplet.places[schmapplet.selected].id === this.placeid) {
        schmapplet.places[schmapplet.selected].highlight(null,true);
        schmapplet.placeid = this.placeid;
        if (zoomLevel > 0) {
            if (schmapplet.places[schmapplet.selected].zoomedIn) {
                if (isIE6 || isIE7) {
                    var cursor = '/images/zoomout.cur';
                } else {
                    var cursor = '-moz-zoom-out';
                }
            } else {
                if (isIE6 || isIE7) {
                    var cursor = '/images/zoom.cur';
                } else {
                    var cursor = '-moz-zoom-in';
                }
            }

            if (schmapplet.places[schmapplet.selected].marker) {
                setStyle(schmapplet.places[schmapplet.selected].markerbig.getElement(), {'cursor':cursor});
                setStyle(schmapplet.places[schmapplet.selected].marker.getElement(), {'cursor':cursor});
            }
			if (schmapplet.places[schmapplet.selected].Gmarker) {
            setStyle(schmapplet.places[schmapplet.selected].Gmarkerbig.getElement(), {'cursor':cursor});
            setStyle(schmapplet.places[schmapplet.selected].Gmarker.getElement(), {'cursor':cursor});
			
        }
        }
       return;
    }
         schmapplet.places[schmapplet.selected].unhighlight();
    if(placesChecked && schmapplet.uplace) {
        schmapplet.selected = schmapplet.placesById[this.placeid] - 1  ;
        if(schmapplet.selected < 0) {
           schmapplet.selected = 0; 
        }
    } else {
       schmapplet.selected = schmapplet.placesById[this.placeid] ;
    }
    schmapplet.placeid = schmapplet.places[schmapplet.selected].id;
    schmapplet.places[schmapplet.selected].highlight(null,true);
    if (zoomLevel > 0) {
        if (schmapplet.places[schmapplet.selected].zoomedIn) {
                if (isIE6 || isIE7) {
                    var cursor = '/images/zoomout.cur';
                } else {
                    var cursor = '-moz-zoom-out';
                }
            } else {
                if (isIE6 || isIE7) {
                    var cursor = '/images/zoom.cur';
                } else {
                    var cursor = '-moz-zoom-in';
                }
            }

        if (schmapplet.places[schmapplet.selected].marker) {
            setStyle(schmapplet.places[schmapplet.selected].markerbig.getElement(), {'cursor':cursor});
            setStyle(schmapplet.places[schmapplet.selected].marker.getElement(), {'cursor':cursor});
			
        } 
		if (schmapplet.places[schmapplet.selected].Gmarker) {
            setStyle(schmapplet.places[schmapplet.selected].Gmarkerbig.getElement(), {'cursor':cursor});
            setStyle(schmapplet.places[schmapplet.selected].Gmarker.getElement(), {'cursor':cursor});
			
        }
        }
        setCurrentCounter (schmapplet.selected + 1);
    } catch (err) {
        logException(err, "spotClick: " + schmapplet.selected + ".");
    }
    if(typeof(evt.stop) == 'function') {
        evt.stop();
    }
}

function waitForWidth(flag){
    logDebug('flag',flag);
    if(!loadingNewMap
            && typeof(schmapplet.map)!='undefined'){
		    return false;	
	} 
	logTime("stat load map");
	if(MochiKit.Maps === undefined){
	if(flag){
	connect(window, 'MochiMaps-load', zoomInOut);
	}else{
	connect(window, 'MochiMaps-load', waitForWidth);
	}
		
	$('map2').innerHTML = '<p style="height: 100%; background-color: #c0c0c0;">loading map...</p>';
	setStyle('map2', {visibility: 'visible'});
	importGMapUrl()
	return true;
	}
	  loadingNewMap = false;	
    try {
 	if ($('map').clientWidth <= 0) {
	    callLater(gmapTime, waitForWidth);
		return;
 	}
        var orderLen = map_api_order.length;
        var mapi = findArgument('mapapi');
        unshiftElement(map_api_order, mapi);
        for(var i = 0; i < orderLen; i++) {
            var thisOrder = map_api_order[i] ;
            MochiKit.Maps = MochiKit['Maps__' + thisOrder ];
            try {
                Make_Map();
                break;
            } catch (e) {
		logException(e, 'Make_Map: ');
                replaceChildNodes('map');
            }
        }
    } catch (err) {
        logException(err, "11.");
    }
	return false;
}

PlaceObj.prototype.connectMarkerSignals = function() {

    // If this place this a non-empty phone number field in the s-template, this is a place with a score,
    // which should have a higher priority in terms of attaching mouse-over event to the icon than a place
    // without a score
    var placePriority = 1;
    if((typeof(schmapplet.usingSTemplate) != 'undefined') && schmapplet.usingSTemplate == 1) 
    {
        if (place.tel.length)
        {
            placePriority = 2;
        }
    }
    
    
    // Avoid connecting same marker to many places
    if (typeof(this.marker.eventAttachPriority) == 'undefined'
	    || placePriority > this.marker.eventAttachPriority)
    {
        analyticsConnect (this.markerbig, 'click', placeClick, analyticsHooks.mapIconClick, true);
        analyticsConnect (this.marker, 'click', placeClick, analyticsHooks.mapIconClick, true);
        connect(this.markerbig, 'mouseout', spotRestore);
        connect(this.marker, 'mouseover', spotClick);
        connect(this.markerbig, 'mouseover', spotClick);
        this.marker.eventAttachPriority = placePriority;
        this.markerbig.placeid = place.id;
        this.marker.placeid = place.id;
    }
}

PlaceObj.prototype.connectGMarkerSignals = function() {
    analyticsConnect (this.Gmarkerbig, 'click', placeClick, analyticsHooks.mapIconClick, true);
    analyticsConnect (this.Gmarker, 'click', placeClick, analyticsHooks.mapIconClick, true);
    connect(this.Gmarkerbig, 'mouseout', spotRestore);
    connect(this.Gmarker, 'mouseover', spotClick);
    connect(this.Gmarkerbig, 'mouseover', spotClick);
}

function rebuildMapDiv(){
	clearMapLeaks();
			removeElement('map');
			appendChildNodes('canvas',  DIV({id: 'map'}));
			if(typeof(schmapplet.ultranarrow) != 'undefined'
			&& schmapplet.ultranarrow.toLowerCase() == 'true') {
				$('map').style.left = '2px';
				$('map').style.right = '2px';
			}
			if(isGuideSchmapplet){
			    var newtop = 38;
			    setStyle('map', {'top': newtop + 'px'});
			}
			    if(isIE6) {
                  unbreakIE();
            }
			connect('map', 'onmouseover', autoPauseEx);
			connect('map', 'onmouseout', autoPlayEx);
}

function loadSchmapMapData(dir,newXml,tcode) {
	loadingNewSchmapplet = true;
	var path = [dir, "xparams.sjs"].join("/");
	if(schmapplet.map){
		schmapplet.map.loadNewData(path);
		schmapplet.toLoadNewData = false;
	}else{
		schmapplet.toLoadNewData = path;
	}
	if (!loadingEmptyGuide){
                if($('section-hotswap-frame') != null) {
                $('section-hotswap-frame').style.visibility='hidden';
                $('loading-message-guide').style.visibility = 'visible';
        }
        $('guide-hotswap-div').style.visibility = 'visible';
	    if($('guide-hotswap-frame') != null) {
		    $('guide-hotswap-frame').style.visibility = 'hidden';
		    $('loading-message-guide').style.visibility = 'visible';
	     }
	}
	addScript(path,loadNewPlaces,newXml,tcode);
}

function centerMap() {
    schmapplet.map.setDisplay(schmapplet.bounds.getCenter(), 0.55);
}

function Make_Map(){
   if(initialized){
       rebuildMapDiv();
   }

   $('map').innerHTML = '';
	schmapplet.readyToMakeIcons = true;
    schmapplet.map = new MochiKit.Maps.Map('map');
	try {
		// logDebug('make map     ',Map_object.schmapplet_s);
		schmapplet.origbounds = MochiKit.Maps.Bounds.fromGeoRSS(Map_object.origGeoBox);
        schmapplet.bounds = MochiKit.Maps.Bounds.fromGeoRSS(Map_object.schmapplet_s);
    } catch(e) {

        logException(e, 'Make_Map.');
    }
	logDebug('initialized',initialized);
   if(schmapplet.toLoadNewData){
		schmapplet.map.loadNewData(schmapplet.toLoadNewData);
   }
	    logTime('Finished Making map');
    centerMaps();
    schmapplet.actualOrigBounds = schmapplet.map.actualBoundsFromIdealBounds (schmapplet.origbounds); 
    if(schmapplet.map.provider == 's')
    {
        schmapplet.map.setDisplay(schmapplet.origbounds.getCenter());
    }
    if(schmapplet.mapview != 'Map'
            || (typeof(schmapplet.places[schmapplet.selected]) != 'undefined'
            && schmapplet.places[schmapplet.selected].zoomedIn)) {
        callLater(0.1, function() {
		if(schmapplet.places[schmapplet.selected].zoomedIn){
           schmapplet.map.setMapType(settings.ZoomMode);
			if((schmapplet.map.hideAll !== undefined)) {
				schmapplet.map.hideAll(true);
			}
          }else{
		 schmapplet.map.setMapType(schmapplet.mapview);
		  }
			 });
    }
    $('map').style.position = 'absolute';
    $('map2').style.position = 'absolute';
    if(isIE6) {
        if(!unbreakIERun) {
           unbreakIE();
        }
        //callLater(0.01, function() {schmapplet.map.fixSize()});
    } else {
        $('map').style.width = '';
        $('map').style.height = '';
        $('map2').style.width = '';
        $('map2').style.height = '';
    }
    schmapplet.marker = false;
    schmapplet.nextIconToMake = undefined;
    if (schmapplet.map.provider == 's'||schmapplet.map.provider == 'c')
    {   
        schmapplet.needGoogle = true;
    }else{
	schmapplet.needGoogle = false;
	}
	callLater(0.1, partial(makeIcons, MochiKit.Maps))
    setStyle('map2', {visibility: 'hidden'});
	if(schmapplet.places[schmapplet.selected].gmarkerbig)
	   schmapplet.places[schmapplet.selected].gmarkerbig.hide();
}

function postMakeIcons1(map) {
	schmapplet.places[schmapplet.selected].maphighlight();
	setStyle('subtitle-ie', {'height': '30px'});
    if (map.provider != 's' && !schmapplet.places[schmapplet.selected].zoomedIn)
    {   
       centerMaps();
    }
    connect(map, 'load', mapsUpdate);
    connect(map, 'zoomend', mapsUpdate);
    connect(map, 'moveend', mapsUpdate);
	

}

function postMakeIcons2() {
    schmapplet.places[schmapplet.selected].markerbig.show();
	if(schmapplet.places[schmapplet.selected].Gmarkerbig)
	schmapplet.places[schmapplet.selected].Gmarkerbig.show();
    if(isIE6) {
        schmapplet.map.fixSize();
    }
	try{	
	    if(settings['MapLink'] == 'true' && removeLinks == false){
	        connect(schmapplet.map.markersElement,'onclick', mainTitlGo);
			setStyle(schmapplet.map.markersElement, {'cursor':'pointer'});
	        connect(schmapplet.map.imgElement,'onclick', mainTitlGo);
			setStyle(schmapplet.map.imgElement, {'cursor':'pointer'})
		}
		logTime('end of makeing  iframes  ',true);
	}catch(e){
    }

    //logDebug("start change template to t014");
    //changeTemplate("t014");
    // This is where we'd check if we want to pre-select a place
}

function updateParentIframeCode() {
	try {
   		if(parent) {
        	if(parent.changeIframeCode) {
				iframeCode = getiFrameSrc();
        		parent.changeIframeCode(iframeCode);
				parent.changeAutoPlay(schmapplet.autoplay);
    		}
		}
	} catch(e) {}
}

function captureWheel(event){
    stopPropagation(event);
    preventDefault(event);
    //logDebug("capture: wheel:" + event.detail);
}

function loopTillPhotoMet() {
    try {
        if(typeof(schmapplet.selected) == 'undefined') {
            schmapplet.selected = 0;
        }
	    if(schmapplet.places[schmapplet.selected].photo_objs.length == 0) {

	        schmapplet.selected += 1;
	        if(schmapplet.selected == schmapplet.places.length)
	            schmapplet.selected = 0;

	        var initValue = schmapplet.selected;
	        while (schmapplet.places[schmapplet.selected].photo_objs.length <= 0) {
	            schmapplet.selected += 1;
	            if(schmapplet.selected == schmapplet.places.length)
	                schmapplet.selected = 0;

	            if (initValue == schmapplet.selected) break;
			}
			schmapplet.selectedPhoto = 0;
			schmapplet.places[schmapplet.selected].highlight();
			setCurrentCounter (schmapplet.selected + 1);
	    }
    } catch (err) {
        logException(err, "4444.");
    }
}

function loopTillStatsMet() {
    try {
        if(typeof(schmapplet.selected) == 'undefined') {
            schmapplet.selected = 0;
        }
		 if(schmapplet.places[schmapplet.selected].ldesc=='') {
			schmapplet.places[schmapplet.selected].unhighlight();
	        schmapplet.selected -= 1;
	        if(schmapplet.selected < 0)
	            schmapplet.selected = schmapplet.places.length-1;

	        var initValue = schmapplet.selected;
	        while (schmapplet.places[schmapplet.selected].ldesc=='') {
	            schmapplet.selected--;
	            if(schmapplet.selected < 0 )
	                schmapplet.selected = schmapplet.places.length-1;

	            if (initValue == schmapplet.selected) break;
			}
			schmapplet.places[schmapplet.selected].highlight();
			setCurrentCounter (schmapplet.selected + 1);
		 }
    } catch (err) {
        logException(err, "4444.");
    }
}

function changeViewByOrder(old_order, new_order,flag) {
	if(old_order>=tabs.length){
		old_order = tabs.length -1;
	}
    var new_view = tabs[new_order].tabRealView;
	if (noPhotosAtAll && new_view == 'photos') {
        return;
    }
    if(isPhotoView || new_view == 'photos') {
	    createTopPhotoTable();
       	if(schmapplet.IEquirks
            || BrowserDetect.browser == 'Safari'){
		if(schmapplet.mycurrent_cellTD){
		    setStyle(schmapplet.mycurrent_cellTD,
                {'height': (Math.abs(document.body.clientHeight - 160 - 16)) + 'px'});
			setStyle('photo-button',
                {'width': (document.body.clientWidth - 22) + 'px'});
		}
	}
	   makeLargePhotos();
    }
    var photoView = false;
    schmapplet.selectedPhoto = 0;

    if(tabs[old_order].tabType == 'maptitle') {
       // $('map').style.visibility = "hidden";
    } else 
        $('place-name-top').style.visibility = "hidden";
	if(tabs[old_order].tabType == 'miniphotostitle' 
	    && tabs[new_order].tabType != 'miniphotostitle'){
    	setStyle('photos', {'z-index':'4'});
        setStyle('loading-message-guide',{'visibility':'hidden'});
	}else {
		setStyle('photos', {'z-index':'6'});
	}
    if(tabs[new_order].tabType != 'maptitle' 
            && tabs[new_order].tabType != 'htmltitle'
            && tabs[new_order].tabType != 'miniphotostitle'
            && tabs[new_order].tabType != 'htmltitle1') {
        $('place-name-top').style.visibility = "visible";
        if (tabs[new_order].tabType == 'miniphotostitle') {
            photoView = true;
        }
    }
    if(tabs[new_order].hasDetail == 'no') {
        hideElement('place-info');
        tabs[new_order].tabDiv.style.bottom = '34px';
    } else {
        showElement('place-info');
        var placeH = getElementDimensions('place-info').h;
        tabs[new_order].tabDiv.style.bottom = placeH +34+'px';
    }
    if(new_view == 'photos') {
        photoView = true;
		loopTillPhotoMet();
    }
    if (isPhotoView != photoView) {
    	if (photoView) {
    		autoPlay();
    	} else {
           autoPause();
        }
	    isPhotoView = photoView;
    }

    schmapplet.view = new_view;
    schmapplet.tabOrder = new_order;
	schmapplet.tabLink=tabs[new_order].tabRealView;
    removeElementClass('view-link' + old_order, 'current-view-link');
    addElementClass('view-link' + new_order, 'current-view-link');
     if(typeof(schmapplet.places[schmapplet.selected]) != 'undefined'){
            schmapplet.places[schmapplet.selected].highlight();
     } else {
           schmapplet.places[0].highlight();
    }
    
    var spanWidth = $('view-panel').clientWidth;
	if (tabs[new_order].tabType == 'htmltitle') {
		   $('schedule').style.visibility = 'visible';
           schmapplet.htmlPanelClick = true;
		if(initialized){
			if(schmapplet.tabLinkOrder != new_order 
			   && $('schedule').currentIndex){
				jugdescroll($('schedule'));
			}
		}
        if(typeof(schmapplet.comingGame) != 'undefined'
		     && schmapplet.comingGame != null) {
            changeBG.apply(schmapplet.comingGame);
		    schmapplet.selected = schmapplet.comingGame.num -1;
        }
		ifAutoPlay(false);
	}else{
		if(schmapplet.gameDayArray!==undefined){
    	removeElementClass(schmapplet.gameDayArray[schmapplet.selected],'backDay');
        addElementClass(schmapplet.gameDayArray[schmapplet.selected],'schedule');
		}
		schmapplet.htmlPanelClick = false;
		}

	if(tabs[old_order].tabType == 'maptitle') {
	    //$('map').style.visibility = "hidden";
	} else {
		if(tabs[old_order].tabRealView =='details'
                && (isSafari || isMacintosh)){
	    	hideElement('details');
		} else {
			$(tabs[old_order].tabRealView).style.visibility = "hidden";
		}
	}
	

    if(tabs[new_order].tabType == 'maptitle') {
	    if($('photo-table'))
			$('photo-table').style.visibility='hidden';
        ifAutoPlay(schmapplet.autoplay);
		if(!flag){
		   waitForWidth();
		} 
		//$('map').style.visibility = "visible";
    } else {
 	   if(tabs[new_order].tabRealView == 'details'
            && (isSafari || isMacintosh)){
		   showElement('details');
	   }else{
 	     $(tabs[new_order].tabRealView).style.visibility = "visible";
       }
    }
    repositionPlaceStripIcons (spanWidth);
	if (tabs[new_order].tabType == 'htmltitle1') {
	    ifAutoPlay(false)
	    isStatsView = true;
		loopTillStatsMet();
        jugdescroll($('stats'));
	}else{
	    isStatsView = false;
	}
	updateParentIframeCode();
	try{
	   parent.updateRadios(tabs.length);
	} catch(e){}
}

	
function changeView() {
    var old_order = schmapplet.tabOrder;  
	if(old_order>=tabs.length){
		old_order = tabs.length -1;
	}
    var old_view = tabs[old_order].tabRealView;
    var new_order = this.order;
    if (new_order === undefined) new_order = 0;
    var new_view = tabs[new_order].tabRealView;
    if(new_view == old_view) return;
    changeViewByOrder(old_order, new_order);
	try{
	    parent.changeView(this.innerHTML);
	}catch(e){
		//logDebug("changeView:  ",e);
	}
	if(schmapplet.IEquirks
            || BrowserDetect.browser == 'Safari'){
		if(schmapplet.mycurrent_cellTD){
		    setStyle(schmapplet.mycurrent_cellTD,
                {'height': ((document.body.clientHeight - 160) - 16) + 'px'});
			setStyle('photo-button',
                {'width': (document.body.clientWidth - 22) + 'px'});
            adjustPhotoTab();
		}

	}
}


function showView(tab_order) {

    $('GetSchmappletText').style.visibility = "hidden";
  //  $('guide-hotswap-div').style.visibility = "hidden";
    $('section-hotswap-div').style.visibility = "hidden";
    $('place-name-top').style.visibility = "hidden";

    //$('map').style.visibility = "hidden";
    var viewLen = tabViews.length  ;
    for (var i = 1; i < viewLen; i++) {
        var thisView = tabViews[i];
       if(thisView=='details'
               && (isSafari || isMacintosh)){
		   hideElement('details');
	   }else{
        $(thisView).style.visibility = "hidden";
    }

    }
    if(tabs[tab_order].tabType == 'detailtitle')
	    $('place-name-top').style.visibility = "visible";

    if(tabs[tab_order].tabType == 'maptitle') {
        $('map').style.visibility = "visible";
    } else {
		if(tabs[tab_order].tabRealView == 'details'
                && (isSafari || isMacintosh)){
		showElement(tabs[tab_order].tabRealView);
		}else{
	    $(tabs[tab_order].tabRealView).style.visibility = "visible";
		}
    }

    addElementClass('view-link' + tab_order, 'current-view-link');
}

function autoPlayEx(evt) {
	if(schmapplet.pauseClick
            || schmapplet.htmlPanelClick){
		return;
    }
  var mx = evt.mouse().client.x;
  var my = evt.mouse().client.y;
  var pos=getElementPosition('GetSchmappletText');
  var dim=getElementDimensions('GetSchmappletText');
  if(schmapplet.IEquirks) {
      mx+= 1;
      my+= 1;
  }
    if(flash_d == null) {
        flash_d = callLater(flashTime, flashPlayButton);
    }
  autoPlay();

}

function autoPauseEx() {
    if (isPhotoView) {
        var sender = this.id;
        if(sender.match(/^view-link\d$/) || sender == 'place-info')
            return;
    }

    autoPause();
}

function autoPause() {
	autoPausedByParent = false;
	if (autoPlaying) {
    	stopCycling();
	    if (autoPlaying) {
		    autoPlayPaused = true;
	    }
    }
}

function autoPlay(evt) {
    if(!schmapplet.autoplay)
       return;
    if (autoPlayStopped
            ||schmapplet.pauseClick
            ||schmapplet.htmlPanelClick)
        return;
	try {
	autoPausedByParent = false;
	if (autoPlaying && autoPlayPaused) {
		autoPlayPaused = false;
		if (!flash_d) {
		    num = 0;
			flashPlayButton(1);
		}
    }
	} catch (err) {
		logException(err, "12.");
	}
}


function findArgument(name) {
    var arg = window.location.href.split(name + "=");
    if(arg.length < 2) return '';
    arg = arg[1].split('&');
    return arg[0];
}

function checkArgs() {
    var debugAll = window.location.hash;
    var arg = findArgument('c');
    if(colorset != arg){
        colorset = arg;
       changingColor(colorset);
    }
    arg = findArgument('placeid');
    if(arg.length&&schmapplet.placeidUrl!=arg) {
        logDebug('got placeid:', arg, 'in', debugAll);
       // removeArgument('placeid');
        if(arg == '-') {
            if(autoPausedByParent && autoPlayPaused)
                autoPlay();
        } else {
           	schmapplet.placeidUrl = arg;
           	schmapplet.placeid = arg;
            var placeIndex = schmapplet.placesById[arg];
            if((placeIndex !== undefined) &&
               (placeIndex != schmapplet.selected)) {
                if(!autoPlayPaused) {
                    autoPause();
                    autoPausedByParent = true;
                }
                // XXX: when this is merged with the cleaned up code,
                // remove this logic into a new method selectPlace(index)
                schmapplet.places[schmapplet.selected].unhighlight();
                schmapplet.selected = placeIndex;
                schmapplet.places[schmapplet.selected].highlight();
                setCurrentCounter (schmapplet.selected + 1);
            }
        }
    }
    var temType = findArgument('mapview');
    if(temType.length && temType!=schmapplet.mapview) {
       schmapplet.mapview = temType;
       changeMapType(temType);
    }
    arg = findArgument('mapapi');
    if(arg.length&&arg!=schmapplet.mapapi) {
		schmapplet.mapapi = arg;
        logDebug('got mapapi:', arg, 'in', debugAll);
        var current_api = MochiKit.Maps;
        var mapapi = MochiKit['Maps__' + arg];
        if((mapapi !== undefined) && (mapapi.Map !== undefined)) {
            try {
                MochiKit.Maps = mapapi;
                Make_Map();
                if(isIE6)
                  unbreakIE();
            } catch(e) {
                MochiKit.Maps = current_api;
                Make_Map();
            }
        }
    }

}

function updateHashParams(name, value) {
    //var hp = document.location.hash;
    var hp = getHashParams();
    var baseurl = document.location.href.split('#')[0];
    for(var p in hp) {
        if(p == name) {
            hp[p] = value;
        }
        else {
        }
    }

    var paramstr = "";
    for(var p in hp) {
		if(hp[p])
        paramstr += p.concat("=", hp[p], "&");
    }
    paramstr = paramstr.substring(0, paramstr.length - 1);
    document.location.replace(baseurl + "#" + paramstr);
}

function showCustomizePage() {
    var normalURL = new StringBuffer();
    normalURL.append("/templates/customize.html?width=230&height=450&tid=t010&tname=");
    var pagePath=window.location.pathname;
    var pageName=pagePath.substring(pagePath.lastIndexOf('/')+1).replace('.html','');
    //get page name without html
    normalURL.append(pageName).append("&uid=").append(schmapplet.uid);
    normalURL.append("&sid=").append(schmapplet.sid).append("#c=");
    normalURL.append(colorset)
    window.open(normalURL.toString(),
            "customizea",
            "width=950, height=650, scrollbars=no, resizable=no");
}

function printPlace(event) {
    if(typeof(event.stop) != 'undefined') {
        event.stop();
    }
    if(typeof(schmapplet.selected) == 'undefined') {
        schmapplet.selected = 0;
    }
    window.printLoaded = true;
    var place = schmapplet.places[schmapplet.selected];
    getAllPhotos(place);
    window.printPlace = place;
    if(typeof(settings.PlacePrintHtml) == 'undefined') {
       settings.PlacePrintHtml ='/common/printplace.html?type=guide';
    }
     url = settings.PlacePrintHtml + '&map=g';
    window.open(url, 'printPlace', 'height=600,width=800,top=0, left=0, toolbar=yes, menubar=yes, scrollbars=yes, resizable=no,location=no, status=no');
}

function showDriveDirections(event) {
    if (schmapplet.places[schmapplet.selected].stickyPlaceType == 2)
    {
        window.open ("http://www.mapquest.com/directions/");
    }
    else
    {
        var placeid = schmapplet.places[schmapplet.selected].id;
        var url_ = new StringBuffer();
        url_.append("http://www.schmap.com/app/gle?gc=L003&lv=").append(placeid);
        window.open(url_);
    }
}

function zoomInOut(event) {
	if(schmapplet.zoomLinkOver){
		window.open(schmapplet.zoomLinkOver);
		return;
		}
	var tab_order = schmapplet.tabOrder;
        if(tabs[tab_order].tabType != 'maptitle') {
            // find the map view-link
            var tabLen = tabs.length ;
            for (var i = 0; i < tabLen; i++ ) {
                var thisTab = tabs[i];
                if (thisTab.tabType == 'maptitle')
                    break;
            }
            if (i < tabLen)
                changeViewByOrder(tab_order, i,true);
        }
	if(waitForWidth(true)){
		return;
	} 
    if(event && event.stop !== undefined) {
        event.stop();
    }
    logDebug('zoomInOut');
    var spanWidth = $('place-info').clientWidth;
    var map = schmapplet.map;
    var point = schmapplet.places[schmapplet.selected].geocode;
    if(schmapplet.needGoogle) {
        if(MochiKit.Maps__Google === undefined) {
            connect(window, 'MochiMaps-load', zoomInOut);
            $('map2').innerHTML = '<p style="height: 100%; background-color: #c0c0c0;">loading map...</p>';
            setStyle('map2', {visibility: 'visible'});
            importGMapUrl();
            return;
        } else  if(schmapplet.map2 === undefined){
            $('map2').innerHTML = '';
            schmapplet.map2 = new MochiKit.Maps__Google.Map('map2');
			if(schmapplet.map.provider=="c"){
			schmapplet.nextIconToMake =undefined;
			callLater(0.1, partial(makeIcons, MochiKit.Maps__Google,schmapplet.map2));
			}
			// schmapplet.nextIconToMake =schmapplet.selected;
			// callLater(0.1, partial(makeIcons, MochiKit.Maps__Google,schmapplet.map2,schmapplet.nextIconToMake,schmapplet.nextIconToMake+1))
		}
        map = schmapplet.map2;
        if(schmapplet.places[schmapplet.selected].gpoint === undefined) {
            point = new MochiKit.Maps__Google.Point(point.latitude,
                                                    point.longitude);
            schmapplet.places[schmapplet.selected].gpoint = point;
        } else {
            point = schmapplet.places[schmapplet.selected].gpoint;
        }
    }
    if(typeof(schmapplet.selected) == 'undefined'){
        schmapplet.selected = 0;
    }
    var placeid = schmapplet.places[schmapplet.selected].id;
    if (fixedPlace === placeid) {
        fixedPlace = null;
    } else {
        if(schmapplet.uplace && placeid == schmapplet.uplace.id) {
            fixedPlace = null;
        } else {
            fixedPlace = placeid ;
        }
    }
    schmapplet.placeid = schmapplet.places[schmapplet.selected].id;
    if (schmapplet.places[schmapplet.selected].zoomedIn) {
        schmapplet.places[schmapplet.selected].zoomedIn = false;
        setStyle('map2', {visibility: 'hidden'});
		if(schmapplet.places[schmapplet.selected].gmarkerbig)
		   schmapplet.places[schmapplet.selected].gmarkerbig.hide();
		if(!schmapplet.needGoogle||schmapplet.mapResized){
        	schmapplet.map.setDisplay(schmapplet.origbounds.getCenter(), 0.55);
        	schmapplet.map.zoomToBounds(schmapplet.origbounds);
		} 
		schmapplet.mapResized = false;
		if(!(schmapplet.usingSTemplate)) {
            if(settings.UseFunctionIcons !== "undefined" &&
                settings.UseFunctionIcons.match(/^true$/i)) {
                showElement(settings.zoomin);
                hideElement(settings.zoomout);
            } else {
                $('zoom-p').innerHTML = settings.ZoomText;
            }
        } else {
             $('zoom-p').innerHTML = settings.ZoomText;
            var placeName = schmapplet.places[schmapplet.selected].name;
            if (placeName.length * 8 > spanWidth) {
                var temLen = Math.round(spanWidth / 8) ;
                var temTxt = placeName;
                if (temLen + 3 <= placeName.length) {
                    placeName = temTxt.substr(0, temLen) + '...';
                }else{
                    placeName = schmapplet.places[schmapplet.selected].name;
                }
             }else{
                placeName = schmapplet.places[schmapplet.selected].name;
             }
			 var content = new StringBuffer();
				if(settings['StripTitleLink'] =='true' && schmapplet.places[schmapplet.selected].url !==""){
			        content.append('<a href="').append(schmapplet.places[schmapplet.selected].url).append('" target="blank">').append(schmapplet.places[schmapplet.selected].name).append('</a>');
				}else{
				    content.append(placeName);
				}
                $('TitleIn').innerHTML = content.toString();
        }
		schmapplet.zoomedIn = false;
        if(typeof(settings.ZoomMode) == 'string') {
            schmapplet.map.setMapType(schmapplet.mapview);
        }
		
        if(autoPlaying && !flash_d)
            ifAutoPlay(schmapplet.autoplay);
        if((settings.ZoomHideIcons !== undefined) &&
           (schmapplet.map.hideAll !== undefined)) {
            schmapplet.map.hideAll(false);
        }
    } else {        
        var placeLen = schmapplet.places.length;
        for (var k = 0; k < placeLen; k++) {
            var thisPlace = schmapplet.places[k];
            thisPlace.zoomedIn = false;
        }
        schmapplet.places[schmapplet.selected].zoomedIn = true;
        
        if(schmapplet.needGoogle) {
            setStyle('map2', {visibility: 'visible'});
        }
		if(!point){
			point = new MochiKit.Maps.Point(schmapplet.places[schmapplet.selected].geo[0],schmapplet.places[schmapplet.selected].geo[1]);
		}
        map.setDisplay(point, zoomLevel);
        
        if(typeof(settings.ZoomMode) == 'string') {
            map.setMapType(settings.ZoomMode);
        }	

		ifAutoPlay(false);
		if(schmapplet.needGoogle)
		{
			createGMarker(map,schmapplet.places[schmapplet.selected]);
		}
		
		schmapplet.zoomedIn = true;
        if(!(schmapplet.usingSTemplate)) {
            if(settings.UseFunctionIcons !== "undefined"
               && settings.UseFunctionIcons.match(/^true$/i)) {
                showElement(settings.zoomout);
                hideElement(settings.zoomin);
            } else {
                $('zoom-p').innerHTML = settings.ZoomOutText;
            }
        } else {
            $('zoom-p').innerHTML = settings.ZoomOutText;
            var placeName = schmapplet.places[schmapplet.selected].addr2;
            $('TitleIn').initTxt = placeName;
            var myTxt = getTrunction('TitleIn', spanWidth,9);
            $('TitleIn').innerHTML = myTxt;
        }			
    }

}

function zoomOut(event) {
      if(typeof(schmapplet.selected) == 'undefined'){
        schmapplet.selected = 0;
    }
    if (schmapplet.places[schmapplet.selected].zoomedIn) {
        schmapplet.places[schmapplet.selected].zoomedIn = false;
        if (settings.UseFunctionIcons !== "undefined" &&
            settings.UseFunctionIcons.match(/^true$/i)) {
            showElement(settings.zoomin);
            hideElement(settings.zoomout);
        } else {
            $('zoom-p').innerHTML = settings.ZoomText;
        }
    }
    var placeid = schmapplet.places[schmapplet.selected].id;
     if (fixedPlace === placeid) {
        fixedPlace = null;
         schmapplet.placeid = schmapplet.places[0].id ;
    } else {
          if(schmapplet.uplace && placeid == schmapplet.uplace.id) {
               fixedPlace = null;
            } else {
               fixedPlace = placeid ;
            }
        schmapplet.placeid = schmapplet.places[schmapplet.selected].id ;
    }
    schmapplet.map.setDisplay(schmapplet.origbounds.getCenter(), 0.55);
    schmapplet.map.zoomToBounds(schmapplet.origbounds);
    if(typeof(event.stop) != 'undefined') {
        event.stop();
    }
}

function changeStyleSheetColor(matchString, styleName, color) {
    var sheetLen = document.styleSheets.length ;
    for(var i = 0; i < sheetLen; i++) {
        var thisSheet = document.styleSheets[i];
        var s = thisSheet;
        if(!s || !s.href) continue;
        if(!s.href.match(/embedded.css$/)) continue;

        var rules = s.cssRules || s.rules;

	    var rulesLen = rules.length;
        for(var i2 = 0; i2 < rulesLen; i2++) {
            var r = rules[i2];
            var st = r.selectorText;

            if (st.indexOf(matchString) < 0)  continue;

            var rStyle = r.style;
            if( /*rStyle[styleName] &&*/ schmapplet.colorset[color]) {
                try {
                    rStyle[styleName] = '#' + schmapplet.colorset[color];
                } catch(e) {
                    //logDebug('colorset: failed to apply css change');
                }
            }

            break;
        }

        break;
    }
}

function changeStyleSheet(matchString, styleName, styleValue) {
    var sheetLen = document.styleSheets.length;
    for(var i = 0; i < sheetLen; i++) {
        var s = document.styleSheets[i];
        if(!s.href.match(/embedded.css$/)) continue;

        var rules = s.cssRules || s.rules;

	    var rulesLen = rules.length;
        for(var i2 = 0; i2 < rulesLen; i2++) {
            var r = rules[i2];
            var st = r.selectorText;

            if (st.indexOf(matchString) < 0)  continue;

            var rStyle = r.style;

			for (property in rStyle) {

				if(rStyle[property]) {
					//logDebug(selector +'=>'+ property +':'+ styleSet[property])
                    //logDebug(st +'=>'+ property +':'+ rStyle[property]);
				}
			}

            if(rStyle[styleName]) {
                try {
                    rStyle[styleName] = styleValue;
                } catch(e) {
                    //logDebug('colorset: failed to apply css change');
                }
            }

            break;
        }

        break;
    }
}

function getiFrameSrc() {
	var iFrameSrc = new StringBuffer();
    var curTabName = tabs[schmapplet.tabOrder].tabRealView;
	var origSrc = document.location.href;
	if(schmapplet.oldUid){
    	origSrc = origSrc.replace(schmapplet.oldUid,schmapplet.uid);
		origSrc = origSrc.replace(schmapplet.oldSid,schmapplet.sid);
	}
	origSrc = origSrc.replace(schmapplet.pageTemplate,template.ident);
	origSrc = origSrc.split('&mapapi=');
	origSrc = origSrc[0];
	try{
	if(parent.mapboxid){
	origSrc = origSrc.replace("t020d","t020");
	}
	}catch(e){
	}
	var mapapiString = '';
	if(schmapplet.mapapi){
		var origName = schmapplet.pageTid +".html";
		var newPageTid = schmapplet.mapapi.substr(0,1).toLowerCase()
		var newName = newPageTid +'.html';
		origSrc = origSrc.replace(origName,newName);
		}
	origSrc = origSrc.replace('&multimaps=true','');
	var segments = origSrc.match(/(.*)#mapview=[^&#]+([&#].*)/i);
    var url_ = new StringBuffer();
    var s = Map_object.schmapplet_s.split(" ");
    try {
        if(fixedPlace != null && fixedPlace != '') {
          // var placeid = schmapplet.places[schmapplet.selected].id;
	       url_.append("&placeid=");
	       url_.append(fixedPlace);
        }
	} catch(e) {	}
	url_.append("&topleft=").append(s[0]) ;
	url_.append(",").append(s[1]).append("&bottomright=") ;
	url_.append(s[2]).append(",").append(s[3]) ;

    if(schmapplet.uplaceonly){
		url_.append("&uplaceonly=").append(schmapplet.uplaceonly) ;
	} 
	if(schmapplet.subtitle){
		url_.append("&subtitle=").append(schmapplet.subtitle) ;
	}
	iFrameSrc.append(segments[1]);
    iFrameSrc = getSiInUrl(iFrameSrc);

    iFrameSrc.append("#mapview=").append(schmapplet.mapview);
    iFrameSrc.append("&tab=").append(curTabName).append(url_.toString());
    if(autoplayUrl != null)
         iFrameSrc.append("&autoplay=").append(schmapplet.autoplay);
    schmapplet.tabLink = curTabName;

    if (schmapplet.uplace) {
        iFrameSrc.append("&uplace=").append(schmapplet.uplace.id).append("|").append(schmapplet.uplace.geo[0]).append(",").append(schmapplet.uplace.geo[1]).append("|").append(schmapplet.uplace.name).append("|").append(schmapplet.uplace.sdesc);
	}
    if (schmapplet.applyColors) {
        iFrameSrc.append("&applycolors=").append(schmapplet.applyColors);
	}
     if(showMenusFromUrl != null) {
        iFrameSrc.append("&showMenus=").append(showMenusFromUrl);
    }
    iFrameSrc.append("&c=").append(colorset);
    return iFrameSrc.toString();
}

function getFullSchmapURL() {
	var iFrameSrc = new StringBuffer();
    var curTabName = tabs[schmapplet.tabOrder].tabRealView;

    iFrameSrc.append("http://").append(window.location.host).append("/").append(schmapplet.uid).append("/").append(schmapplet.sid).append("/")

    var url_ = new StringBuffer();
    var s = Map_object.schmapplet_s.split(" ");

	if (initPlaceId !== undefined && initPlaceId.length > 0) {
	    url_.append("&p=").append(initPlaceId);
    }

   	url_.append("&topleft=").append(s[0]) ;
	url_.append(",").append(s[1]).append("&bottomright=") ;
	url_.append(s[2]).append(",").append(s[3]) ;
    url_.append("&i=none");
	iFrameSrc.append('#r=none&mapview=').append(schmapplet.mapview);
    iFrameSrc.append("&tab=").append(curTabName).append(url_.toString());


    return iFrameSrc.toString();
}

function getSectionSrcXml(uid, navName) {
    return concat(['/common/minismplmenu.html?/',
             uid, '/', navName, '&Nav']);
}

function setupWidget() {
    logTime('Initialization completed (before framework creation)');
    try{
        if(parent){
            if (typeof(parent.placesChecked) != 'undefined') {
                placesChecked = parent.placesChecked;
            }
        }
    } catch(e){}
    if(settings['CenteredLayout']=='true'){
		addElementClass('place-info','alignCenter');
	}else{
		removeElementClass('place-info','alignCenter');
	}
	if(settings['templateLayout']=='geotweet'){
 
	 schmapplet.placetweet = true;

	}
    $('canvas').style.visibility = "visible";
	var pagePath=window.location.pathname;
	var pageName=pagePath.substring(pagePath.lastIndexOf('/')+1).replace('.html','');
    //get page name without html
	schmapplet.pageTemplate = pageName.substr(0,4);
	var pageTid=pageName.substr(pageName.length-1);
	schmapplet.pageTid = pageTid;
     if(!initialized ) {
         var hashp = getHashParams();
         schmapplet.colorset = null;
        colorset = hashp.c || "";
        if (colorset.length < 1 || colorset.toLowerCase() == 'none') {
            colorset = 'f6f6f6A72122A62122A62122FFF88FFAF5BBffffffFFF88Fd8d8d8A4A7A6A621226990ffECEBBD0000005C5A4E5C5A4E000000929292F0EFDA';
        }    
           changingColor(colorset);

    } 
	if(settings['SuppressAutopan'] =='true'){
	schmapplet.noAutoPan = true;
	}
	if(typeof(xparams) != 'undefined'){
    	if(typeof(xparams.zoomLinkOverride) != 'undefined'
			&& xparams.zoomLinkOverride != '') {
	    	var zoomLinkOver = xparams.zoomLinkOverride.split('|');
		    if(zoomLinkOver.length==2){
			    zoomlinkUrl = zoomLinkOver[1];
			    zoomLinkOver = zoomLinkOver[0];
			    settings['ZoomText'] = zoomLinkOver;
			    settings['ZoomOutText'] = zoomLinkOver;
			    schmapplet.zoomLinkOver = zoomlinkUrl;
	        }
	    }
		if(typeof(xparams.MapLink) != 'undefined'
			&& xparams.MapLink != '') {
			settings.MapLink = xparams.MapLink;
		}
		if(typeof(xparams.MapLink) != 'undefined'
			&& xparams.SubTitleLink != '') {
			settings.SubTitleLink = xparams.SubTitleLink;
		}	
		if(typeof(xparams.GameVenueLink) != 'undefined'
			&& xparams.GameVenueLink != '') {
			settings.GameVenueLink = xparams.GameVenueLink;
		}
		if(typeof(xparams.TitleLink) != 'undefined'
			&& xparams.TitleLink != '') {
			settings.TitleLink = xparams.TitleLink;
		}
	}
    isPhotoView = false;
    schmapplet.selectedPhoto = 0;
    var obt = $('optionalBottomText');
    if(obt) {
        $('canvas').style.bottom = obt.getAttribute('height') + 'px';
    }
    if(pageName.substr(0,1) == 's') {
       schmapplet.usingSTemplate = 1; 
       var spanWidth = $('canvas').clientWidth + 2;
    }

	schmapplet.advertH = 0;
	if($('optionalBottomText')) {
		 schmapplet.advertH = $('optionalBottomText').getAttribute('height');
       }
	schmapplet.tabLinkOrder = 0;
	photoTabSN = -1;

    // this helps development and debugging
    if(window.top === window)
        setElementDimensions('canvas', {w: 198, h: 378});

    if(typeof(schmapplet.ultranarrow) != 'undefined'
       && schmapplet.ultranarrow.toLowerCase() == 'true') {
        $('details').style.left = '1px';
        $('place-name-top').style.left = '1px';
        $('subtitle-ie').style.left = '1px';
        $('subtitle-div').style.left = '2px';
        $('view-panel').style.left = '2px';
        $('place-info').style.left = '2px';
        $('whatsthis').style.left = '1px';
        $('map').style.left = '2px';
        $('map2').style.left = '2px';
        $('photos').style.left = '1px';
        $('GetSchmappletText').style.left = '1px';
        $('guide-hotswap-div').style.left = '1px';
        $('section-hotswap-div').style.left = '1px';
		$('copyright-hotswap-div').style.left = '1px';
        $('schedule').style.left = '2px';
        $('stats').style.left = '2px';
        $('stats').style.right = '2px';
        $('details').style.right = '1px';
        $('place-name-top').style.right = '1px';
        $('subtitle-div').style.right = '1px';
        $('view-panel').style.right = '2px';
        $('place-info').style.right = '2px';
        $('map').style.right = '2px';
        $('map2').style.right = '2px';
        $('photos').style.right = '1px';
        $('GetSchmappletText').style.right = '1px';
        $('schedule').style.right = '2px';
    }

    getPlaceInfoStyle('TitleInPlaceStrip');
    getPlaceInfoStyle('ShortDescInPlaceStrip');
    getPlaceInfoStyle('AddrLine1InPlaceStrip');
    getPlaceInfoStyle('PhoneNoInPlaceStrip');
    getPlaceInfoStyle('urlInPlaceStrip');

    if (typeof(settings.isGuideSchmapplet) != "undefined"
               && settings.isGuideSchmapplet.match(/^true$/i)) {
        $('subtitle-div').style.visibility = "visible";
        $('subtitle-ie').style.visibility = "visible";
        var newtop = 38;
        setStyle('map', {'top': newtop + 'px'});
        setStyle('map2', {'top': newtop + 'px'});
        setStyle('schedule', {'top': newtop + 'px'});
        setStyle('stats', {'top': newtop + 'px'});
        setStyle('place-name-top', {'top': newtop + 'px'});
		newtop = newtop + 23;
        setStyle('details', {'top': newtop + 'px'});
        setStyle('photos', {'top': newtop - 23 + 'px'});
        var newheight = document.body.clientHeight - 129 - newtop;
        newheight = document.body.clientHeight - 124 - newtop;
        
        if (!initialized) {
			disconnect('print-p', 'onclick', printPlace);
			if (isIE6) { 
			connect('zoom-p', 'onmouseover', showUnderline);
			connect('zoom-p', 'onmouseout', hideUnderline);
			}
        }
         $('title-button-span').innerHTML = '';
         $('subtitle-button-span').innerHTML = '';
        isGuideSchmapplet = true;
    } else if(typeof(settings.Logo)!='undefined'
               && settings.Logo.length > 0) {
        var mainTitleLogo = PNG({width: 122, height: 22, 'src': settings.Logo});
       
       	$('title-link').removeChild($('title-link').lastChild);
    	$('title-link').appendChild(mainTitleLogo);
        hideElement('title');
        $('title-link').style.padding = '0px';
		if(typeof(settings.DisableTitleLinks) == 'undefined'
                || settings.DisableTitleLinks == 'false' || settings['TitleLink'] == 'true') {
            disconnect(mainTitleLogo, 'onclick', mainTitlGo);
            connect(mainTitleLogo, 'onclick', mainTitlGo);
        } else {
            disconnect($('title-link').lastChild,'onmouseover',hideUnderline);
            connect($('title-link').lastChild,'onmouseover',hideUnderline);
        } 
        $('subtitle-div').style.visibility = "visible";
        $('subtitle-ie').style.visibility = "visible";
        var newtop = 38;
        setStyle('map', {'top': newtop + 'px'});
        setStyle('map2', {'top': newtop + 'px'});
        setStyle('schedule', {'top': newtop + 'px'});
        setStyle('stats', {'top': newtop + 'px'});
        setStyle('place-name-top', {'top': newtop + 'px'});
        newtop = newtop + $('place-name-top').clientHeight;
        setStyle('details', {'top': newtop + 'px'});
        setStyle('photos', {'top': newtop - 22 + 'px'});

        var newheight = document.body.clientHeight - 129 - newtop;
        newheight = document.body.clientHeight - 124 - newtop;
        isGuideSchmapplet = true;
    } else  {
        isGuideSchmapplet = false;
    }

    if (typeof(settings.OnePlaceOnly) != "undefined"
            && settings.OnePlaceOnly.match(/^true$/i)) {
        hideElement('play-button');
		hideElement('stop-button');
		hideElement('pause-button');
		hideElement('prev-button');
		hideElement('next-button');
		hideElement('counter');
	} else if ((typeof(settings.ShowAllPlayButtons) != "undefined"
            && settings.ShowAllPlayButtons.match(/^false$/i))) {
        hideElement('play-button');
		hideElement('stop-button');
		hideElement('pause-button');
    } else if (typeof(settings.ShowAllPlayButtons) != "undefined"
            && settings.ShowAllPlayButtons.match(/^true$/i)){
        settings['playf'] = PNG({src:settings.PlayFlash,width:16,height:13});
	    settings['playb'] = PNG({src:settings.Play,width:16,height:13});
		$('play-button').innerHTML = '';
		$('pause-button').innerHTML = '';
		$('stop-button').innerHTML = '';
		$('next-button').innerHTML = '';
        appendChildNodes('play-button',
                settings.playb,settings.playf);
        hideElement(settings.playf);
        appendChildNodes('pause-button',
                PNG({id:'stopbutton',src:settings.Stop,width:13,height:13}));
        appendChildNodes('stop-button',
                PNG({src:settings.Pause,width:13,height:13}));
        appendChildNodes('prev-button',
                PNG({src:settings.Back,width:13,height:13}));
        appendChildNodes('next-button',
                PNG({src:settings.Forward,width:13,height:13}));
		 if (!initialized) {
        disconnect('prev-button', 'onclick', prevPlace);
        analyticsConnect ('prev-button', 'onclick', prevPlace, analyticsHooks.back);
        disconnect('next-button', 'onclick', nextPlace);
        analyticsConnect ('next-button', 'onclick', nextPlace, analyticsHooks.forward);
        disconnect('play-button', 'onclick', startPlay);
        connect('play-button', 'onclick', startPlay);
        disconnect('pause-button', 'onclick', stopPlay);
        connect('pause-button', 'onclick', stopPlay);
        disconnect('stop-button', 'onclick', pausePlay);
        connect('stop-button', 'onclick', pausePlayClick);
		 }
    }

    if(templateChanged && schmapplet.copyrightPanel 
	   && schmapplet.copyrightPanel.length > 20 ){
		$('copyright-hotswap-div').innerHTML = schmapplet.copyrightPanel;
    }

    if(isIE6){
        unbreakIE();
        unbreakIERun = 1;
        disconnect(window, 'onresize', unbreakIE);
        connect(window, 'onresize', unbreakIE);
    } else {
        disconnect(window, 'onresize', repositionPlaceStrip);
        connect(window, 'onresize', repositionPlaceStrip);
    }

    if (typeof(settings.Footer)!='undefined' && settings.Footer.match(/^t:/)) {
        var links = $('logo-url');
        links.innerHTML = settings.Footer.replace(/^t:/, '');
	} else {
    	if (typeof(settings.Footer)!='undefined' && settings.Footer.match(/^i:/)) {
	        settings.LogoBottom = settings.Footer.replace(/^i:/, '');
	    }
		$('whatsthis').innerHTML= '';
        if(!isIE6) {
            settings['logo'] = IMG({id:'logo',src: settings.LogoBottom});
			
            appendChildNodes($('whatsthis'), settings.logo);
            $('logo').height = 12;
        } else {
            settings['logot'] = PNG({id:'logo',src: settings.LogoBottom,width:67,height:12});
            $('whatsthis').innerHTML = '';
            appendChildNodes($('whatsthis'),settings.logot);
        }
    }


    map(function(el) {connect(el, 'onmouseover', autoPauseEx);},
       ['map','map2','view-panel', 'details', 'photos', 'place-info', 'schedule','stats']);
    map(function(el) {connect(el, 'onmouseout', autoPlayEx);},
       ['map','map2','view-panel', 'details', 'photos', 'place-info', 'schedule','stats']);
    if(settings.Play.toLowerCase()=='null'){
        hideElement('play-button')
            }
    if(settings.Pause.toLowerCase()=='null'){
        hideElement('stop-button');
    }
    if(settings.Stop.toLowerCase()=='null'){
        hideElement('pause-button');
    }
    if ((typeof(schmapplet.usingSTemplate) != 'undefined')
            && schmapplet.usingSTemplate == 1) {    //1
        if (zoomLevel > 0) {      //2
            $('zoom-p').innerHTML = settings.ZoomText;
            $('zoom-p').style.visibility = "hidden";
            if (schmapplet.usingSTemplate == 1) {
                $('zoom-p').style.fontSize = '10px';
            }
            $('zoom-p').style.fontSize = '9px';
            var offset = '-28px';
            removeElementClass('zoom-p', 'zoom-p');

            addElementClass('zoom-p', 'zoom-p-sports');

            var offset = '16px';
            var relativeZoomPos = false;
            if (settings['ZoomToStadiumOffset']) {
                if (settings['ZoomToStadiumOffset'] == 'relative')
                {
                    relativeZoomPos = true;
                } else {
                    offset = Number(settings['ZoomToStadiumOffset']);
                    offset = offset.toString() + 'px';
                }
            }
            var spanWidth = $('place-info').clientWidth + 'px';
            if (relativeZoomPos){
                setStyle('zoom-p', {'position':'absolute','margin-top':'5px','visibility':'hidden',width:spanWidth});
            } else {
                setStyle('zoom-p', {'position':'absolute','bottom':offset,left:'4px','visibility':'hidden',width:spanWidth});
            }
            
            // Allow optional centering of the zoom in text based on 'CenterZoomLink' template parameter
            if (settings.CenterZoomLink != 'undefined' && settings.CenterZoomLink == 'true')
            {
                addElementClass('zoom-p','alignCenter');
            }
            
            disconnect('zoom-p', 'onclick', zoomInOut);
            analyticsConnect ('zoom-p', 'onclick', zoomInOut, analyticsHooks.textZoom);
        }      //2  over
        disconnect('print-p', 'onclick', printPlace);
        setStyle('print-p', {'cursor':'default'});
        setStyle('directions-p', {'cursor':'default'});
    } else {       // match 1
        if (settings.UseFunctionIcons !== "undefined"
                && settings.UseFunctionIcons.match(/^true$/i)) {
            settings['printb'] = PNG({id:'print-button',title:'Print'
                ,src:settings.Print,width:13,height:12});
            setStyle('print-p', {'left': '0px'});
            $('print-p').innerHTML = '';
            appendChildNodes('print-p', settings.printb);

            settings['directionsb'] = PNG({id:'directions-button',title:'Get directions',
                src:settings.Directions,width:13,height:12});
            settings['zoomout'] = PNG({id:'zoom-out-button',title:'Zoom out',
                src:settings.ZoomOut,width:13,height:12});
            settings['zoomin'] = PNG({id:'zoom-in-button',title:'Zoom in',
                src:settings.ZoomIn,width:13,height:12});

            if (typeof(settings.HasDriverDirection) != 'undefined'
                    && settings.HasDriverDirection == 'no') {
                hideElement('directions-p');
                setStyle('zoom-p', {'left': 16 + 'px'});
            } else {
                $('directions-p').innerHTML = '';
                appendChildNodes('directions-p', settings.directionsb);
                setStyle('directions-p', {'left': 16 + 3 + 'px'});
                setStyle('zoom-p', {'left': 16 + 16 + 6 + 'px'});
                disconnect('directions-p', 'onclick', showDriveDirections);
                connect('directions-p', 'onclick', showDriveDirections);
            }
            if (zoomLevel > 0) {
                $('zoom-p').innerHTML = '';
                appendChildNodes('zoom-p', settings.zoomout, settings.zoomin);
                hideElement(settings.zoomout);
            }
        } else {
            $('print-p').innerHTML = "print";
            setStyle('print-p', {'left': '0px'});
            if (zoomLevel > 0) {
               $('zoom-p').innerHTML = "zoom in";
            }
            if (typeof(settings.HasDriverDirection) != 'undefined'
                    && settings.HasDriverDirection == 'no') {
                hideElement('directions-p');
                setStyle('zoom-p', {'left': 16 + 'px'});
            } else {
                setStyle('directions-p', {'left': 16 + 6 + 'px'});
                $('directions-p').innerHTML = "Get directions";
                setStyle('zoom-p', {'left': 16 + 16 + 12 + 'px'});
                disconnect('directions-p', 'onclick', showDriveDirections);
                connect('directions-p', 'onclick', showDriveDirections);
            }
        }
        connect('print-p', 'onclick', printPlace);
         if (zoomLevel > 0) {
            analyticsConnect ('zoom-p', 'onclick', zoomInOut, analyticsHooks.textZoom);
        } else {
           hideElement('zoom-p');   
       }
    }

	if (typeof(settings.FooterType) != 'undefined'
            && settings.FooterType.match(/panel/i)) {
		disconnect('whatsthis','onmouseover',showSchmappletTextPanel);
		disconnect('whatsthis','onmouseout',hideSchmappletTextPanel);
		disconnect('GetSchmappletText','onmouseout',hideSchmappletTextPanel);
        disconnect('code', 'onclick', clickselect);
        analyticsConnect ('whatsthis', 'onmouseover', showSchmappletTextPanel, analyticsHooks.getThisWidget);
		connect('whatsthis','onmouseout',hideSchmappletTextPanel);
		connect('GetSchmappletText','onmouseout',hideSchmappletTextPanel);
		connect('canvas','onmouseout',hideSchmappletTextPanel);
        analyticsConnect ('code', 'onclick', clickselect, analyticsHooks.copyCodeLeft);
	}
	updateParentIframeCode();
    if (typeof(schmapplet.placeid) == "undefined") {
    	schmapplet.placeid = PlaceId;
        initPlaceId = schmapplet.placeid;
	}
    if (typeof(schmapplet.autoplay) == 'undefined') {
        schmapplet.autoplay = settings.Autoplay;
        schmapplet.autoplay = Boolean(Number(schmapplet.autoplay));
    }

    if (typeof(schmapplet.delayTime) == "undefined") {
    	schmapplet.delayTime = settings.Delay;
	}
    schmapplet.cycleTime = (schmapplet.delayTime / flashTime) / 1000;
	loadPlacesInfo();
	
    var belowText = getElementsByTagAndClassName('a', 'MyText');
    var length = belowText.length;
    if (length == 1) {
        analyticsConnect (belowText[0], 'onclick', function(){}, analyticsHooks.belowTextClick);
        analyticsConnect (belowText[0], 'onmouseover', function(){}, analyticsHooks.belowTextOver);
    }
}

function clickselect(){
	this.select();
}

function loadPlacesInfo() {

	window.debugrunner = settings;
    if (!settings.PlacesXmlName) {
	    settings.PlacesXmlName = 'places.xml';
    }

    if (!schmapplet.isiGoogle){
        if(schmapplet.lang&&schmapplet.lang!==""){
		if(schmapplet.lang!=='en'){
		settings.PlacesXmlName = settings.PlacesXmlName.replace('.xml','') + "_" + schmapplet.lang + '.xml';
		}
	}else{
    settings.PlacesXmlName += config.get("negotiateSuffix");
	}
    }
    var placePath = settings.SchmappletHome.replace('%uid%',schmapplet.uid);
    placePath = placePath.replace('%sid%',schmapplet.sid);
    var url = placePath + '/'+settings.PlacesXmlName
    xmlLoad(url, handlePlaces);
}

function handlePlaces(req) {
    logTime('Framework created ... starting loading places');      
    var xml = req.responseXML;
    schmapplet.placesInfo = new XmlDoc(xml);
	loadPlaces();
}

function getExceptionInfo(xml) {
    // Parsing the exception.xml and get info from it and put into the global
    // it's really not correct to place them in the global, we have to push them
    // into the exceptions Object later.
	var xmlAccess = new XMLAccess();
	xmlAccess.setXmlDoc(xml);
    var root, mapIconsDir, iconFileNodes, pageParamsNode,showButton,isGuide;
    root = xmlAccess.getFirstChild(xml, '/schmap:SchmappletParams');
    mapIconsDir = xmlAccess.getSingleChildText(root, 'schmap:MapIconsDir');
    if(typeof(mapIconsDir) != "undefined" && mapIconsDir != "") {
        mapiconspath = mapIconsDir;
    }
    //logDebug("mapiconspath:" + mapiconspath);

    iconFileNodes = xmlAccess.getChildren(root, 'schmap:IconFile');
    forEach(iconFileNodes, function (node) {
        var code = xmlAccess.getSingleChildText(node, 'schmap:code');
        var url = xmlAccess.getSingleChildText(node, 'schmap:url');
        if(url != 'null' && url.length > 0) {
          settings[code] = url;
        }
        });
    showButton = xmlAccess.getSingleChildText(root, 'schmap:ShowAllPlayButtons');
    isGuide = xmlAccess.getSingleChildText(root, 'schmap:isGuideSchmapplet');

    if(typeof(showButton)!='undefined'&& showButton.length > 0) {
        settings.ShowAllPlayButtons = showButton;
    }
    if(typeof(isGuide)!='undefined' && isGuide.length > 0) {
        settings.isGuideSchmapplet = isGuide;
    }
    pageParamsNode = xmlAccess.getFirstChild(root, 'schmap:PageParams');
    if(pageParamsNode) {
        var pageParamsElems = xmlAccess.getSons(pageParamsNode, './*');
        forEach(pageParamsElems, function(node) {
            var name = node.nodeName;
            name = name.split(':')[1];
            if(name == "dlparameter") {
                 //logDebug("exceptions.dlparameter:" + exceptions.dlparameter);
                 //var value = xmlAccess.getCData(node);
                 //exceptions.dlparameter = value;

                var value = xmlAccess.getText(node);
            	var segments = value.match(/topleft=(.[^&#]+)[&]{0,}/i);
            	if (segments) {
            		topleft = segments[1];
            	}
            	segments = value.match(/bottomright=(.[^&#]+)[&]{0,}/i);
            	if (segments) {
            		bottomright = segments[1];
            	}
            } else if (name == "PlacesXmlName") {
                // don't allow override
            } else {
                 var value = xmlAccess.getText(node);
                 settings[name] = value;
            }
            //logDebug("name:" + name + ",value:" + value);
        });

    }
	
    setupWidget();
}

function getInfoFromMetaParams() {
    var pairs = {};
	var nodes = document.getElementsByTagName('meta');
    var nodesLen = nodes.length ;
    for(var i=0; i < nodesLen; i++) {
        var node = nodes[i];
        if(node.name) 
            schmapplet[node.name] = node.content;
		pairs[node.name] = node.content;
    }
    return pairs;
}

function getParamsFromXml() {
    var ti = template.ident;
	if(!schmapplet.isiGoogle && schmapplet.lang){
		var lang = '&lang='+schmapplet.lang;
	}else{
		var lang = '';
	}
    var url = "/templates/params/including.html?doc=xml&tpl=" + ti + ".html" + lang;
	logDebug(url);
	var xml = xmlSyncLoad(url);
    var nodes = xml.childNodes;
    var result = {};
    forEach(nodes, function(node) {
        if(node.nodeName != "meta") return;
        var name = node.getAttribute("name");
        //var httpEquiv = node.getAttribute("http-equiv")

        if(!name) return;
        if(name == 'getWidgetPanel'){
            schmapplet.getWidgetPanel = xmlAccess.getText(node);
        }
		if(name == 'copyrightPanel'){
            schmapplet.copyrightPanel = xmlAccess.getText(node);
        }
        var content = node.getAttribute("content");
        result[name] = content;
    });
    return result;
}

function changeTemplate(tcode) {
    logDebug("change template");
    if(tcode == template.ident) {
        return;
    }
    templateChanged = 1;
    template.ident = tcode;
    logDebug("new template identifier:" + tcode);
    exception();
}
function isNotUndefOrNull(refer){
	if(typeof(refer)!="undefined" && refer!=null && refer!="")return true;
	return false;
}

function ifRemoveFutherGames(){
    if(typeof(settings.RemoveFutureSchedule)!="undefined"){
        var content = settings.RemoveFutureSchedule;
        var uids = content.split(",");
        var len = uids.length;
        for(var i=0;i<len;i++){
            if(typeof(schmapplet.uid)!='undefined' && schmapplet.uid==uids[i])
                return true;
        }
        return false;
    }
    return false;
}

/* if this uid exists in the content list of a <meta> which name is RemoveFutureSchedule,
 * use htmltitleForResultView's content instead of htmltitle's content,and store old htmltitle in
 * settings.oldHtmlTitle for reuse .
 * */

function exception(){
	settings = {};
    if(templateChanged) {
        update(settings, getParamsFromXml()); 
    } else {
        update(settings, getInfoFromMetaParams()); 
    }
    nodes = document.getElementsByTagName('link');
    var nodesLen = nodes.length ;
    for(var i=0; i < nodesLen; i++) {
        var node = nodes[i];
        if(node.rel)
            schmapplet[node.rel] = node;
        if (node.rel == "FooterLink")
    		settings[node.rel] = node.href;        
    }
    if(trackPage){
	    if (typeof(settings.TrackPage) !='undefined'
		    && settings.TrackPage.length > 0){
			trackPage = settings.TrackPage;
		} else {
		    trackPage = false;
		}
	}
    
    mapiconspath = settings.MapIconsDir;
	pageiconpath = settings.IconsDir;
	logDebug('mapiconspath   ',mapiconspath);
   
	var pageiconnames = ["Play","PlayFlash","Pause","Stop","Back","Forward",
            "LogoBottom","CC","DefaultPlace","ZoomOut","ZoomIn","Print",
            "Directions"];
	var pageiconvalue = ["play.png","play-flash.png","pause.png","stop.png",
            "prev.png","next.png","logo.png","cc.png","defaultplace.png",
            "zoom-out.png","zoom-in.png","print.png","car.png"];
	var pageLen = pageiconnames.length ;
    for(ii=0;ii<pageLen;ii++) {
        var name = pageiconnames[ii];
        var value = pageiconvalue[ii];
        var pcn = name;
	    var pcv = value;
	    settings[pcn] = pageiconpath + pcv;
	}
    if(showMenusFromUrl == null) {
        if(typeof(settings.ShowMenus) != 'undefined') {
            showMenusFromMeta = settings.ShowMenus;
            for (var i = 0; i < showMenusFromMeta.length; i++) {
                showTwoMenus[i] = showMenusFromMeta.charAt(i);
            }
        } else {
           showTwoMenus = [1,1] ;
        }

    }
    if(typeof(xparams) != 'undefined'
                &&  typeof(xparams.zoomLevel) != 'undefined'
                && xparams.zoomLevel != '') {
         zoomLevel = xparams.zoomLevel;
    } else {
         zoomLevel = Math.round(settings.ZoomLevel);
    }
    if(typeof(schmapplet.usingSTemplate) != 'undefined'
            && !schmapplet.usingSTemplate) {
        var xmlHttp;
        var xmlname = settings.SchmappletHome.replace('%uid%', schmapplet.uid);
        xmlname = xmlname.replace('%sid%', schmapplet.sid);
        xmlname += '/' + schmapplet.TemplateCode + 'exceptions.xml';

        try {   // Firefox, Opera 8.0+, Safari
            xmlHttp = new XMLHttpRequest();
        } catch(e) {  // Internet Explorer
            try {
                xmlHttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
            } catch(e) {
                try {
                    xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    logDebug("Your browser does not support AJAX!");
                }
            }
        }
        xmlHttp.open("GET", xmlname + "?rnd=" + Math.random(), false);
        xmlHttp.send(null);
        if (xmlHttp.status == 200) {  // 200 request is successful
            getExceptionInfo(xmlHttp.responseXML);
        } else {
           tabs = [];
           setupWidget();
        }
    } else {
		tabs = [];
        setupWidget();
    }
}


function beforSetup(){

	if(typeof(needGoogle)!=="undefined"){
		schmapplet.needGoogle = needGoogle;
	}
    if (!schmapplet.mapIcons)
    {
        schmapplet.mapIcons = {};
        schmapplet._loading = true;
        schmapplet.selected = 0;
        schmapplet.view = 'map';
        schmapplet.IEquirks = (b_version.search(/MSIE/i) != -1);
        schmapplet.cycleTime = 6;
        schmapplet.placesById = {};
        schmapplet._placesCount = 0;
    }
    
     if (beforSetupCalled) {
          return;
     } else {
          beforSetupCalled = true;
     }
	schmapplet.placeidUrl = '';
    var searchp = getSearchParams();

    // iGoogle hack
    if ( (searchp.parent && searchp.parent.match(/google/i)) || searchp['.lang'] ) {
        schmapplet.isiGoogle = true; 
    } else {
        schmapplet.isiGoogle = false; 
    }

    schmapplet.sid = searchp.sid;
    schmapplet.uid = searchp.uid;
	schmapplet.oldUid = schmapplet.uid;
	schmapplet.oldSid = schmapplet.sid;
	schmapplet.ultranarrow = searchp.ultranarrow;
    schmapplet.si = searchp.si;
	schmapplet.lang = searchp.lang;
    if (!schmapplet.si)
    {
        schmapplet.si = searchp.sit;
    }
    
	var hashp = getHashParams();
    schmapplet.mapview = hashp.mapview;
    schmapplet.applyColors = hashp.applycolors;
    if (typeof(schmapplet.mapview) == "undefined"
        || schmapplet.mapview.length <= 0) {
	   schmapplet.mapview = 'Map';
	}
	schmapplet.tabLink = hashp.tab;
    if(typeof(hashp.subtitle) != 'undefined') {
       schmapplet.subtitle = hashp.subtitle ;
    }
    if(hashp.topleft!=''){
       schmapplet.topleft = hashp.topleft;
       schmapplet.bottomright = hashp.bottomright;
    } else {
        schmapplet.topleft = null;
        schmapplet.bottomright = null;
    }
    if(hashp.placeid) {
       schmapplet.placeid = hashp.placeid;
       fixedPlace = hashp.placeid ;
    }
    schmapplet.placeid = hashp.placeid;
    initPlaceId = schmapplet.placeid;
    schmapplet.autoplay = hashp.autoplay;
    if(typeof(hashp.autoplay) != 'undefined') {
        schmapplet.autoplay = Boolean(hashp.autoplay);
        autoplayUrl = schmapplet.autoplay;
    }
    schmapplet.delayTime = hashp.delay;
    if(typeof(hashp.showMenus) != 'undefined') {
        showMenusFromUrl = hashp.showMenus;
        for(var i = 0;i < showMenusFromUrl.length;i++) {
           showTwoMenus[i] = showMenusFromUrl.charAt(i);
        }
    } 

    if (hashp.uplace) {
        if (hashp.uplaceonly) {    
            schmapplet.uplaceonly = hashp.uplaceonly;
            isPlaceOnly = true;
        }
        schmapplet.uplace = createUserPlace(hashp.uplace);
        schmapplet.places = [];
        schmapplet.places[0] = schmapplet.uplace;
    }
    schmapplet.isPolled = hashp.isPolled;
    var url = document.location.href;
	var m = url.match(/http:\/\/(.+?)\//i);
    schmapplet.url_prefix = m[0];
    overwriteXparams();
    

    if(typeof(xparams) != 'undefined'
            && typeof(xparams.permanentLogo) != 'undefined') {
        schmapplet.permanentLogo = xparams.permanentLogo;
		if(typeof(schmapplet.mapLogo) != 'undefined'
		  && schmapplet.mapLogo != null) {
			var temObj2 = {};
	        temObj2.mapLogo = schmapplet.mapLogo;
	        temObj2.logoLink = schmapplet.logoLink;
	        mapLogo.push(temObj2);
		}
        var temObj1 = {};
        if (xparams.mapLogo != '')
        {
            temObj1.mapLogo = xparams.mapLogo;
            temObj1.logoLink = xparams.logoLink;
            mapLogo.push(temObj1);
        }
    } else {
       schmapplet.permanentLogo = false;
    }
    
    if(typeof(schmapdata_ov)!=='undefined'){
		schmapdata = schmapdata_ov;
	}
   try{
         if(typeof(schmapplet.isPolled) != 'undefined'
            && schmapplet.isPolled == 1) {
            var interval = setInterval("checkArgs()", 10);
         }
    } catch(e) {}
   
	exception();
	//logDebug("finish exception()");

}
function showUnderline(){
	 setStyle(this, {'text-decoration': 'underline','cursor': 'pointer'});
}

function hideUnderline(){
     setStyle(this, {'text-decoration': 'none','cursor':'default'});
}
connect(window, 'onload', beforSetup);
connect(window, 'onunload', uninstall);

function cancelDelay(evt){
    if(mouseIntoInfoPanelFromTop(evt, this)) {
        return;
    }
   if (schmapplet.delay){//logDebug(434343);
   schmapplet.delay.cancel();
    schmapplet.delay = null;
   }
}

function mouseIntoInfoPanelFromTop(evt, obj) {
    var mx = evt.mouse().client.x;
    var my = evt.mouse().client.y;
    var pos = getElementPosition(obj);
    var dim = getElementDimensions(obj);
    //logDebug("small y:", pos.y, "my:", my, "big y:", pos.y + dim.h, "small x:", pos.x, "mx:", mx, "big x:", pos.x + dim.w);
    //logDebug("evt type:" + evt.type + ",obj.id:" + obj.id + ",small y:"+ pos.y+ ",my:"+ my+ ",big y:"+ pos.y + dim.h+ ",small x:"+ pos.x + ",mx:"+ mx+ ",big x:"+ pos.x + dim.w);
    //if(34 < mx && 152 > mx && 18 < my) {
    if (schmapplet.IEquirks) {
        pos.y += 2;
        pos.x += 2;
    }
    //logDebug("mymymy"+my);
    if (isSafari) {
        my += 14;
    }

    if (mx == 0 || my == 0) return true;
    if (pos.x < mx && (pos.x + dim.w) > mx && pos.y < my && (pos.y + dim.h) > my) {
        ////logDebug("mouse in " + id);
        return true;
    }
    return false;
}
function truncated(str, num, lat) {
  //str=str.toString();
  if(typeof(str) != "string") return "";
  if(!str) return "";
  if(!lat) lat = '...';
  var result = str.substring(0, num);

  if(str.length > num) {
    result += lat;
  }
  return result;
}
function truncatWidth(str, num, lat) {
    str = str.toString();
    if (!str) return "";
    if (!lat) lat = '...';

    var sp = SPAN({'class':'aaa'});
    setStyle(sp, {'visibility':'hidden', 'position': 'absolute','z-index':'-50'});
    appendChildNodes(document.body, sp);
    var strLen = str.length ;
    for (i = i; i < strLen; i++) {
        var result = str.substring(0, i);
        sp.innerHTML = result;
        if (sp.offsetWidth >= num) {
            break;
        }
    }
result = truncated(str,i--);
  return result;
}

function centerMaps() {
	schmapplet.map.zoomToBounds(schmapplet.bounds);
	updateParentIframeCode();
}

function keepCenter(resize){
	if(!schmapplet.map)return;
	schmapplet.mapResized = true;
    if(schmapplet.selected!==undefined&&schmapplet.places[schmapplet.selected]){
         if(schmapplet.places[schmapplet.selected].zoomedIn){
            var place = schmapplet.places[schmapplet.selected];
            zoomLevel = Math.abs(zoomLevel);
            schmapplet.map.setDisplay(place.geocode,settings.ZoomLevel);
            return;
          }
	}
    centerMaps();
}

function dragStart(){
		if (BrowserDetect.browser == 'Explorer') {
	document.attachEvent("onmousemove", parent.dragTo);
 //   document.attachEvent("onmouseup", top.endDrag);
  }else {
    document.addEventListener("mousemove", parent.dragTo,   true);
  }

	}

function adjustMapHeigtforIE() {
     if(isIE6){
         h = getElementDimensions('canvas').h -160 + 12;
         if (isGuideSchmapplet) {
             h-=14;
         }
         $('map').style.height=h + 'px';
         $('map2').style.height=h + 'px';
     }
}

function unbreakIE(){
	try{ // it is necessary
	var bodyWidth = document.body.clientWidth;
	var bodyHeight = document.body.clientHeight;
	var subtitleHeight = $('subtitle-div').clientHeight;
        var obt = $('optionalBottomText');
        if(obt) {
            bodyHeight -= Number(obt.getAttribute('height'));
        }
	setStyle('canvas',{'width': (bodyWidth- 2) + 'px','height':(bodyHeight - 2) + 'px'});
	setStyle('codetext',{'width': (bodyWidth- 16) + 'px'});
	setStyle('detail-url',{'width': (bodyWidth- 36) + 'px'});
    setStyle('photo-table', {'height': '100%'});
	setStyle('photo-button',{'width': (bodyWidth- 22) + 'px'});
  	if (isGuideSchmapplet) {
            if (typeof(schmapplet.ultranarrow) != 'undefined' 
                    && schmapplet.ultranarrow.toLowerCase() == 'true') {
                setStyle('details', {'width': (bodyWidth - 16) + 'px','height':(bodyHeight - 178 - subtitleHeight) + 'px'});
                setStyle('place-name-top', {'width': (bodyWidth - 16) + 'px'});
                setStyle('view-panel', {'width': (bodyWidth - 12) + 'px'});
                setStyle('place-info', {'width': (bodyWidth - 10) + 'px'});
                setStyle('map', {'width': (bodyWidth - 6) + 'px','height':(bodyHeight - 162) + 'px'});
                setStyle('map2', {'width': (bodyWidth - 6) + 'px','height':(bodyHeight - 160) + 'px'});
                setStyle('photos', {'width': (bodyWidth - 6) + 'px','height':(bodyHeight - 160) + 'px'});
                setStyle('subtitle-div', {'width': (bodyWidth - 6) + 'px'});
                map(function(el) {
                    setStyle(el, {'width': bodyWidth - 6 + 'px'})
                }, ['guide-hotswap-frame','section-hotswap-frame','article-frame']);
                setStyle('subtitle-ie', {'width': (bodyWidth - 6) + 'px'});
                setStyle('schedule', {'width': (bodyWidth - 6) + 'px','height':(bodyHeight - 160 + 85) + 'px'});
		        setStyle('stats', {'width': (bodyWidth - 6) + 'px','height':(bodyHeight - 160 + 85) + 'px'});
                setStyle('GetSchmappletText', {'width': (bodyWidth - 16) + 'px','height':(bodyHeight - 51) + 'px'});
                setStyle('guide-hotswap-div', {'width': (bodyWidth - 16) + 'px','height':(bodyHeight - 66) + 'px'});
                setStyle('section-hotswap-div', {'width': (bodyWidth - 16) + 'px','height':(bodyHeight - 66) + 'px'});
                setStyle('copyright-hotswap-div', {'width': (bodyWidth - 14) + 'px','height':(bodyHeight - 53) + 'px'});
                $('copyright-hotswap-div').style.left ="2px";
            } else {
                setStyle('details', {'width': (bodyWidth - 22) + 'px','height':(bodyHeight - 170) + 'px'});
                setStyle('place-name-top', {'width': (bodyWidth - 22) + 'px'});
                setStyle('view-panel', {'width': (bodyWidth - 11) + 'px'});
                addElementClass('view-panel', 'view-panel-class');
                setStyle('place-info', {'width': (bodyWidth - 16) + 'px'});
                setStyle('map', {'width': (bodyWidth - 12) + 'px','height':(bodyHeight - 146) + 'px'});
                setStyle('map2', {'width': (bodyWidth - 12) + 'px','height':(bodyHeight - 146) + 'px'});
                setStyle('photos', {'width': (bodyWidth - 12) + 'px','height':(bodyHeight - 160 - subtitleHeight + 14) + 'px'});
                setStyle('subtitle-div', {'width': (bodyWidth - 12) + 'px'});
                map(function(el) {
                    setStyle(el, {'width': bodyWidth - 12 + 'px'})
                }, ['guide-hotswap-frame','section-hotswap-frame','article-frame']);
                setStyle('subtitle-ie', {'width': (bodyWidth - 12) + 'px'});
                setStyle('schedule', {'width': (bodyWidth - 14) + 'px','height':(bodyHeight - 143 - subtitleHeight + 85) + 'px'});
		        setStyle('stats', {'width': (bodyWidth - 12) + 'px','height':(bodyHeight - 143 - subtitleHeight + 85) + 'px'});
                setStyle('GetSchmappletText', {'width': (bodyWidth - 22) + 'px','height':(bodyHeight - 65) + 'px'});
                setStyle('guide-hotswap-div', {'width': (bodyWidth - 22) + 'px','height':(bodyHeight - 66) + 'px'});
                setStyle('section-hotswap-div', {'width': (bodyWidth - 22) + 'px','height':(bodyHeight - 66) + 'px'});
		        setStyle('copyright-hotswap-div', {'width': (bodyWidth - 22) + 'px','height':(bodyHeight - 66) + 'px'});

            }
        } else {
            if (typeof(schmapplet.ultranarrow) != 'undefined' && schmapplet.ultranarrow.toLowerCase() == 'true') {
                setStyle('details', {'width': (bodyWidth - 16) + 'px','height':(bodyHeight - 170) + 'px'});
                setStyle('place-name-top', {'width': (bodyWidth - 16) + 'px'});
                setStyle('view-panel', {'width': (bodyWidth - 12) + 'px'});
                addElementClass('view-panel', 'view-panel-class');
                setStyle('place-info', {'width': (bodyWidth - 10) + 'px'});
                setStyle('map', {'width': (bodyWidth - 6) + 'px','height':(bodyHeight - 143+2) + 'px'});
                setStyle('map2', {'width': (bodyWidth - 6) + 'px','height':(bodyHeight - 143) + 'px'});
                setStyle('photos', {'width': (bodyWidth - 6) + 'px','height':(bodyHeight - 144) + 'px'});
                setStyle('schedule', {'width': (bodyWidth - 6) + 'px','height':(bodyHeight - 143 + 85) + 'px'});
		        setStyle('stats', {'width': (bodyWidth - 6) + 'px','height':(bodyHeight - 143 + 85) + 'px'});
                setStyle('GetSchmappletText', {'width': (bodyWidth - 16) + 'px','height':(bodyHeight - 52) + 'px'});
                setStyle('guide-hotswap-div', {'width': (bodyWidth - 16) + 'px','height':(bodyHeight - 66) + 'px'});
                setStyle('section-hotswap-div', {'width': (bodyWidth - 16) + 'px','height':(bodyHeight - 66) + 'px'});
                setStyle('subtitle-div', {'width': (bodyWidth - 6) + 'px'});
		        setStyle('copyright-hotswap-div', {'width': (bodyWidth - 14) + 'px','height':(bodyHeight -54) + 'px'});
                $('copyright-hotswap-div').style.left ="2px";

                map(function(el) {
                    setStyle(el, {'width': bodyWidth - 6 + 'px'})
                }, ['guide-hotswap-frame','section-hotswap-frame','article-frame']);
            } else {
                setStyle('details', {'width': (bodyWidth - 22) + 'px','height':(bodyHeight - 174) + 'px'});
                setStyle('place-name-top', {'width': (bodyWidth - 22) + 'px'});
                setStyle('view-panel', {'width': (bodyWidth - 11) + 'px'});
                addElementClass('view-panel', 'view-panel-class');
                setStyle('place-info', {'width': (bodyWidth - 16) + 'px'});
                setStyle('map', {'width': (bodyWidth - 12) + 'px','height':(bodyHeight - 145) + 'px'});
                setStyle('map2', {'width': (bodyWidth - 12) + 'px','height':(bodyHeight - 146) + 'px'});
                setStyle('photos', {'width': (bodyWidth - 12) + 'px','height':(bodyHeight - 144) + 'px'});
                setStyle('schedule', {'width': (bodyWidth - 12) + 'px','height':(bodyHeight - 143 + 85) + 'px'});
		        setStyle('stats', {'width': (bodyWidth - 12) + 'px','height':(bodyHeight - 143 + 85) + 'px'});
                setStyle('GetSchmappletText', {'width': (bodyWidth - 22) + 'px','height':(bodyHeight - 65) + 'px'});
                setStyle('subtitle-div', {'width': (bodyWidth - 12) + 'px'});
                setStyle('guide-hotswap-div', {'width': (bodyWidth - 22) + 'px','height':(bodyHeight - 65) + 'px'});
                setStyle('section-hotswap-div', {'width': (bodyWidth - 22) + 'px','height':(bodyHeight - 65) + 'px'});
				setStyle('copyright-hotswap-div', {'width': (bodyWidth - 22) + 'px','height':(bodyHeight - 65) + 'px'});

			   map(function(el) {
                    setStyle(el, {'width': bodyWidth - 12 + 'px'})
                }, ['guide-hotswap-frame','section-hotswap-frame','article-frame']);
            }
        }
        
        repositionPlaceStrip();
		if(isStatsView){
		    jugdescroll($('stats'));
		}
    }catch(e){}
}

function subTitlGo(){
    if(settings['SubTitleLink'] == 'true'){
      var url = new StringBuffer();
	  url.append("http://").append(window.location.host).append("/").append(schmapplet.uid).append("/").append(schmapplet.sid);
    var fullSchmapCode = url.toString();
    } else
	var fullSchmapCode = getFullSchmapURL();  
    var urlParam = ''
    if(settings['WidgetLinkPopupWidth'])
    urlParam += 'width=' + settings['WidgetLinkPopupWidth'];
    if(settings['WidgetLinkPopupHeight'])
    urlParam += ', height=' + settings['WidgetLinkPopupHeight'];
    window.open(fullSchmapCode,'',urlParam);
}

function mainTitlGo(){
      var url = new StringBuffer();
	  url.append("http://").append(window.location.host).append("/").append(schmapplet.uid).append("/").append('home/');
    var urlParam = ''
    if(settings['WidgetLinkPopupWidth'])
    urlParam += 'width=' + settings['WidgetLinkPopupWidth'];
    if(settings['WidgetLinkPopupHeight'])
    urlParam += ', height=' + settings['WidgetLinkPopupHeight'];
    window.open(url.toString(), '', urlParam);
}

function fixed(c, n) {   
    with(Math) 
       return round(Number(c)*pow(10,n))/pow(10,n);
}

function mapsUpdate(evt){
    if(isIE7) {
		
        //var dim = getElementDimensions('canvas');
        var left = getStyle('map', 'left');
        var right = getStyle('map', 'right');
        var topv = getStyle('map', 'top');
        setStyle('map', {position: 'absolute', top: topv,
                         bottom: '120px', left: left, right: right});
        setStyle('map2', {position: 'absolute', top: topv,
                         bottom: '120px', left: left, right: right});

        var dim = getElementDimensions('map'); //important
        //setElementDimensions('map', {h: dim.h - 2, w: dim.w - 2});

        var obt = $('optionalBottomText');
        var advertH = 0;
        if(obt) {
            advertH = obt.getAttribute("height");
        }
       try{
         if (typeof(parent.placesChecked) == 'undefined') {
             setElementDimensions('canvas', {h: document.body.clientHeight-2 - advertH,
                 w: document.body.clientWidth-2});
          }
      }catch(e){
			setElementDimensions('canvas', {h: document.body.clientHeight-2 - advertH,
                w: document.body.clientWidth-2});
	 }
    }
    var bounds = schmapplet.map.getBounds();
    var t = fixed(bounds.north, 5);
    var l = fixed(bounds.west, 5);
    var b = fixed(bounds.south, 5);
    var r = fixed(bounds.east, 5);
    Map_object.schmapplet_s = concat([t," ",l," ",b," ",r]);
	//schmapplet.bounds = MochiKit.Maps.Bounds.fromGeoRSS(Map_object.schmapplet_s);
	updateParentIframeCode();
  
}

function changeMapType (mapView){
    schmapplet.map.setMapType(mapView);
	schmapplet.mapview = mapView;
		try{
		if(parent) {
		if(parent.changeIframeCode) {
		    iframeCode = getiFrameSrc();
			parent.changeIframeCode(iframeCode);
		}
	}   
	}catch(e){} 
}

function isphotoComplete(photo){
    if(typeof(photo.complete) == 'Boolean') {
		return photo.complete;
		}else{
			return true;
			}

	}

function loadNewPlaces(place_xml,tcode) {
	schmapplet.photoMade = false;
	logDebug(place_xml);
	if(tcode != template.ident && tcode) {
		templateChanged = 1;
		template.ident = tcode;
		logDebug("new template identifier:" + tcode);
	}else{
		templateChanged = 0;	
	}
	if (!loadingEmptyGuide){
			if($('section-hotswap-frame') != null) {
			$('section-hotswap-frame').style.visibility='hidden';
			$('loading-message-guide').style.visibility = 'visible';
    }
    $('guide-hotswap-div').style.visibility = 'visible';
    if($('guide-hotswap-frame') != null) {
		$('guide-hotswap-frame').style.visibility = 'hidden';
		$('loading-message-guide').style.visibility = 'visible';
     }
	}
	loadingNewSchmapplet = true;
        unbreakIERun = 0;
        ShowMenus = null;
        loadSchmapPlacesFlag = true;
        var urlElemsArr = place_xml.split('/');
        schmapplet.uid = urlElemsArr[1];
        schmapplet.sid = urlElemsArr[2];
        sectionLoaded = 0;
		loadingNewMap = true;
        if (templateChanged) {
	    logDebug("loadNewPlaces is called with guide hostswap");
            try {
                if (parent){
                    if (parent.window.location.pathname.search('addplace.html') == -1)
                    {
                        showMyPlace = false;
                    }
                }
            } catch(e) { }

            if (!loadingEmptyGuide){
                schmapplet.topleft = null;
	            schmapplet.bottomright = null;
	        }
            schmapplet.subtitle = '';
            Map_object.schmapplet_s = null;
            showMenusFromMeta = null;
            exception();
	        loadingEmptyGuide = false;
        } else {
            logDebug("loadNewPlaces is called without guide hotswap");
            loadNewPlace = true;
            schmapplet.topleft = null;
	        schmapplet.bottomright = null;
            schmapplet.subtitle = '';
            Map_object.schmapplet_s = null;
            settings.MiniSubTitle = "undefined" ;
			if(!schmapplet.isiGoogle && schmapplet.lang&&schmapplet.lang!==""){
				if(schmapplet.lang!=='en'){
					place_xml = place_xml.replace('.xml','') + "_" + schmapplet.lang + '.xml';
					}
			}else{
            place_xml += config.get("negotiateSuffix");
			}
			logDebug('selecte  ',schmapplet.selected,typeof(schmapplet.selected));
            if (schmapplet.places[schmapplet.selected].zoomedIn) {
				if(!(schmapplet.usingSTemplate)) {
					if(settings.UseFunctionIcons !== "undefined" &&
						settings.UseFunctionIcons.match(/^true$/i)) {
						showElement(settings.zoomin);
						hideElement(settings.zoomout);
					} else {
						$('zoom-p').innerHTML = settings.ZoomText;
					}
				} else {
				$('zoom-p').innerHTML = settings.ZoomText;
				}
				schmapplet.zoomedIn = false;
			}
			xmlLoad(place_xml, handlePlaces);
        }
		schmapplet.map2 = undefined;
}

function ifAutoPlay(j){
    if(j){
       startPlay(); 
	}else{
        pausePlayClick();
	}
	updateParentIframeCode();
	}
function pausePlayClick(){
	schmapplet.pauseClick = true;
	pausePlay();
	}
function changeIframe(){
    if($('guide-hotswap-frame')){
        $('guide-hotswap-frame').style.left = 0;
        $('guide-hotswap-frame').style.right = 0;
        $('guide-hotswap-frame').style.top = 0;
        $('guide-hotswap-frame').scrolling='no';
    }
    if($('section-hotswap-frame')) {
        $('section-hotswap-frame').style.left = 0;
        $('section-hotswap-frame').style.right = 0;
        $('section-hotswap-frame').style.top = 0;
    }
}

function getAllPhotos(place) {
    if (typeof(place.photo_objs) != 'undefined'
        && place.photo_objs.length <= 0)
        place.photo_objs = place.wcities_photos;
}


// the function i add to here because the parent call the function in child ,sometimes it is not stable,
 // and when we use it directly ,it is faster ;

function loadCountriesInfo(param) {
    var xmlPath = param;
    xmlLoad(xmlPath, handleCountries);
}

function loadNavInfo(param) {
   if(navMenu.loaded){
	   navMenu.loadedXml = param.toString();
   }
    var xmlPath = param;
	
    xmlLoad(xmlPath, handleNav);
}

function handleCountries(req) {
    var xml = req.responseXML;
    var menuPath = new XmlDoc(xml);
    parseCountries(menuPath);
}

function handleNav(req) {
    var xml = req.responseXML;
    var menuPath = new XmlDoc(xml);
    parseNav(menuPath);
}

function parseCountries(menuPath) {
    var navXml = menuPath.xml;
	var xmlAccess = new XMLAccess();
	xmlAccess.setXmlDoc(navXml);
    var navNode = xmlAccess.getFirstChild(navXml, '/schmap:mininavmenu');
    countriesMenu.navName = xmlAccess.getAttributeNode(navNode, 'name');
    var bigMenulist = xmlAccess.getChildren(navNode, 'schmap:continent');
    countriesMenu.bigMenus = map(function(bigMenuNode) {
        var bigMenu = {};
        bigMenu.text = xmlAccess.getAttributeNode(bigMenuNode, 'name');
        var midMenulist = xmlAccess.getChildren(bigMenuNode, 'schmap:country');
        bigMenu.midMenus = map(function(midMenuNode) {
            var midMenu = {};
            midMenu.text = xmlAccess.getAttributeNode(midMenuNode, 'name');
            midMenu.link = xmlAccess.getAttributeNode(midMenuNode, 'url');
			var template = xmlAccess.getAttributeNode(midMenuNode, 'template');
		    midMenu.template = template;
			midMenu.nav = xmlAccess.getAttributeNode(midMenuNode, 'loadmenu');
            var smallMenulist = xmlAccess.getChildren(midMenuNode, 'schmap:city');
            midMenu.smallMenus = map(function (smallMenuNode) {
                var smallMenu = {};
                smallMenu.text = xmlAccess.getAttributeNode(smallMenuNode, 'name');
                smallMenu.link = xmlAccess.getAttributeNode(smallMenuNode, 'url');
                smallMenu.geobox = xmlAccess.getAttributeNode(smallMenuNode, 'geobox');
                var smallMenuTemplate = xmlAccess.getAttributeNode(smallMenuNode, 'template');
                if(smallMenuTemplate&&smallMenuTemplate!==''){
                    smallMenu.template = smallMenuTemplate;
                }else{
                    smallMenu.template = template;
                }
				smallMenu.nav = xmlAccess.getAttributeNode(smallMenuNode, 'loadmenu');
                return smallMenu;
            }, smallMenulist);
            return midMenu;
        }, midMenulist);
        return bigMenu;
    }, bigMenulist);
}

function parseNav(menuPath) {
   var navXml = menuPath.xml;
   var xmlAccess = new XMLAccess();
	xmlAccess.setXmlDoc(navXml);
   var navNode =  xmlAccess.getFirstChild(navXml, '/schmap:schmappletmenu');
   navMenu.navName =  navNode.getAttribute('name');
   var bigMenulist = xmlAccess.getChildren(navNode, 'schmap:L1Entry');
   navMenu.bigMenus = map(function(bigMenuNode) {
       var bigMenu = {};
       bigMenu.text = xmlAccess.getSingleChildText(bigMenuNode, 'schmap:Text');
       bigMenu.link = xmlAccess.getSingleChildText(bigMenuNode, 'schmap:Link');
	   bigMenu.styleString =  bigMenuNode.getAttribute('style');
	   bigMenu.indent =  bigMenuNode.getAttribute('indent');
       var midMenulist = xmlAccess.getChildren(bigMenuNode, 'schmap:L1SubEntry');
       bigMenu.midMenus=map(function(midMenuNode) {
          var midMenu = {};
          midMenu.text = xmlAccess.getSingleChildText(midMenuNode, 'schmap:Text');
           midMenu.link = xmlAccess.getSingleChildText(midMenuNode, 'schmap:Link');
          midMenu.submenu =xmlAccess.getFirstChild(midMenuNode,'schmap:Submenu');
          var smallMenulist =xmlAccess.getChildren(midMenu.submenu,'schmap:L2Entry');
          midMenu.smallMenus =map(function (smallMenuNode) {
             var smallMenu={};
             smallMenu.text = xmlAccess.getSingleChildText(smallMenuNode, 'schmap:Text');
             smallMenu.link = xmlAccess.getSingleChildText(smallMenuNode, 'schmap:Link');
             smallMenu.count = xmlAccess.getSingleChildText(smallMenuNode, 'schmap:Count');
          return smallMenu;
         },smallMenulist);
        return midMenu;
      },midMenulist);
       return bigMenu;
   },bigMenulist);
  
   try{
      
	if(navMenu.loaded) {
       // window.frames["guide-hotswap-frame"].buildMenu(navMenu, navMenu.div, true);
       $('guide-hotswap-frame').contentWindow.buildMenu(navMenu, navMenu.div, true);
        navMenu.loaded = false;
    } 
       //for sports landing page;
	if(parent){
		parent.buildDropDown(navMenu, schmapplet.sid);
		if(parent.document.getElementById('teamSelect')) {
						var nowSelect = parent.document.getElementById('teamSelect');
						var optionsLen = nowSelect.options.length;
						for(var i = 0 ;i < optionsLen;i++) {
							if(subtitle == nowSelect.options[i].text) {
								nowSelect.options[i].selected = true;
								break;
						    }
					    }
					}
	}
   }catch(e){ }
}
function logTimeAll(message) {
  try{
  var prevTime = top.schmapplet.lastLoggedTime;
    top.schmapplet.lastLoggedTime = new Date();
    if(prevTime === undefined) {
        logDebug(message, '-- counting time');
    } else {
        logDebug(message, '--',
                 (top.schmapplet.lastLoggedTime - prevTime) / 1000, 'seconds');
    }
	 }catch(e){}
}

function changeTitleContent(content){
	
	$('subtitle-p').innerHTML=content;
	if( schmapplet.places[schmapplet.selected].id ==schmapplet.uplace.id){
		$('TitleIn').innerHTML=content;
	    
	}	
	schmapplet.uplace.sdesc=content;
	schmapplet.places[0].name = content;
	updateParentIframeCode();
}
	
function changeDescContent(content){
	if(schmapplet.places[schmapplet.selected].id == schmapplet.uplace.id){
	    showElement('ShortDescIn');
		$('ShortDescIn').innerHTML=content;
		
	}
	schmapplet.uplace.sdesc=content;
	schmapplet.places[0].sdesc = content;
	updateParentIframeCode();
	 
}
function checkonPlace(MyPlaceChecked, SchmapPlacesChecked){
    if (typeof(schmapplet.places[schmapplet.selected]) != 'undefined'
            && schmapplet.places[schmapplet.selected].zoomedIn) {
        zoomInOut.apply('zoom-p');
    }
    showMyPlace = true;
    initilized = 0;
    isFinished = 0;
    unbreakIERun = 0;
    if ((MyPlaceChecked && !SchmapPlacesChecked) || 
        (!MyPlaceChecked && SchmapPlacesChecked))
    {
        parent.setPlaceCheckEnabled(!MyPlaceChecked, !SchmapPlacesChecked);
    } else {
        parent.setPlaceCheckEnabled(true, true);
    }
    
    if (!MyPlaceChecked) {
        showMyPlace = false;
        isPlaceOnly = false;
        placesChecked = 0;
    }
    
    if(SchmapPlacesChecked) 
    {
        isPlaceOnly = false;
        if(typeof(schmapplet.noPhoto) != 'undefined') {
           noPhotosAtAll = schmapplet.noPhoto;
        }
        schmapplet.uplaceonly = null;
        if(!MyPlaceChecked) {
            placesChecked = 1;
        } else {
            placesChecked = 0;
        }
        if(fixedPlace != null)
          schmapplet.placeid = fixedPlace ;
       else
         schmapplet.placeid = null;
         
    } else if (!SchmapPlacesChecked && MyPlaceChecked) {
        isPlaceOnly = true;
        schmapplet.places = [];
        schmapplet.places[0] = schmapplet.uplace;
        noPhotosAtAll = true;
        schmapplet.uplaceonly = "true";
        placesChecked = 0;
        schmapplet.placeid = null;
    }
    setSubtitle();
    createPage();
    updateParentIframeCode();
}
function changeGeo(geo)
{
    var lng = geo.lng();  
    var lat = geo.lat();
    schmapplet.uplace.geo[0] = lat;
    schmapplet.uplace.geo[1] = lng;
    var location = new MochiKit.Maps.Point(lat, lng);
    schmapplet.uplace.geocode = location;
    schmapplet.uplace.marker.reposition(location);
    schmapplet.uplace.markerbig.reposition(location);
    
    // Now work out what guide, if any, the place belongs to
    var newGuide = findContainingGuide (geo);
    if (parent)
    {
        if ((newGuide == '' || (newGuide.toLowerCase() != parent.currGuide.toLowerCase())) && (newGuide != 'err'))
        {
            // The guide has change, so we need to load in the new guide
            if (newGuide == '')
            {
                // The new guide is the 'empty guide' ie. the point that the user added place
                // has been moved to is not contained in aany of out Schmap Guides
                
                guide_hotswap_showed = true;  // this is required to make the code realise that a new
                                              // guide is being loaded
                                              
                // Only load in new map if the location has been moved out of the bounds of the map
                // currently displayed in the Schmapplet
                var changeMap = true;
                if (typeof(schmapplet.topleft) != "undefined"
                    && schmapplet.topleft != 'undefined'
                    && schmapplet.topleft != null
                    && typeof(schmapplet.bottomright) != "undefined"
                    && schmapplet.bottomright != 'undefined'
                    && schmapplet.bottomright != null) 
                {
                    var tl = schmapplet.topleft.split(',');
                    var br = schmapplet.bottomright.split(',');
                    var north = tl[0];
                    var west  = tl[1];
                    var south = br[0];
                    var east  = br[1];
                    if (lat < north && lat > south && lng > west && lng < east)
                    {
                        changeMap = false;
                    }
                }
                
                if (changeMap)
                {
                    // Set up coordinates to use for this 'empty' guide in the schmapplet and set the
                    // 'loadingEmptyGuide' flag to prevent these cordinates from being destroyed before
                    // the new Schmapplet is loaded
                    schmapplet.topleft = (lat + 0.05) + ',' + (lng - 0.05);
                    schmapplet.bottomright = (lat - 0.05) + ',' + (lng + 0.05);
                    loadingEmptyGuide = true;
                    loadNewPlaces ('/noguide/empty/places.xml');
                }
                parent.allowMyPlaceOnlyChecked();
            }
            else
            {
                // Load in the new guide
                if (changedUrl != '')
                {
                    var url = changedUrl + '/places.xml';
                    
                    guide_hotswap_showed = true;  // this is required to make the code realise that a new
                                                  // guide is being loaded
                    loadNewPlaces (url);
                    parent.enableSchmapCheckBox();
                }
            }
        }
        parent.currGuide = newGuide;
    }
    
    updateParentIframeCode();
}

// Find the guide that 'contains' the given point
function findContainingGuide(geo)
{
    var lng = geo.lng();  
    var lat = geo.lat();
    
    try
    {
        if(countriesMenu && countriesMenu.bigMenus.length >0) 
        {
            var bigMenus = countriesMenu.bigMenus;
            var bmLen = bigMenus.length;
            for (var i = 0; i < bmLen; i++) 
            {
                var myBigMenu = bigMenus[i] ;
                var b_text1 = myBigMenu.text;
                var mmLen = myBigMenu.midMenus.length;
                for(var j = 0;j < mmLen;j++){
                    var midMenu = myBigMenu.midMenus[j];
                    var smLen = midMenu.smallMenus.length;
		    for (var z = 0;z < smLen;z++)  {
                        var smallMenu = midMenu.smallMenus[z] ;
                        var url = smallMenu.link;
                        var urlArr = url.split('/');
                        var nameOfGuide = urlArr[1];
                        changedUrl = smallMenu.link;
                        var geoBox = smallMenu.geobox;
                    
                        var coords = geoBox.split (',');
                        var north = coords[2];
                        var south = coords[0];
                        var east  = coords[3];
                        var west  = coords[1];
                                            
                        if (lat <= north && lat >= south &&
                            lng >= west && lng <= east)
                        {
                            return (nameOfGuide);
                        }
                    }
                }
	    }
	}
    }
    catch(e)
    {
        return('err');
    }
    return ('');
}

function changeIcon(iconId, iconUrl)
{   
    var normalUrl = iconUrl + '-normal.png'
    schmapplet.uplace.marker.setImage(normalUrl);
    var overUrl = iconUrl + '-over.png'
    schmapplet.uplace.markerbig.setImage(overUrl);
    schmapplet.uplace.id = iconId;
    schmapplet.uplace.schmapIcon = iconId; 

    updateParentIframeCode();
}

function copyObject(uplace) {
   var myPlace = {};
   for(var temPro in uplace){
       myPlace[temPro] = uplace[temPro] ;
   }
    return myPlace;
}

function createPage(){
	schmapplet.hasStats = false;
	if(typeof(xparams) != 'undefined'
                     && xparams["disableLinks"] == 'yes'){
		schmapplet.disableLinks = true;				 
	}
    if (isGuideSchmapplet) {
		if(subtitle.length > 0){
            $('subtitle-p').innerHTML = subtitle;
		    try{
				if(!initialized && parent){
					if(parent.document.getElementById('teamSelect')) {
						var nowSelect = parent.document.getElementById('teamSelect');
						var optionsLen = nowSelect.options.length;
						for(var i = 0 ;i < optionsLen;i++) {
							if(subtitle == nowSelect.options[i].text) {
								nowSelect.options[i].selected = true;
								logDebug('########   '+nowSelect.options[i].text);
								break;
						    }
					    }
					}
				}
			}catch(e){}
            removeElementClass('subtitle-p','heightForSub');
            if(typeof(settings.HasBoldSubtitle) != 'undefined'
                    && settings.HasBoldSubtitle == 'yes') {
                setStyle('subtitle-p',{'font-weight':'bold'});
            } else {
                setStyle('subtitle-p',{'font-weight':'normal'});
            }
            if (typeof(settings.DisableTitleLinks) == 'undefined'
                    || settings.DisableTitleLinks == 'false' || settings['SubTitleLink'] == 'true'
                    && placesChecked) {
                    disconnectAll('subtitle-p', 'onmouseover');
                    connect('subtitle-p', 'onmouseover', showUnderline);
                    connect('subtitle-p', 'onmouseout', hideUnderline);
                     disconnectAll('subtitle-p', 'onclick');
                     connect('subtitle-p','onclick',subTitlGo);
					setStyle('subtitle-p',{'cursor':'pointer'});
            } else {
                disconnectAll('subtitle-p', 'onmouseover');
                disconnect('subtitle-p','onclick',subTitlGo);
           }
        } 
    } else {
        $('title').initTxt = schmapplet.title;
        if ($('title') != null) {
             if(typeof(settings.DisableTitleLinks) == 'undefined'
                || settings.DisableTitleLinks == 'false') {
                 $('title').href = guide_url;
                 if (isIE6) { //add title mouseover
                     connect('title', 'onmouseover', showUnderline);
                     connect('title', 'onmouseout', hideUnderline);
                 }
             } else {
                 $('title').onclick = null;
                 connect('title', 'onmouseover', hideUnderline);
             }
        }
        $('subtitle-div').style.visibility = "hidden";
    }
    schmapplet.photoNodesAll = [];
    schmapplet.photos = [];

    var placesVsID = [];
    var stickPlaces = [];
    if (loadNewPlace) {
        // we are loading places via sections menu. Sticky places should be preserved.
        for (var i = 0; i < schmapplet.places.length; i++) {
            if (schmapplet.places[i].stickyPlaceType > 0) {
                stickPlaces.push(schmapplet.places[i]);
                placesVsID.push(schmapplet.places[i].id);
                ++ schmapplet._placesCount;
            }
        }
    } else {
        if (typeof(schmapplet.uplace) != 'undefined' && showMyPlace) {
            // always the first place
            schmapplet.placesById[schmapplet.uplace.id] = 0;
            schmapplet._placesCount = 1;
            stickPlaces.push(schmapplet.uplace);
            placesVsID.push(schmapplet.uplace.id);
        }
    }
    var mto = settings.MiniTabOrder;
    var mtot = mto.replace('htmltitle1','');
    if(mtot.search('htmltitle') != -1){
            if(typeof(settings.HtmlPanel) == 'undefined'){
               schmapplet.sportsSchedule = true;
        }
    }
    mto = mto.replace(/\s/g, '');
	mto = mto.split(',');

     //logTime('Create places');
    schmapplet.pcodeArray = [];
	schmapplet.regionArray = [];
    if(loadSchmapPlacesFlag && !isPlaceOnly) {
       schmapplet.rawPlaces = map(createPlace, schmapplet.placeslist);
       schmapplet.noPhoto = noPhotosAtAll ;
       loadSchmapPlacesFlag = false;
    } 

    if(!isPlaceOnly) {
        
        for (var i = 0; i < placesVsID.length; i++) {
            schmapplet.placesById[placesVsID[i]] = i;
        }
        schmapplet.places = [];
        if (stickPlaces.length > 0 && showMyPlace) {
            schmapplet.places = schmapplet.places.concat(stickPlaces, schmapplet.rawPlaces);
            hideElement ('subtitle-button-span');
        } else {
            schmapplet.places = schmapplet.rawPlaces;
            showElement ('subtitle-button-span');
        }
        //logTime('End of create places ');
    } else {
        hideElement ('subtitle-button-span');
    }

    var mtoLen = mto.length;
	$('view-panel').innerHTML = '<p id="counter"><span id="counter-current"></span></p>';
    tabs = [];
    for(var i=0; i < mtoLen; i++) {
        var tab = new tabOne();
        if(mto[i].indexOf(':0') != '-1') {
            var tabname  = mto[i].replace(':0','');
            tab.hasDetail = 'no';
        } else {
           var tabname = mto[i];
        }
        tab.tabType = tabname;
       if(tab.tabType == 'htmltitle1'
               && !schmapplet.hasStats) {
			break;
		}
		if(IEquirks && (i)) {
            appendChildNodes('view-panel',  SPAN({id: 'view-link-separator' + i},'/'));
        }
        appendChildNodes('view-panel',
                         SPAN({id: 'view-link' + i,
                               'class': 'view-link' + (i ? '' : ' first-view-link')}));
        
        if(mto.length ==1){
			hideElement('view-link0');
			}
        if(tab.tabType.toString() == 'htmltitle') {
            if((typeof(settings.HtmlPanel) == 'undefined'
                || settings.HtmlPanel.length <= 0)
                    && !schmapplet.usingSTemplate && !schmapplet.placetweet
                   ){
                continue;
            }
            if(typeof(settings.HtmlPanel) !== 'undefined'){
                $('article-frame').src = settings.HtmlPanel;	
			}else{
                $('schedule').innerHTML = '';
                schmapplet.sportsSchedule = true;
                setStyle('schedule',{'bottom':'122px'});
			}
			if(ifRemoveFutherGames()){
                if(isNotUndefOrNull(settings.htmltitleForResultView))
                    buildViewTab(tab,settings.htmltitleForResultView,'schedule');
                else
                    buildViewTab(tab,settings.htmltitle,'schedule');
			}else{
				buildViewTab(tab,settings.htmltitle,'schedule');
			}
            if(tab.tabRealView == schmapplet.tabLink){
                schmapplet.tabLinkOrder = i;
            }
        } else if(tab.tabType.toString() == "maptitle") {
           buildViewTab(tab,settings.MapTitle,'map');	

            if(tab.tabRealView == schmapplet.tabLink){
                schmapplet.tabLinkOrder = i;
            }
        } else if(tab.tabType.toString() == 'miniphotostitle') {
            photoTabSN = i;
            if(i == 0 && typeof(schmapplet.tabLink) == "undefined")
            	isPhotoView = true;
				buildViewTab(tab,settings.miniphotostitle,'photos');	
            
            if(tab.tabRealView == schmapplet.tabLink){
                schmapplet.tabLinkOrder = i;
            	isPhotoView = true;
            } else {
            }
        } else if(tab.tabType.toString() == 'detailtitle') {
		    buildViewTab(tab,settings.DetailTitle,'details');
			schmapplet.hasDetailTab = true;
            if(tab.tabRealView == schmapplet.tabLink){
                schmapplet.tabLinkOrder = i;
            }
        }else if(tab.tabType.toString() == 'htmltitle1') {
			if(!schmapplet.hasStats){
				break;
			}
			buildViewTab(tab,settings.htmltitle1,'stats');
            
            setStyle('statsContent',{'height':document.body.clientHeight-24-75 -schmapplet.advertH + 'px'});
				map(function(ele){
				setStyle(ele,{'margin-left':document.body.clientWidth/2 - 5+'px'});
				 },['upArrowStats','disupStats','downStats','disdownStats']);
	
		    schmapplet.hasHtml1Tab = true;
			if(tab.tabRealView == schmapplet.tabLink){
                schmapplet.tabLinkOrder = i;
            }
        }

        tabs.push(tab);
    }
	if(typeof(schmapplet.tabOrder)=='undefined'){
	schmapplet.tabOrder = 0;
	}
    var lasttab = "#view-link" + (tabs.length - 1);
    changeStyleSheetColor(lasttab, 'borderRightColor', 4);
	 var tabLen = tabs.length;
    for (i = 0; i < tabLen; i++) {
        var tabID = 'view-link' + i;
        var thisTab = tabs[i] ;
        $(tabID).innerHTML = thisTab.tabText;
        if(typeof(thisTab.tabAlt)!='undefined')
	         $(tabID).title = thisTab.tabAlt;
        $(tabID).order = i;
    }
   map(function(el) 
       {
           var hook = analyticsHooks.schedTabClick;
           if (el.id == 'view-link1')
           {
               hook = analyticsHooks.mapTabClick;
           }
           else if (el.id == 'view-link2')
           {
               hook = analyticsHooks.statsTabClick;
           }
           analyticsConnect (el, 'onclick', changeView, hook);
       },
       getElementsByTagAndClassName('SPAN', 'view-link'));
    showView(schmapplet.tabLinkOrder);

    // Reduce the font size of the view links for narrow sports schmapplets 
    if (schmapplet.sportsSchedule)
    {
        var spanWidth = $('canvas').clientWidth + 2;
        if (spanWidth <= 180)
        {
            var tabLen = tabs.length ;
            for (var i = 0; i < tabLen; i++ )
            {
                $('view-link' + i).style.fontSize = '9px';
            }
        }
    }
    
    // NPF [Schmap Maps - Begin] Moved this code from lower down since schmapplet.selected needs to be 
    //                           defined before Make_Map (called by waitForWidth)
    schmapplet.selected = 0;  
    if (typeof(schmapplet.placeid) !== 'undefined' && schmapplet.placeid != null) {
        var placeIndex = schmapplet.placesById[schmapplet.placeid];
        if (placeIndex !== undefined) {
            // XXX: when this is merged with the cleaned up code,
            // remove this logic into a new method selectPlace(index)
            schmapplet.places[schmapplet.selected].unhighlight();
            schmapplet.selected = placeIndex;
            setCurrentCounter (schmapplet.selected + 1);
        } else {
            schmapplet.selected = 0;
            schmapplet.placeid = schmapplet.places[schmapplet.selected].id;
            setCurrentCounter (1);
        }
    } else if (isPlaceOnly) {
        schmapplet.uplace.highlight();
        setCurrentCounter (1);
    } else {
        schmapplet.selected = 0;
        schmapplet.placeid = schmapplet.places[schmapplet.selected].id;
        setCurrentCounter (1);
    }
    // NPF [Schmap Maps - End]

    logTime('Finished creating places ... about to make the map');
    //waitForWidth();
    if (!initialized) {
        if ($('map').addEventListener)
        /** DOMMouseScroll is for mozilla. */
            $('map').addEventListener('DOMMouseScroll', captureWheel, false);
        else {
            connect('map', 'onmousewheel', captureWheel);
            // IE/Opera
        }
    }

    $('map').style.position = 'absolute';
    $('map2').style.position = 'absolute';
    if (!isIE6) {
        $('map').style.width = '';
        $('map').style.height = '';
        $('map2').style.width = '';
        $('map2').style.height = '';
    }
    // cycling_d = callLater(schmapplet.cycleTime, cyclePlace);

    if (!schmapplet.autoplay)
        autoPlaying = false;
    else {
        autoPlaying = true;
    }

    if (autoPlaying && !flash_d) {
        // to know the current status is playing or not ,should be played or not 
        num = 0;
        flashPlayButton();
    }

     for(var i = 0 ;i <tabs.length;i++){
          removeElementClass($('view-link' + i), 'disabled-view-link');
          $('view-link' + i).style.cursor = 'pointer';
         if(i > 0) {
            addElementClass($('view-link' + i), 'view-link');
         }
     }

    var nowTabsNum = tabs.length;
    if(noPhotosAtAll && photoTabSN >= 0) {
        removeElementClass('view-link' + photoTabSN, 'current-view-link');
        addElementClass('view-link' + photoTabSN, 'disabled-view-link');
        nowTabsNum --;
        if(tabs.length > (photoTabSN+1)) removeElementClass('view-link' + (photoTabSN+1), 'view-link');
		if(isIE6||isIE7){
			if(photoTabSN!==0){
		         addElementClass('view-link-separator' + photoTabSN, 'disabled-view-link');
			}else if(tabs.length > (photoTabSN + 1)) {
                 addElementClass('view-link-separator' + (photoTabSN+1), 'disabled-view-link');
			}
		}
    } else if(photoTabSN >= 0) {
        removeElementClass('view-link' + photoTabSN, 'disabled-view-link');
				if(isIE6||isIE7){
			if(photoTabSN!==0){
		         removeElementClass('view-link-separator' + photoTabSN, 'disabled-view-link');
			}else if(tabs.length > (photoTabSN+1)) {
				 removeElementClass('view-link-separator' + (photoTabSN+1), 'disabled-view-link');
				}
			}
    }
    if( schmapplet.sportsSchedule){
        createSchedule();
	}

	makeThumbPhotos();
	logDebug('nowTabsNum ', nowTabsNum);
    if(nowTabsNum == 1) {
        for(var i = 0 ;i <tabs.length;i++){
          removeElementClass($('view-link' + i), 'current-view-link');
          addElementClass($('view-link' + i), 'disabled-view-link');
          changeViewByOrder(schmapplet.tabOrder, 0);
        }
    } else {
        var order = $('view-link' + schmapplet.tabLinkOrder);
        if (isPhotoView && noPhotosAtAll) {
           var new_order = 0;
           changeViewByOrder(schmapplet.tabOrder, new_order);
        } else {logDebug('nowTabsNum f', schmapplet.tabOrder,order.order);
          changeViewByOrder(schmapplet.tabOrder, order.order);
        }
    }


    initialized = 1;
    loadNewPlace = false;
	if (initialized || !isPhotoView) { 
        try {
            // $('loading-message-section').style.visibility = 'hidden';
            if($('loading-message-guide')) {
              setStyle('loading-message-guide',{'visibility':'hidden'});
            }
        } catch(e) {
            logDebug('mmmm',e);
        }
        $('guide-hotswap-div').style.visibility = 'hidden';
        $('section-hotswap-div').style.visibility = 'hidden';
        section_hotswap_showed = false;
        guide_hotswap_showed = false;
		loadingNewSchmapplet = false;
    }

    if (schmapplet.usingSTemplate)
    {
        if (zoomLevel > 0)
        {
            $('zoom-p').style.visibility = "visible";
        }
    }

    // add codes for loading menus after all of mini schmap loaded completely
   if(settings.MiniMenuOverrideName != 'undefined'
            && settings.MiniMenuOverrideName != null
            && settings.MiniMenuOverrideName.length > 0) {
        var guidePath = '/xml/' + settings.MiniMenuOverrideName;
        guideSrcXml = '/common/minicitiesmenu.html?'+guidePath+'&Countries';
       truncationNeeded = 0;
    }

    if(typeof(settings.isGuideSchmapplet) != 'undefined'
            && settings.isGuideSchmapplet.match(/true/i)) {
        if(showTwoMenus[0] == 1) {
            callLater(5.0, function() {
                if (guideLoaded == 0) {
                    
                    if ($('guide-hotswap-div').innerHTML == '') {
                        $('guide-hotswap-div').innerHTML = guideHtml;
                    }
                   
                    //loadCountriesInfo('/xml/mininavmenu.xml');
                    $('guide-hotswap-frame').contentWindow.location.replace(guideSrcXml);
                    guideLoaded = 1;
                }
            });
        }
       if(showTwoMenus[1] == 1) {
                if (sectionLoaded == 0) {
                    if ($('section-hotswap-div').innerHTML == '') {
                        $('section-hotswap-div').innerHTML = sectionHtml;
                    }
                    sectionSrcXml = getSectionSrcXml(schmapplet.uid,
                        settings.MiniMenu2OverrideName);

                   if (BrowserDetect.browser === "Firefox")
                   {
                       $('section-hotswap-frame').contentWindow.document.body.innerHTML = '';
                   }
                    callLater(5.0, function() {
                        $('section-hotswap-frame').contentWindow.location.replace(sectionSrcXml);
                        //$('section-hotswap-frame').src = sectionSrcXml;
                    });
                    sectionLoaded = 1;
        }
    }
        }

    // #3010 [BEGIN]
    if (typeof(settings.RemoveLinksOverride) != 'undefined') {
        var uids = settings['RemoveLinksOverride'].split(',');
        removeLinks = false;
        for (var i=0; i < uids.length; i++) {
            if (uids[i] == schmapplet.uid) {
                removeLinks = true;
            }
        }
        if (removeLinks) {
            removeLargeTemplateLinks();
        }
    }
    // #3010 [END]

    logTime('Schmaplet completely loaded', true);
}


// #3010 [BEGIN]
function removeLargeTemplateLinks() {

    disconnect($('title-link').lastChild, 'onclick', mainTitlGo);
    connect($('title-link').lastChild,'onmouseover',hideUnderline);
    disconnectAll('subtitle-p', 'onmouseover');
    setStyle('subtitle-p', {'cursor': 'default'});
    disconnectAll('subtitle-p', 'onclick');

    disconnect(schmapplet.map.markersElement,'onclick', mainTitlGo);
    setStyle(schmapplet.map.markersElement, {'cursor':'default'});
    disconnect(schmapplet.map.imgElement,'onclick', mainTitlGo);
    setStyle(schmapplet.map.imgElement, {'cursor':'default'});

    disconnectAll('TitleIn', 'onmouseover');
    disconnectAll('TitleIn', 'onclick');
    setStyle('TitleIn', {'cursor': 'default'});

}
// #3010 [END]

function changingColor(colorset){
    schmapplet.colorset = parse_colorset(colorset);
    
    // The following is a bit of a hack to deal with necessary color mapping change in losing the tabs, and
    // switching to view links. It has the effect of keeping the place strp as it's original color in Schmapplets
    // that were distributed before the change to remove the tabs.
    if (schmapplet.colorset[15] == '5C5A4E')
    {
        schmapplet.colorset[15] = newDefaultDetailsStripColor;
    }
    if (schmapplet.colorset[19] == 'F0EFDA')
    {
        schmapplet.colorset[19] = 'FFEA97';
    }
    apply_colorset(schmapplet.colorset, colorset_template, /embedded.css$/);
 }
function hasPlayedGames(i){
	for(j=0; j<schmapplet.regionArray[i].regionArray.length;j++){
		var played = schmapplet.regionArray[i].played[j];
		if(played)
			return true;
	}
	return false;
}
function createSchedule(){
	$('schedule').innerHTML = '<div id="upArrowDiv" class="ArrowDIV" style="display: block;"><img id="upArrow" class="upArrow" src="/images/pageiconstest/up.gif" style=" display: none;"/><img id="disup" class="upOrDown" src="/images/pageiconstest/disup.gif" style=" display: block;"/></div><div id="scheduleborad" style="overflow:hidden;"></div><div id="downArrowDIV" class="ArrowDIV" style="display: block;"><img id="down" class="upOrDown" src="/images/pageiconstest/down.gif" style=" display: block;"/><img id="disdown" class="upOrDown" src="/images/pageiconstest/disdown.gif" style="display: none;"/></div>';
	var today = new Date();
	var thisMonth = schmapplet.months[today.getMonth()];
	var nextMonth = schmapplet.months[today.getMonth()+1];
	var divIndex = 0;
    var pcodeArrayLen = schmapplet.pcodeArray.length;
	var currentIndex = 0;
    var lastMonthIndex = 0;
	var nextMonthIndex = 0;
	schmapplet.gameDayArray = [];
    for(i=0; i < pcodeArrayLen;i++){
		var month = DIV({"class": 'sportsMonth'},schmapplet.pcodeArray[i]);
		month.num = '';
		//logDebug('thisMonth '+thisMonth +' schmapplet.pcodeArray[i].substr(0,3) '+schmapplet.pcodeArray[i].substr(0,3));
		 if(schmapplet.pcodeArray[i].substr(0,3) == thisMonth
                 && schmapplet.pcodeArray[i].substr(schmapplet.pcodeArray[i].length-4)==today.getFullYear()){
			 currentIndex = divIndex;
         } else if(schmapplet.pcodeArray[i].substr(0,3) == nextMonth
                 && schmapplet.pcodeArray[i].substr(schmapplet.pcodeArray[i].length-4)==today.getFullYear()){
		    nextMonthIndex = divIndex ;
		 } 
		 if(i == pcodeArrayLen -1)
             lastMonthIndex = divIndex;
         divIndex++;
         if(ifRemoveFutherGames()){
         	if(hasPlayedGames(i)){
         		appendChildNodes('scheduleborad',month);
         		connect(month,'onmouseover',changeBG);
		 		connect(month,'onmouseout',changeBGback);
        	 }else{
         		//continue;
         	}
         }else{
         	appendChildNodes('scheduleborad',month);
         	connect(month,'onmouseover',changeBG);
		 	connect(month,'onmouseout',changeBGback);
         }
//         connect(month,'onmouseover',changeBG);
//		 connect(month,'onmouseout',changeBGback);
		 for(j=0; j<schmapplet.regionArray[i].regionArray.length;j++){
			 var day = DIV({"class": 'sportsDay'},schmapplet.regionArray[i].regionArray[j]);
			 day.num = schmapplet.regionArray[i].placeNum[j];
			 day.url = schmapplet.regionArray[i].url[j];
			 day.played = schmapplet.regionArray[i].played[j];
			 day.divIndex = divIndex;
			 divIndex++;
		     if(ifRemoveFutherGames()){
			 	if(day.played)
			 		appendChildNodes('scheduleborad',day);
	         }else{
	         	appendChildNodes('scheduleborad',day);
	         }
			 if(day.url!=''&&!schmapplet.disableLinks){
			     analyticsConnect (day, 'onclick', goToSportsUrl, analyticsHooks.schedGameLink);
				setStyle(day,{'cursor':'pointer'});
			 }
	         connect(day,'onmouseover',changeBG);
     		 connect(day,'onmouseout',changeBGback);
			 schmapplet.gameDayArray.push(day);
		 }
	}
    var temBottom = parseInt($('schedule').style.bottom) - 34;
     if(isGuideSchmapplet) {
		 var scheduHeight =  document.body.clientHeight-75-37- temBottom -schmapplet.advertH;
           setStyle('scheduleborad',{'height':scheduHeight + 'px'});
      } else {
		   var scheduHeight =  document.body.clientHeight-75-37- temBottom + $('subtitle-div').clientHeight -schmapplet.advertH;
          setStyle('scheduleborad',{'height':scheduHeight + 'px'});
      }
    map(function(ele){
				setStyle(ele,{'margin-left':document.body.clientWidth/2 - 5+'px'});
				 },['upArrow','disup','down','disdown']);
	schmapplet.comingGame = null;

    var scheduleLen = schmapplet.gameDayArray.length;
    for (var i = scheduleLen - 1; i >= 0; i--) {
                var currentDiv = schmapplet.gameDayArray[i];
                if (typeof(currentDiv.played) != 'undefined'
				      && currentDiv.played != 0) {
                    if (currentDiv != null) {
                        schmapplet.comingGame = currentDiv;
						currentIndex = schmapplet.comingGame.divIndex;
                        break;
                    }  else {
					    schmapplet.comingGame = schmapplet.gameDayArray[0];
						currentIndex = schmapplet.comingGame.divIndex;
					}
                } else {
			      	schmapplet.comingGame = schmapplet.gameDayArray[0];
					currentIndex = schmapplet.comingGame.divIndex;
				}
    }
	if(currentIndex && currentIndex != 0){
		$('schedule').currentIndex = currentIndex;
	} else if(currentIndex == 0 && nextMonthIndex != 0){
		$('schedule').currentIndex = nextMonthIndex;
	} else {
	    $('schedule').currentIndex = lastMonthIndex;
	}
	if(schmapplet.comingGame)
     changeBG.apply(schmapplet.comingGame);
   callLater(0.1,function(){
        if($('loading-message-guide').style.visibility == 'hidden' 
		    && $('schedule').style.visibility == 'visible'  )
           jugdeArticle();
		   jugdescroll($('schedule'));
    });
}

function startScoll(){
	if(!schmapplet.scrollTimerStarted){
		schmapplet.currentSrollObj = this.scrollObj;
		schmapplet.scrollTimer = setInterval('scollingDown()',20);
		schmapplet.scrollTimerStarted = 1;
	}
}

function changeBG(){
    schmapplet.sportsBG = getStyle('schedule','backgroundColor');
    if(typeof(schmapplet.comingGame) != 'undefined'
            && schmapplet.comingGame != null) {
        removeElementClass(schmapplet.comingGame,'backDay');
	   addElementClass(schmapplet.comingGame,'schedule');
    }
    if(typeof(schmapplet.gameDayArray[schmapplet.selected]) != 'undefined') {
       removeElementClass(schmapplet.gameDayArray[schmapplet.selected],'backDay');
       addElementClass(schmapplet.gameDayArray[schmapplet.selected],'schedule');
    }
    addElementClass(this,'backDay');
	if(this.num==undefined) return;
	setCurrentCounter (this.num);
	if(this.num =='') return;schmapplet.places[schmapplet.selected].unhighlight();
	schmapplet.selected = this.num-1;
	schmapplet.places[this.num-1].highlight();
}

function changeBGback(){
    removeElementClass(this,'backDay');
    addElementClass(this,'schedule');
	setCurrentCounter (schmapplet.selected+1);
	if(this.num =='') return;
	addElementClass(schmapplet.gameDayArray[schmapplet.selected],'backDay');
}
function scollingDown(){
	schmapplet.currentSrollObj.scrollTop += 4;
	if(schmapplet.scrolldownFlag){
		endScoll();
		return;	
	}
	jugdescroll(schmapplet.currentSrollObj.parentNode);
}

function startuScoll(){
	if(!schmapplet.scrollTimerStarted){
	schmapplet.currentSrollObj = this.scrollObj;
	schmapplet.scrollTimer = setInterval('scollingUp()',20);
	schmapplet.scrollTimerStarted = 1;
	}
}

function scollingUp(){
	schmapplet.currentSrollObj.scrollTop -= 4;
	jugdescroll(schmapplet.currentSrollObj.parentNode);
}

function endScoll(){
	schmapplet.scrollTimerStarted = 0;
	clearInterval(schmapplet.scrollTimer);
	schmapplet.scrollTimer = null;
}

function goToSportsUrl(){
	window.open(this.url);
	}

function jugdescroll(divObj) {
    var currentNode = divObj.childNodes[1];
	if(divObj.id == 'schedule' && schmapplet.IEquirks) {
	   var temH = getElementDimensions(currentNode).h -10;
	} else {
	   var temH = getElementDimensions(currentNode).h ;
	}
    if (currentNode.scrollHeight <= temH) {
        hideElement(divObj.firstChild);
        hideElement(divObj.lastChild);
        currentNode.style.marginTop = '10px';
    } else {
         showElement(divObj.firstChild);
         showElement(divObj.lastChild);
         currentNode.style.marginTop = '0px';
        if (currentNode.scrollTop <= 0) {
            hideElement(divObj.firstChild.firstChild);
            showElement(divObj.firstChild.lastChild);
        } else {
            showElement(divObj.firstChild.firstChild);
            hideElement(divObj.firstChild.lastChild);
			divObj.firstChild.scrollObj = currentNode;
            connect(divObj.firstChild, 'onmouseover', startuScoll);
            connect(divObj.firstChild, 'onmouseout', endScoll);

        }
        if (currentNode.scrollHeight - getElementDimensions(currentNode).h 
                <= currentNode.scrollTop && currentNode.scrollTop >= 0)  // NPF
        {
            hideElement(divObj.lastChild.firstChild);
            showElement(divObj.lastChild.lastChild);
        } else {
            showElement(divObj.lastChild.firstChild);
            hideElement(divObj.lastChild.lastChild);
			divObj.lastChild.scrollObj = currentNode;
            connect(divObj.lastChild, 'onmouseover', startScoll);
            connect(divObj.lastChild, 'onmouseout', endScoll);
       }
    }
}

function formatDate(){
    var now = new Date();
    var getYear = (now.getFullYear() + '').substring(2);
    var getMonth = now.getMonth() + 1;
    var getDate = now.getDate();
    getMonth += '';
    getDate += '';
    if(getMonth.length < 2) {
        getMonth = '0' + getMonth;
    }
    if(getDate.length < 2) {
        getDate = '0' + getDate;
    }
    var temString = getDate + getMonth + getYear ;
    return temString;
}
function getSiInUrl(thisUrl,append)  {
    var temTxt = thisUrl.toString();
	temTxt = temTxt.replace('&sit=','&si=');
    if(typeof(schmapplet.si) != 'undefined'
            && schmapplet.si ){
       var hyphenNum = schmapplet.si.split('-');
       var hyphenLen = hyphenNum.length -1 ;
       switch(hyphenLen) {
           case 0 :
             var temString1 = formatDate();
             temString1 = '-' + temString1 ;
             var temString2 = Math.random() + '';
             temString2 = temString2.split('.');
             var temStr =  temString1 + temString2[1].substr(0,6);
             temStr = schmapplet.si + temStr ;
             if(append){
                temStr = '&si=' + temStr ;
                temTxt= temTxt +  temStr;
             }else{
                temTxt = temTxt.replace(schmapplet.si,temStr);
             }
             thisUrl.buffer = [temTxt ] ;
             return thisUrl;
          case 1:
             var temString1 = formatDate();
             temString1 = '-' + temString1 ;
             var temString2 = Math.random() + '';
             temString2 = temString2.split('.');
             var temStr =  temString1 + temString2[1].substr(0,6);
             temStr = schmapplet.si +temStr ;
             if(append){
                temStr = '&si=' + temStr ;
                temTxt= temTxt +  temStr;
             }else{
                temTxt = temTxt.replace(schmapplet.si,temStr);
             }
              thisUrl.buffer = [temTxt] ;
              return thisUrl;
          case 2:
           var temsi = hyphenNum[0] + '-' + hyphenNum[2];
            var temString1 = formatDate();
            temString1 = '-' + temString1 ;
            var temString2 = Math.random() + '';
            temString2 = temString2.split('.');
            var temStr = temString1 + temString2[1].substr(0,6);
            temStr = temsi + temStr ;
             if(append){
                temStr = '&si=' + temStr ;
                temTxt= temTxt +  temStr;
             }else{
               temTxt = temTxt.replace(schmapplet.si,temStr);
             }
              thisUrl.buffer = [temTxt] ;
            return thisUrl;
        }
    } else {
         var temString1 = formatDate();
         var temString2 = Math.random() + '';
         temString2 = temString2.split('.');
         var temStr =  temString1 + temString2[1].substr(0,6);
         temStr = 'SCHMAP-' + temStr ;
         thisUrl.append('&si=').append(temStr);
   }
    return thisUrl;
}

function uninstall() {
    clearMapLeaks();
}

function getPlaceInfoStyle(mychild) {
    var divName = mychild.replace('PlaceStrip','');
    if (typeof(settings[mychild]) != 'undefined'
            && settings[mychild].match(/no/i)) { // if 1
        hideElement(divName);
    } else {
        if (typeof(settings[mychild]) != 'undefined') {  //if 2
            $(divName).className = '';
            var styles = settings[mychild].split(':');
            if (styles.length > 1) {   //if 3
                var myStyle = styles[1];
                var myStyleLen = myStyle.length;
                for (var j = 0; j < myStyleLen; j++) {
                    var styleName = myStyle.charAt(j);
                    styleName += '-placeInfo';
                    addElementClass(divName, styleName);
                }
            }  //if 3
        }    //if 2 over
   }
}
function getTrunction(srcElement,spanWidth,num) {
    var endTxt = $(srcElement).initTxt;
	if(typeof(endTxt)== 'undefined') {
	   endTxt = '';
	} else {
        if(isIE6)  spanWidth -= 10;
    if($(srcElement).className.indexOf('n-placeInfo') != -1) {
        var srcTxt = $(srcElement).initTxt;
        if (srcTxt.length * num > spanWidth) {
            var temLen = Math.round(spanWidth / num) ;
            var temTxt = srcTxt;
            if (temLen + 3 <= srcTxt.length) {
            endTxt = temTxt.substr(0, temLen) + '...';
            }
        }
    }
	
	}
    return endTxt;
}
function getTrunctions(srcElement,spanWidth,num) {
    var endTxt = $(srcElement).initTxt;
	if(typeof(endTxt)== 'undefined') {
	   endTxt = '';
	} else {
        if(isIE6)  spanWidth -= 10;
 
        var srcTxt = $(srcElement).initTxt;
        if (Number(srcTxt.length * num) > Number(spanWidth)) {
            var temLen = Math.round(spanWidth / num *4) ;
            var temTxt = srcTxt;
            if (temLen + 3 <= srcTxt.length) {
            endTxt = temTxt.substr(0, temLen-6) + '...';
            }
        }
 
	
	}
    return endTxt;
}

function overwriteXparams(){
	if(typeof(xparams_ov)=='undefined'){
	    return;
	}
	var params = keys(xparams_ov);
	for(i=0;i<params.length;i++){
		var param = params[i];
		if(param ==	'mapLogo'){
 
			if(xparams_ov['mapLogo'].substr(xparams_ov['mapLogo'].length-5,1)=='0'){
				schmapplet.mapLogo = xparams_ov['mapLogo'];
				continue;
			}
		}
        if(param ==	'logoLink'){
			schmapplet.logoLink = xparams_ov['logoLink'];
		}
		xparams[param] = xparams_ov[param];
	}
}
function jugdeArticle(){
    if($('scheduleborad')) {
        var tempH1 = $('scheduleborad').scrollHeight - $('schedule').currentIndex * 20 ;
        var tempH2 = getElementDimensions('scheduleborad').h - tempH1;
        if(tempH2 > 0 ) {
               $('scheduleborad').scrollTop = $('scheduleborad').scrollHeight - getElementDimensions('scheduleborad').h;
        } else {
           $('scheduleborad').scrollTop = $('schedule').currentIndex* 20 ;
        }
    }

}

if(trackPage) {
	var pageTracker; 
	addScript('/common/ga.js', function () {
	    pageTracker = _gat._getTracker("UA-2919908-1");
	    pageTracker._initData();
	    pageTracker._trackPageview();

	});
}

function createGMarker(map,thisPlace){
    if((settings.ZoomHideIcons !== undefined) &&
           (map.hideAll !== undefined)) {
		    if(typeof(thisPlace.gmarkerbig) == 'undefined'){
			    var geocode = new MochiKit.Maps__Google.Point(schmapplet.places[schmapplet.selected].geo[0],
		                                              schmapplet.places[schmapplet.selected].geo[1]);
				var mapIconBig = mapiconspath + schmapplet.places[schmapplet.selected].schmapIcon + '-over.png';
				var mapIconbig = new MochiKit.Maps__Google.Icon(mapIconBig,      
														new MochiKit.Style.Dimensions(settings.OverIconSize[0],
																settings.OverIconSize[1]),
														new MochiKit.Style.Coordinates(schmapplet.overAnchorX,
																schmapplet.overAnchorY));
			    var gmarkerbig = new MochiKit.Maps__Google.Marker(geocode, mapIconbig);
				thisPlace.gmarkerbig = gmarkerbig;
				gmarkerbig.placeid = thisPlace.id;
			    schmapplet.map2.addItem(thisPlace.gmarkerbig);
			} else {
			   thisPlace.gmarkerbig.show()
			}
			
        map.hideAll(settings.ZoomHideIcons);
    }

}
function checkPhotoFinished(){
    if($('photo-p').firstChild.complete){
       $('loading-message-guide').style.visibility = 'hidden';
	   $('photo-table').style.visibility = 'visible';
	   return;
   } else {
    callLater(0.01,checkPhotoFinished);
   }
}

function showMyPanel(evt){
    
	$('copyright-hotswap-div').style.visibility = 'visible';
	if ($('copyrightTxt')) {
		$('copyright').onclick = function(){ 
			window.open('http://www.schmap.com/copyright/sportswidgets');
			$('copyright-hotswap-div').style.visibility = 'hidden';
		}
	}

}

function hideMyPanel(evt){
if (isMouseInsideContainer(evt,'infoEle','copyright-hotswap-div')) return;
   $('copyright-hotswap-div').style.visibility = 'hidden';

}

function isMouseInsideContainer(evt,targetElem,container) {
  var mx = evt.mouse().client.x;
  var my = evt.mouse().client.y;
  var pos_lower = getElementPosition(targetElem);
  var dim_lower = getElementDimensions(targetElem);
  var pos=getElementPosition(container);
  var dim=getElementDimensions(container);
  if(schmapplet.IEquirks) {
      mx+= 1;
      my+= 1;
  }
  if(my <= pos.y){
        if(my > pos_lower.y + 1 && mx > pos_lower.x 
	     && mx < (pos_lower.x + dim_lower.w)){
          // the top of title-button is 3 px,but we can only get 2px
		  return true;
		}
    }else{
		if(my < (pos.y + dim.h) && mx > pos.x && mx < (pos.x+dim.w)){
		  return true;
	    }
	}
	 return false;
}

function gotoMylink(){
    window.open('http://www.schmap.com/widgets');
	$('copyright-hotswap-div').style.visibility = 'hidden';
}

function isMouseInsideSchmappletText(evt) {
  var mx = evt.mouse().client.x;
  var my = evt.mouse().client.y;
  var pos_lower = getElementPosition('whatsthis');
  var dim_lower = getElementDimensions('whatsthis');
  var pos=getElementPosition('GetSchmappletText');
  var dim=getElementDimensions('GetSchmappletText');
  if(schmapplet.IEquirks) {
      mx+= 1;
      my+= 1;
  }
  if(!showed) {
	  return false;
  }
  if(my>=(pos.y+dim.h)){
	  if(my<(pos_lower.y+dim_lower.h) && mx>pos_lower.x && mx<(pos_lower.x+dim_lower.w)){
		  return true;
		  }

	  }else{
		    if(my>pos.y && mx>pos.x && mx<(pos.x+dim.w)){
		  return true;
		  }

		  }
		  return false;

}

function buildViewTab(tab,thisHtmlTitle,thisDivName){
	if(typeof(thisHtmlTitle) != 'undefined'){
		var thisTitle = thisHtmlTitle.split('|');
		if(thisTitle.length > 1){
			tab.tabAlt = thisTitle[1];
			tab.tabRealView = thisDivName;
			tab.tabDiv = $(thisDivName);
		}else{
		    tab.tabRealView = thisDivName;
			tab.tabDiv = $(thisDivName);
		}
		var tempTxt = thisTitle[0].split(',');
		if(tempTxt.length > 1){
			var titleLen = tempTxt.length;
			for(var i=0;i<titleLen;i++){
				var oneTxt = {};
				var temOne = tempTxt[i].split(':');
				oneTxt.name = temOne[0];
				oneTxt.len = temOne[1];
				tab.displayedObj.push(oneTxt);
			}
		}
		tab.tabText = thisTitle[0];
    } 
	// Switch 'Schedule' to 'sched' for narrow sports schmapplets
	if (schmapplet.sportsSchedule 
	    && tab.displayedObj.length > 1) {
		var spanWidth = $('canvas').clientWidth + 2;
		for(var i=0;i<tab.displayedObj.length;i++){
		    var thisObj = tab.displayedObj[i];
			if(spanWidth<= thisObj.len){
			   tab.tabText = thisObj.name;
			   break;
			}
		}
	}	
}


function changePhoto(){
   hideElement(this);
   this.imgMouseover.style.display = 'inline';
}

function changePhotoBack(){
   hideElement(this);
   this.imgMouseout.style.display = 'inline';;
}

function stripTitleGo(baseurl) {
	var url = new StringBuffer();
	if(!baseurl){
		baseurl = '';
		var utltail = schmapplet.sid + '/';
	}else {
	    baseurl = settings.SchmappletHome.split('/')[1] + '/';
	    var utltail =  '';
	}
	url.append("http://").append(window.location.host).append("/").append(baseurl).append(schmapplet.uid.toLowerCase()).append("/").append(utltail).append("#p=");
	var placeid = schmapplet.places[schmapplet.selected].id;
	url.append(placeid) ;
    var urlParam = ''
    if(settings['WidgetLinkPopupWidth'])
    urlParam += 'width=' + settings['WidgetLinkPopupWidth'];
    if(settings['WidgetLinkPopupHeight'])
    urlParam += ', height=' + settings['WidgetLinkPopupHeight'];
	urlParam += 'toolbar=yes, menubar=yes, location=0, resizable=yes';
 
   	window.open(url.toString(),'',urlParam);
	}

