﻿/*  Virtual Earth Client Javascript Beta v3
 *  (c) 2007 Genexis Consulting Pty Ltd.
 *
 *  Contact: http://www.genexis.com.au
 *  Email: alfred.wong@genexis.com.au, fred.yip@genexis.com.au
 *
/*--------------------------------------------------------------------------*/
var pinID = 0;
var map = null;
var current_zoom_level;    
var current_mode;
var current_map_style;
var mHeight = 1400;
var mWidth = 1400;
var IEmode = false;
var IE6mode = false;
var old_on_mouse_over_call_back = null;
function GetMap()      
{   
    CheckIEVersion();
    //alert('GetMap');      
    map = new VEMap('myMap');
    map.ShowDisambiguationDialog(false);
    map.LoadMap();
    map.SetMapStyle(VEMapStyle.Hybrid);
    map.SetZoomLevel(3);
    current_mode = map.GetMapMode();  
    current_zoom_level = map.GetZoomLevel(); 
    current_map_style = map.GetMapStyle();
    map.AttachEvent("onchangeview", OnChangeView);
    map.AttachEvent('oninitmode', ModeChange2);
    old_on_mouse_over_call_back = VEPushpin.OnMouseOverCallback;
    UseCustomPopup(true);
} 

var _custom_popup_created = false;
function UseCustomPopup(yesorno)
{
    if (yesorno)
    {
        VEPushpin.ShowDetailOnMouseOver = false;
        VEPushpin.OnMouseOverCallback = PinHover;
        if (!_custom_popup_created) CreateCustomPopup();
    }
    else
    {
        VEPushpin.ShowDetailOnMouseOver = true;
        VEPushpin.OnMouseOverCallback = old_on_mouse_over_call_back; //function(x, y, title, details) {};
    }
}

function AddShim(el,sid)  //add iframe shim     
{   
  if (map.GetMapMode() == VEMapMode.Mode3D)  
  {   
    var s = document.createElement("iframe");      
    s.id = sid;      
    s.frameBorder = "0";      
    s.style.position = "absolute";      
    s.style.zIndex = "1";      
    s.style.top  = el.offsetTop;      
    s.style.left = el.offsetLeft;      
    s.width  = el.offsetWidth;      
    s.height = el.offsetHeight;
    s.scrolling="no";
    s.className="Shim";
    el.shimElement = s;      
    el.parentNode.insertBefore(s, el);   
  }    
}
function RemoveShim(sid) //remove iframe shim      
{             
  var msh = document.getElementById(sid);     
  if (msh!=null) msh.parentNode.removeChild(msh);      
  msh = null;     
} 

function ModeChange2()
{
    if (map.GetMapMode() == VEMapMode.Mode3D)  
    {
        //map.AttachEvent("onchangeview", OnChangeView);
        UseCustomPopup(false);
        if (_custom_popup_created) HidePopup();
    }
    else
    {
        //map.DetachEvent("onchangeview", OnChangeView);
        UseCustomPopup(true);
    }
    if (map.GetMapMode() != current_mode)
    {
        current_mode = map.GetMapMode();
        Restart(2500);
    }
}
function ModeChange() //Change from 2d to 3d etc
{
  if (map.GetMapMode() == VEMapMode.Mode3D)   
  {
    //AddShim(document.getElementById("MenuPanel"),"MenuPanelShim");
    //AddShim(document.getElementById("NewTwitters"),"NewTwittersShim");
    //AddShim(document.getElementById("MessagePanel"),"MessagePanelShim");
    //AddShim(document.getElementById("MessagePanel2"),"MessagePanel2Shim");
    //AddShim(document.getElementById("MessagePanel3"),"MessagePanel3Shim");
    //AddShim(document.getElementById("DatePanel"),"DatePanelShim");
    //AddShim(document.getElementById("Logo"), "LogoShim");
    //AddShim(document.getElementById("ExpandCollapsePanel"), "ExpandCollapsePanelShim");
    //AddShim(document.getElementById("CollapsibleMenu"), "CollapsibleMenuShim");
    //AddShim(document.getElementById("SearchByTimeBox"), "SearchByTimeBoxShim");
    AddShim(document.getElementById("TwitterList"), "TwitterListShim");
    AddShim(document.getElementById("Messenger"), "MessengerShim");
    
  }else
  {
    //RemoveShim("MenuPanelShim");
    //RemoveShim("NewTwittersShim");
    //RemoveShim("MessagePanelShim");
    //RemoveShim("MessagePanel2Shim");
    //RemoveShim("MessagePanel3Shim");
    //RemoveShim("DatePanelShim");
    //RemoveShim("LogoShim");
    //RemoveShim("ExpandCollapsePanelShim");
    //RemoveShim("CollapsibleMenuShim");
    //RemoveShim("SearchByTimeBoxShim");
    RemoveShim("TwitterListShim");
    RemoveShim("MessengerShim");
  }  
}  

function MapResize() //resize
{
    if (map != null)
    {           
        if( typeof( window.innerWidth ) == 'number' )
        {
            mWidth = window.innerWidth;
            mHeight = window.innerHeight;
            //Non-IE
            map.Resize(window.innerWidth,window.innerHeight);
        } 
        else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
        {
            mWidth = document.documentElement.clientWidth;
            mHeight = document.documentElement.clientHeight;
            //IE 6+ in 'standards compliant mode'
            map.Resize(document.documentElement.clientWidth,document.documentElement.clientHeight);
        }
    }
}

var twitter_by_time = false;

// ------------------------------------------
//  Get Twitter Messages using ID criteria
//  - use Web Service
//  - obtain JSON objects
// ------------------------------------------
var get_new_twitters_timer = null;
function GetNewTwitterMessages(delay, id)
{ 
    if (twitter_by_time == false)
    {
        get_new_twitters_timer = setTimeout("Service.GetTwitterMessagesAfterID(" + id + ", 20, OnGetNewTwitterMessages_Succeeded, OnGetNewTwitterMessages_Failed);", delay);
        //get_new_twitters_timer = setTimeout("new Ajax.Updater('NewTwitters', 'TwitterMessages.aspx?id=" + id + "', {asynchronous:true, evalScripts:true})", delay);
    }
    else
    {
        twitter_by_time = false;
        GetNewTwitterMessagesByTime(100);
    }
    
}

// ------------------------------------------

// ------------------------------------------
//  Get Twitter Messages using Time criteria
//  - use Web Service
//  - obtain JSON objects
// ------------------------------------------
var get_new_twitters_by_time_timer = null;
function GetNewTwitterMessagesByTime(delay)
{ 
    get_new_twitters_by_time_timer = setTimeout("Service.GetTwitterMessagesSince("+ t_day + "," + t_hour + "," + t_minute + ", 0, 30, OnGetNewTwitterMessages_Succeeded, OnGetNewTwitterMessages_Failed);", delay);
    
    //get_new_twitters_by_time_timer = setTimeout("new Ajax.Updater('NewTwitters', 'TwitterMessages.aspx?day=" + t_day + "&hr=" + t_hour + "&min=" + t_minute + "', {asynchronous:true, evalScripts:true})", delay);
    
    UpdateTwitteringSinceTime(t_day,t_hour,t_minute);
}

// ------------------------------------------
//  Get Twitter Messages using Time criteria 
//  Used the app is resumed from idling state 
//  e.g. no new messages or backend server is down.
//  - use Web Service
//  - obtain JSON objects
// ------------------------------------------
var get_new_twitters_by_time_remedy_timer = null;
function GetNewTwitterMessagesByTimeRemedy(delay, day, hour, minute, second)
{ 
    if (twitter_by_time == false)
    {
        get_new_twitters_by_time_timer = setTimeout("Service.GetTwitterMessagesSince("+ day + "," + hour + "," + minute + "," + second + ", 30, OnGetNewTwitterMessages_Succeeded, OnGetNewTwitterMessages_Failed);", delay);
        //get_new_twitters_by_time_remedy_timer = setTimeout("new Ajax.Updater('NewTwitters', 'TwitterMessages.aspx?day=" + day + "&hr=" + hour + "&min=" + minute + "&sec=" + second + "', {asynchronous:true, evalScripts:true})", delay);
    }
    else
    {
        twitter_by_time = false;
        GetNewTwitterMessagesByTime(100);
    }
}

// --------------------------------------------
//  Web Service Handlers common for functions:
//      - GetNewTwitterMessages
//      - GetNewTwitterMessagesByTime
//      - GetNewTwitterMessagesByTimeRemedy
// --------------------------------------------
function OnGetNewTwitterMessages_Succeeded(results, eventArgs)
{
    // store the array of JSON twitter messages locally
    new_twitters = results;
    current_twitter_index = 0;
    // if there is new twitter, set the local variable of last_twitter_id to be the ID of the newest feteched twitter message.
    var twitter_message_msg = '';
    if (results) {
                     if (results.length > 0) { last_twitter_id = results[results.length - 1].ID; twitter_message_msg = results.length + ' new Twitter Messages'; }
                     else { twitter_message_msg = "Please wait while TwitterEarth is downloading more messages ... <br />Don't want to wait? Why not 'Search' for past messages!"; }
                 }
    // update message counters, newest/oldest message time
    SetTwitterMessageCounter(twitter_message_msg);
    Service.GetNewestTwitterMessageRelativeDate(OnGetNewestTwitterMessageRelativeDate_Succeeded, OnGetNewestTwitterMessageRelativeDate_Failed);
    Service.GetOldestTwitterMessageRelativeDate(OnGetOldestTwitterMessageRelativeDate_Succeeded, OnGetOldestTwitterMessageRelativeDate_Failed);
    setTimeout('DisplayTwitters();', 1000);
}

function OnGetNewTwitterMessages_Failed(error)
{
    alert('Get New Twitter Messages Error: TODO:: Need to implement error handling!');
}

// -----------------------------------------

// -----------------------------------------
//  Prepare to download twitter messages that
//  match the specified time criteria.
// -----------------------------------------
var t_minute = 0;
var t_hour = 0;
var t_day = 0;
function ScheduleToGetNewTwitterMessagesByTime()
{
    twitter_by_time = true;
    var formref = document.form1;
    var day_str = formref.DayText.value;
    var hour_str = formref.HourText.value;
    var minute_str = formref.MinText.value;
    var day = parseInt(day_str);
    var hour = parseInt(hour_str);
    var minute = parseInt(minute_str);
    var temp_m = (day * 24 * 60) + (hour * 60) + minute;
    t_minute = temp_m % 60; 
    var temp_h = (temp_m - t_minute) / 60;
    t_hour = (temp_h % 24);
    t_day = (temp_h - t_hour) / 24;
    
    RestartOnSearchByTime(1000);
}

// free up existing threads e.g. timer
// and download twitters that match the specified time criteria
function RestartOnSearchByTime(delay)
{
    _focusMapPostAction = false;
    if (_DeleteLastPinTimer) { clearTimeout(_DeleteLastPinTimer); _DeleteLastPinTimer = null; }
    if (_PostPlacePinTimer) { clearTimeout(_PostPlacePinTimer); _PostPlacePinTimer = null; }
    if (countdown_timer) { clearTimeout(countdown_timer); countdown_timer = null; }
    
    if (!_keep_messages) map.DeleteAllPushpins();
    twitter_by_time = false;
    if (get_new_twitters_timer) { clearTimeout(get_new_twitters_timer); get_new_twitters_timer = null; }
    if (get_new_twitters_by_time_timer) { clearTimeout(get_new_twitters_by_time_timer); get_new_twitters_by_time_timer = null; }
    if (get_new_twitters_by_time_remedy_timer) { clearTimeout(get_new_twitters_by_time_remedy_timer); get_new_twitters_by_time_remedy_timer = null; }
    GetNewTwitterMessagesByTime(delay);
}

// ----------------------------------------

var last_twitter_id = -1;
var new_twitters = null;
var current_twitter_index = 0;

function DisplayTwitters()
{   
    if (new_twitters)
    {
        if (current_twitter_index < new_twitters.length)
        {
            var ct = new_twitters[current_twitter_index];
            AddPin(ct.Latitude, ct.Longitude, ct.Location, ct.ScreenName, ct.Text, ct.ProfileImageURL, ct.RelativeCreatedAt);
            //AddPin(ct[1], ct[2], ct[3], ct[4], ct[5], ct[6], ct[7]);
        }
        else
        {
            GetNewTwitterMessages(1000, last_twitter_id);
        }
    }
}

function AddPin(lat, longt, location_name, screen_name, text, image_url, created_at)      
{   
     FocusMap(lat, longt, location_name, screen_name, text, image_url, created_at);      
}
function PlacePin(lat, longt, location_name, screen_name, text, image_url, created_at)      
{      
    var loc = new VELatLong(lat, longt);
//    var details = '<img src="' + image_url + 
//                            '"><br><div style="text-align:left; text-shadow:LightGreen;">'+ unescape(text) + '</div>' +
//                            '<br><br>Location:<br><center><i>' + 
//                            unescape(location_name) + 
//                            '</i></center><br>Created At:<br><center>' + 
//                            created_at + 
//                            '</center>' + //</font>' +
//                            '<br><br><div id="' + pinID + '_timer" align=right style="font-style:italic;"></div>';
    var details = '';
    if (map.GetMapMode() == VEMapMode.Mode3D)
    {
        details = '<br/><br/><center><img src="' + image_url + 
                            '"><br><div style="text-align:center; text-shadow:LightGreen;">'+ unescape(text) + '</div>' +
                            '<br><br>&nbsp;&nbsp;Location:<br><center><i>' + 
                            unescape(location_name) + 
                            '</i></center><br>&nbsp;&nbsp;Created At:<br><center>' + 
                            created_at + 
                            '</center>' + //</font>' +
                            '<br><br><div id="' + pinID + '_timer" align=center style="font-style:italic;"></div></center>';
    }
    else
    {
        details = '<table style="position:relative; width:100%; text-align:center;">' +
                    '<tr><td colspan="3">&nbsp;</td></tr>' +
                    '<tr><td width="15%"></td><td>' + screen_name + '</td><td width="15%"></td></tr>' +
                    '<tr><td width="15%"></td><td><img src="' + image_url + '"/></td><td width="15%"></td></tr>' +
                    '<tr><td width="15%"></td><td>' + unescape(text) + '</td><td width="15%"></td></tr>' +
                    '<tr><td colspan="3">&nbsp;</td></tr>' +
                    '<tr><td width="15%"></td><td>Location:</td><td width="15%"></td></tr>' +
                    '<tr><td width="15%"></td><td>' + unescape(location_name) + '</td><td width="15%"></td></tr>' +
                    '<tr><td colspan="3">&nbsp;</td></tr>' +
                    '<tr><td width="15%"></td><td>Created At:</td><td width="15%"></td></tr>' +
                    '<tr><td width="15%"></td><td>' + created_at + '</td><td width="15%"></td></tr>' +
                    '<tr><td colspan="3">&nbsp;</td></tr>' +
                    '<tr><td width="15%"></td><td><div id="' + pinID + '_timer" style="font-style:italic;"></div></td><td width="15%"></td></tr>' +
                  '</table>';
    }
    var pin = new VEPushpin(               
                            pinID,            
                            loc,            
                            image_url,                
                            unescape(screen_name),                
                             details,              
                             'iconStyle',               
                             'titleStyle',               
                             'detailsStyle'           
                             ); 
     map.AddPushpin(pin);
     pinID++;
     
     AddToTwitterList(location_name, screen_name, text, image_url, created_at);
}

var _DeleteLastPinTimer = null;
function PostPlacePin()
{
     var pobj = document.getElementById((pinID-1) + "_" + map.GUID);
     if (pobj)
     {
        pobj.onmouseover();
        CountDown((pinID-1), (speed/1000));
     }
     _DeleteLastPinTimer = setTimeout('DeleteLastPin(1);', speed); //5000);
     current_twitter_index++;
}


function DeleteLastPin(next)
{
    if (map.GetMapMode() == VEMapMode.Mode2D) HidePopup();
    if (!_keep_messages)
    {
        var pobj = document.getElementById((pinID-1) + '_' + map.GUID); 
        if (pobj) 
        {
            pobj.onmouseout();
            map.DeletePushpin(pinID-1);
        }
        else 
        {
            try
            {
                map.DeleteAllPushpin();
            } catch (e)
            {
            } 
        }
    }
    if (next == 1)
    {
        DecrementTwitterMessageCounter();
        DisplayTwitters();
    }
}

// ------------------------------------------
//  Update TwitterMessageCounter div content
// ------------------------------------------
function DecrementTwitterMessageCounter()
{
    var tmc = document.getElementById('TwitterMessageCounter');
    if (tmc)
    {
        var str = tmc.innerHTML;
        var sarray = str.split(" ");
        str = (sarray.length > 1) ? sarray[0] : "1";
        var num = parseInt(str);
        tmc.innerHTML = (num > 1) ? (num-1 + ' new Twitter Messages') : 'Retrieving more Twitter Messsage';
    }
}

function SetTwitterMessageCounter(msg)
{
    SetHTMLElementContent('TwitterMessageCounter', msg);
}

// --------------------------------------------------------
//  Update the Newest/OldestTwitterMessageTime div content.
//  This section also contains handlers for calling web
//  services of GetNewestTwitterMessageRelativeDate ... etc.
// --------------------------------------------------------
function SetNewestTwitterMessageTime(msg)
{   
    SetHTMLElementContent('NewestTwitterMessageTime', msg);
}

function SetOldestTwitterMessageTime(msg)
{
    SetHTMLElementContent('OldestTwitterMessageTime', msg);
}

function OnGetNewestTwitterMessageRelativeDate_Succeeded(results, eventArgs)
{
    if (results)    SetNewestTwitterMessageTime(results);
    else SetNewestTwitterMessageTime('Information Currently Unavailable');
} 

function OnGetNewestTwitterMessageRelativeDate_Failed(error)
{
    alert('GetNewestTwitterMessageRelativeDate Error: TODO:: Need to implement error handling!');
}

function OnGetOldestTwitterMessageRelativeDate_Succeeded(results, eventArgs)
{
    if (results)    SetOldestTwitterMessageTime(results);
    else SetOldestTwitterMessageTime('Information Currently Unavailable');
} 

function OnGetOldestTwitterMessageRelativeDate_Failed(error)
{
    alert('GetOldestTwitterMessageRelativeDate Error: TODO:: Need to implement error handling!');
}

// -------------------------------------------
function GetCurrentTime()
{
    var d = new Date();
    return d.getDate();
}

function UpdateTwitteringSinceTime(day,hr, min)
{
    var now = new Date();
    var since = now;
    since.setHours(now.getHours()-(hr + day*24));
    since.setMinutes(now.getMinutes()-min);
    var ampm = "AM";
    var hour = since.getHours();
    if (hour >= 12)
    {
        ampm = "PM";
        if (hour > 12)
            hour = hour % 12;
    }
    
    document.getElementById("TwitteringSinceTime").innerText = hour  + ":" + since.getMinutes() + ampm + " " + since.toLocaleDateString();
}

// ----------------------------------------------------------
//  Generic Function - used to update the content of
//  a specified HTML element. The HTML element is identified
//  by its id e.g. "TwitterMessageCounter", 
//  "OldestTwitterMessageTime", "NewestTwitterMessageTime".
// ----------------------------------------------------------
function SetHTMLElementContent(html_id, message)
{
    var de = document.getElementById(html_id);
    if (de) de.innerText = message;
}

// ----------------------------------------------------------

var _focusMapPostAction = null;
var _PostPlacePinTimer = null;
function OnChangeView()
{
    if (map.GetZoomLevel() != current_zoom_level)
    {
        current_zoom_level = map.GetZoomLevel();
        Restart(1000);
    }
    else if (_focusMapPostAction)
    {
        _focusMapPostAction = false;
        PlacePin(_lat,_longt, _location_name, _screen_name, _text, _image_url, _created_at);
        _PostPlacePinTimer = setTimeout('PostPlacePin();', 850);
    }
}

var _lat, _longt, _location_name, _screen_name, _text, _image_url, _created_at;
function FocusMap(lat, longt, location_name, screen_name, text, image_url, created_at)
{
    if (map)
    {
        _focusMapPostAction = true;
        //PlacePin(lat,longt, location_name, screen_name, text, image_url, created_at);
        _lat = lat;
        _longt = longt;
        _location_name = location_name;
        _screen_name = screen_name;
        _text = text;
        _image_url = image_url;
        _created_at = created_at;
     
        var current_center = map.GetCenter();
        if ( Math.abs(current_center.Latitude - lat) <= 0.08 )
        {
            if ( Math.abs(current_center.Longitude - longt) <= 0.08 )
            {    
                OnChangeView();
            }
            else
            {
                map.SetCenter(new VELatLong(lat, longt));
            }
        }
        else
        {
            if ((map.GetMapMode() == VEMapMode.Mode3D) || (map.GetZoomLevel() > 2))
            {
                map.SetCenter(new VELatLong(lat, longt));
             }
             else
             {
                OnChangeView();
             }
        }
    }
}

function Restart(delay)
{
    _focusMapPostAction = false;
    if (_DeleteLastPinTimer) { clearTimeout(_DeleteLastPinTimer); _DeleteLastPinTimer = null; }
    if (_PostPlacePinTimer) { clearTimeout(_PostPlacePinTimer); _PostPlacePinTimer = null; }
    if (countdown_timer) { clearTimeout(countdown_timer); countdown_timer = null; }
    if (new_twitters)
    {
        var ct = new_twitters[current_twitter_index];
        if (!_keep_messages) map.DeleteAllPushpins();//DeleteLastPin(0);
        GetNewTwitterMessages(delay, ct[0]);
    }
}

var speed = 5000;
function ChangeSpeed(what)
{
    speed = (parseInt(what.value) * 1000);
}

var countdown_timer = null;
function CountDown(id_of_pin, remaining_second)
{
    if (remaining_second > 0)
    {
        var p_timer = document.getElementById(id_of_pin + '_timer');
        if (p_timer)
        {
            p_timer.innerText = 'Closing in ' + remaining_second;
            countdown_timer = setTimeout('CountDown(' + id_of_pin + ',' + (remaining_second-1) +')',1000); 
        }
    }
    else
    {
        var p_timer = document.getElementById(id_of_pin + '_timer');
        if (p_timer) p_timer.innerText =  ' ';
    }
}

var s_day = 0;
var s_hour = 0;
var s_min = 0;
function UpdateTotalTimeDay(what)
{
    s_day = parseInt(what.value);
    UpdateTotalTime();
}
function UpdateTotalTimeHour(what)
{
    s_hour = parseInt(what.value);
    UpdateTotalTime();
}
function UpdateTotalTimeMinute(what)
{
    s_min = parseInt(what.value);
    UpdateTotalTime();
}

function UpdateTotalTime()
{
    var temp_m = (s_day * 24 * 60) + (s_hour * 60) + s_min;
    var c_min = temp_m % 60;
    var temp_h = (temp_m - c_min) / 60;
    var c_hour = temp_h % 24;
    var c_day = (temp_h - c_hour) / 24;
    
    var total_time = document.getElementById("TotalTime");
    if (total_time) total_time.innerText = "Display Twitters from " + c_day + " day " + c_hour + " hr " + c_min + " min ago.";
}

// -------------------------------------------
//  Twitter Message history related functions
// -------------------------------------------

var _keep_messages = false;
function KeepOrDeleteMessages(what)
{
    _keep_messages = what.checked;
    if(!_keep_messages)
        map.DeleteAllPushpins();
}

function AddToTwitterList(location_name, screen_name, text, image_url, created_at)
{
    if (_keep_message_history)
    {
        if  (_keep_updating_message_history)
        {   
                                
            var twitter_details = document.getElementById("TwitterDetails");
            
            var details = '<div align="left">' + screen_name + '<br/><img src="' + image_url + '"></div><br/>';
            details += '<div style="text-align:left; text-shadow:LightGreen;">' + unescape(text) + '</div><br/><br/>';
            details += '<div style="text-align:left;">Location:<br/></div>';
            details += '<center><i>' + unescape(location_name) + '</i></center><br/>';
            details += '<div style="text-align:left;">Created At:<br/></div>';
            details += '<center>' + created_at + '</center>';
            
            twitter_details.innerHTML = details + "<BR />" + twitter_details.innerHTML;
            
            _message_history_size++;
            var message_history_counter = document.getElementById("MessageHistoryCounter");
            message_history_counter.innerHTML = "History Size: " + _message_history_size;
        }
    }
}

var _keep_message_history = true;
var _message_history_size = 0;
function KeepOrDeleteMessageHistory(what)
{
    _keep_message_history = what.checked;
    if (!_keep_message_history)
    {
        var twitter_details = document.getElementById("TwitterDetails");
        twitter_details.removeChild(twitter_details.firstChild);
        twitter_details.innerHTML = ""; 
        _message_history_size = 0;
        var message_history_counter = document.getElementById("MessageHistoryCounter");
        message_history_counter.innerHTML = "History Size: " + _message_history_size;
    }
}

var _keep_updating_message_history = true;
function KeepUpdatingMessageHistory(what)
{
    _keep_updating_message_history = what.checked;
//    alert('_keep_updating_message_history ' + _keep_updating_message_history);
}


// -------------------------------------------
//  Popup related functions
// -------------------------------------------
function CreateCustomPopup()
{
    var popupMasterDiv=document.createElement("div");
    popupMasterDiv.id="Popup";
    popupMasterDiv.style.display="none";
    popupMasterDiv.className="PopupMaster";
    
    map.AddControl(popupMasterDiv);
    var popupPointerDiv=document.createElement("div");
    popupPointerDiv.id="PopupPointer";
    
    popupMasterDiv.appendChild(popupPointerDiv);
    var popupContentDiv=document.createElement("div");
    popupContentDiv.id="PopupContent";
    
    popupMasterDiv.appendChild(popupContentDiv);
    
    var popupLoadingDiv=document.createElement("div");
    popupLoadingDiv.id="PopupLoading";
    popupLoadingDiv.className="PopupLoading";
    popupMasterDiv.appendChild(popupLoadingDiv);
    var popupCloseDiv=document.createElement("div");
    popupCloseDiv.id="PopupClose";
    
    popupCloseDiv.attachEvent('onclick', new Function("HidePopup()"));
    popupMasterDiv.appendChild(popupCloseDiv);
    
    if (IE6mode)
    {
        popupContentDiv.className="IE6PopupContent";
        popupCloseDiv.className="IE6PopupClose";
        popupPointerDiv.className="IE6PopupPointerTL";
    }
    else
    {
        popupContentDiv.style.position = "absolute";
        popupContentDiv.style.font= "11px Tahoma"; 
        popupContentDiv.style.color="#0061A0";
        popupContentDiv.style.backgroundImage="url(Image/Bubble2.png)";
        popupContentDiv.style.backgroundRepeat="no-repeat";
        popupContentDiv.style.padding="10px"; 
        popupContentDiv.style.zIndex="1"; 
        //if (!IEmode)
        //    popupContentDiv.style.width="297px!important"; 
        //else
            popupContentDiv.style.width="400px"; 
        
        //if (!IEmode)
        //    popupContentDiv.style.height="auto!important"; 
        //else
            popupContentDiv.style.height="280px"; 
        //popupContentDiv.style.height="auto";
        popupContentDiv.style.minHeight="280px";
        popupContentDiv.textAlign="center"; 
        popupContentDiv.style.overflow="auto";
        //popupContentDiv.className="PopupContent";
        
        popupCloseDiv.style.position="absolute"; 
        popupCloseDiv.style.height="80px"; 
        popupCloseDiv.style.width="103px"; 
        popupCloseDiv.style.font="bold 10px arial"; 
        popupCloseDiv.style.textAlign="center"; 
        popupCloseDiv.style.cursor="pointer";
        popupCloseDiv.style.background= "url(Image/BubbleClose3.png) no-repeat";
        popupCloseDiv.style.zIndex="100";
        //popupCloseDiv.className="PopupClose";
        popupPointerDiv.style.position="absolute";
        popupPointerDiv.style.background= "url(Image/BubbleBeakTL.png) no-repeat"; 
        popupPointerDiv.style.width="54px"; 
        popupPointerDiv.style.height="58px"; 
        popupPointerDiv.style.zIndex="100"; 
    }
    
    _custom_popup_created = true;
}


function HidePopup()
{
    var popupMasterDiv = document.getElementById("Popup");
    if(popupMasterDiv!=null)
    {
        popupMasterDiv.style.display="none"
    }
}

function PinHover(x,y,title,details)
{
    var y_margin_offset = 15 + 30;
    if (_banner_expanded) y_margin_offset += 76;
    
    //var ID= parseInt(title); //details;
    var popupContentDiv = document.getElementById("PopupContent");
    var popupMasterDiv = document.getElementById("Popup");
    var popupPointerDiv = document.getElementById("PopupPointer");
    var popupLoadingDiv = document.getElementById("PopupLoading");
    var popupCloseDiv = document.getElementById("PopupClose");

    PhotoPopupGUIDs=new Array();
    var classPrefix="";
    var classSuffix="";
//    if(IE6mode)
//    {
//        classPrefix="IE6"
//    }
    var classSuffix="";
    var PopupWidth=400; //279; //300;
    var PopupHeight=280;
    var PopupPointerWidth=54;
    var PopupPointerHeight=58;
    var PopupLoadingWidth=64;
    var PopupLoadingHeight=64;
    var PopupCloseWidth=103;
    var PopupCloseHeight=80;
    var mapX=x-map.GetLeft();
    var mapY=y-map.GetTop();
    if(mapY<=(mHeight/2))
    {
        classSuffix="T"
        popupContentDiv.style.top=0+"px";
        popupMasterDiv.style.top= y_margin_offset + (y-PopupPointerHeight)+"px";
        popupLoadingDiv.style.top=(PopupHeight-PopupLoadingHeight)/2+"px";
        popupPointerDiv.style.top = 0+"px";
        popupCloseDiv.style.top=2+"px";
    }
    else
    {
        classSuffix="B";
        popupContentDiv.style.top=PopupPointerHeight+"px";
        popupMasterDiv.style.top= y_margin_offset + (y-PopupHeight)+"px";
        popupLoadingDiv.style.top=(PopupHeight-PopupLoadingHeight)/2+"px";
        popupPointerDiv.style.top=(PopupHeight)+"px";
        popupCloseDiv.style.top=(PopupPointerHeight+2)+"px";
    }
    if(mapX<=(mWidth/2))
    {
        classSuffix+="L";
        popupContentDiv.style.left=PopupPointerWidth+"px";
        popupMasterDiv.style.left=x+"px";
        popupLoadingDiv.style.left= PopupPointerWidth + ((PopupWidth - PopupLoadingWidth) / 2) + "px"; //(((PopupWidth-PopupPointerWidth)-PopupLoadingWidth)/2+PopupPointerWidth)+"px";
        popupPointerDiv.style.left = 0+"px";
        popupCloseDiv.style.left=(PopupPointerWidth+PopupWidth-PopupCloseWidth)+"px";
    }
    else
    {
        classSuffix+="R";

        popupContentDiv.style.left=0+"px";
        popupMasterDiv.style.left= (x - PopupWidth - PopupPointerWidth)+"px";
        popupLoadingDiv.style.left= ((PopupWidth-PopupPointerWidth) / 2) + "px"; //((PopupWidth-PopupLoadingWidth)/2)+"px";
        popupPointerDiv.style.left = (PopupWidth - 1) +"px";
        popupCloseDiv.style.left=(PopupWidth-PopupCloseWidth)+"px";
    }
    
    if (IE6mode)
    {
        classPrefix = "IE6";
        popupPointerDiv.className=classPrefix+"PopupPointer"+classSuffix;
    }
    else
    {
        popupPointerDiv.style.background = "url(Image/BubbleBeak" + classSuffix + ".png) no-repeat";
    }
    popupMasterDiv.style.display="block";
    popupContentDiv.innerHTML = details;
}

// -----------------------------------

function CheckIEVersion()
{
    if (typeof( window.innerWidth ) == 'number')
    {
        IEmode = false;
        IE6mode=false;
    }
    else
    {
        IEmode = true;
        var version=0
        if(navigator.appVersion.indexOf("MSIE")!=-1){
        temp=navigator.appVersion.split("MSIE")
        version=parseFloat(temp[1])}
        if(version>=5.5&&version<7)
        {
            IE6mode=true
        }
    }
}

var _banner_expanded = true;
function ExpandCollapseBanner()
{
    _banner_expanded = !_banner_expanded;
}