//
// App.js
//
// Application-level scripts
//

var ActiveRequests = {};

var openThumbnailDiv = null;

function GetApplicationRoot()
{
    var root = o("ApplicationRoot");
    
    if( root != null )
        return root.value.replace(/\/$/, "");
    else
        return "";
}

function HideElement(id)
{
    o(id).style.visibility="hidden";
}

function ShowElement(id)
{
    o(id).style.visibility="visible";
}

function CreateRequest( name, url, args, complete )
{
    var req = new Object();
    
    req.Name = name;
    req.Url = url;
    req.Args = args;
    req.OnComplete = complete;
    req.Request = new XMLHttpRequest();
    
    req.Begin = function() {
                    ActiveRequests[this.Name] = this;
                    this.Request.onreadystatechange = this.OnComplete; 
                    this.Request.open("POST", this.Url );
                    this.Request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    this.Request.send(this.Args); 
                }
    
    return req;
}

function OnTagKeyDown(evt)
{
   evt = (evt) ? evt : event;
   var charcode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
   if( charcode == 13 || charcode == 3 )
   {
        AddTag("TagInputTextBox");
        return false; 
   }
   
   return true;
}

function OnSearchKeyDown(evt,buttonId)
{
   evt = (evt) ? evt : event;
   var charcode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
   if( charcode == 13 || charcode == 3 )
   {
        o(buttonId).click();
        return false; 
   }
   
   return true;
}

function GetElementPosition(id)
{
    var elem = o(id);
    var top = 0;
    var left = 0;
    while(elem) 
    {
    
        left+=elem.offsetLeft;
        top+=elem.offsetTop;
        elem = elem.offsetParent;
    }
    if( navigator.userAgent.indexOf("Mac") != -1 &&
        typeof document.body.leftMargin != "undefined") 
    {
        left += document.body.leftMargin;
        top += document.body.topMargin;
    }
        
    return {left:left, top:top};
}

function GetElementScreenPosition(id)
{
    var pos = GetElementPosition(id);
    
    if( IsIE() )
    {
        pos.left = pos.left + window.screenLeft - document.documentElement.scrollLeft;
        pos.top = pos.top + window.screenTop - document.documentElement.scrollTop;
    }
    else
    {
        pos.left = pos.left + window.screenX - window.pageXOffset;
        pos.top = pos.top + window.screenY - window.pageYOffset;
    }
    
    return pos;
    
}

function BlockEnter(evt)
{
   evt = (evt) ? evt : event;
   var charcode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
   if( charcode == 13 || charcode == 3 )
   {
        return false; 
   }
   
   return true;
}

var divSections = [ "trackCommentsDiv", "trackWikiDiv", "trackViewsDiv", "trackCorrsDiv", "trackBlogDiv", "trackGroupsDiv" ];
var divSectionLinks = [ "CommentsSectionLink", "WikiSectionLink", "ViewsSectionLink", "CorrSectionLink", "BlogSectionLink", "GroupsSectionLink" ];

function HideSections() 
{
    for( var i=0; i<divSections.length; i++)
    {
        o(divSections[i]).style.display = "none"; 
        o(divSectionLinks[i]).className = "trc-aSectionInactive";
    }
}

function ShowSection(index)
{
    HideSections();
    o(divSections[index]).style.display = "block";
    o(divSectionLinks[index]).className = "trc-aSectionActive";
}

function SubmitAddBookmark( trackId )
{
    var url = GetApplicationRoot() + "/MiscPages/ManageTracks.ashx" + location.search;
    var args = "addbk=" + encodeURIComponent(trackId+"");
    
    var req = CreateRequest( "AddBookmark", url, args, AddBookmarkComplete );
    req.Begin();
}

function AddBookmarkComplete()
{
    var req = ActiveRequests["AddBookmark"].Request;
    
    if( req.readyState == 4 && 
        req.status == 200 ) 
    {
        alert("A bookmark has been added to your 'My Tracks' page.");
    }
}

function UpdateTrackDesc( current, update, textBoxId )
{
    var updateDiv = o(update);
    var currentDiv = o(current);
    var textBox = o(textBoxId);
    
    if( updateDiv.style.display == "inline" )
        return;
    
    currentDiv.style.display = "none";
    updateDiv.style.display = "inline";
    
    if( currentDiv.innerHTML != undefined)
    { 
        textBox.value = currentDiv.innerHTML;
    }
}

function ToggleTrackDesc( descId, buttonId )
{
    var button = o(buttonId);
    var div = o(descId);
    
    if( button.innerHTML == "[Hide]" )
    {
        div.style.display = "none";
        button.innerHTML = "[Show]";
    }
    else
    {
        div.style.display = "inline";
        button.innerHTML = "[Hide]";
    }   
}

function CancelTrackDescUpdate(current, update)
{
    var updateDiv = o(update);
    var currentDiv = o(current);
    
    updateDiv.style.display = "none";
    currentDiv.style.display = "inline";
}

function ShowThumb(source,thumbId,trackId) 
{
    if( openThumbnailDiv != null &&
        openThumbnailDiv.style.display == "block" )
        openThumbnailDiv.style.display = "none";
    
    var divId = "thumb" + thumbId;
    
    var pos = GetElementPosition(source.id);
   
    var div = o(divId);
    
    div.style.display = "block"; 
    
    openThumbnailDiv = div;
    
    div.style.left = pos.left + "px";
    div.style.top = pos.top + "px";
    
    var img = o("thumbImg"+thumbId);
    
    if( img.src.indexOf('track') < 0 )
        img.src = GetApplicationRoot()+"/images/timeserieschart.aspx?t="+trackId+"&s=0";
}

function HideThumb(source,thumbIndex)
{
    var divId = "thumb" + thumbIndex;
    if( o(divId).style.display == "block" )
        o(divId).style.display = "none";
}

function CheckIllegalMarkup(text)
{
    var pattern = /<[^>]+>[^<]*<[^>]+>/;
    var result = text.match(pattern);
    return (result != null);
}

function TogglePlotHelp()
{
    var div = o("PlotHelpDiv");
    
    if( div.style.display == "block" )
    {
        div.style.display="none";
    } else
    {
        div.style.display="block";
    }
}

function GetTracksForTag( tag, onComplete )
{
    var url = GetApplicationRoot() + "/MiscPages/ManageTracks.ashx" + location.search;
    var args = "tag=" + encodeURIComponent(tag) + "&user=" + encodeURIComponent(tag) + "&id=" + encodeURIComponent(tag);
    
    var req = CreateRequest( "GetTracksForTag", url, args, onComplete );
    req.Begin();
}

function GetTracksForTagComplete()
{
    AddTracksToListBox( "ctl00_cphMainContent_lbxAllTracks" );
    
    var req = ActiveRequests["GetTracksForTag"].Request;
    
    if( req.readyState == 4 )
    {
        o("FindTracksButton").disabled = "";
    }
}

function GetOverlayTracksForTagComplete()
{
    AddTracksToListBox( "PlotWindowTrackList" );
    
    var req = ActiveRequests["GetTracksForTag"].Request;
    
    if( req.readyState == 4 )
    {
        o("FindOverlayTracksButton").disabled = "";
    }
}

function AddTracksToListBox( listboxId )
{
    var req = ActiveRequests["GetTracksForTag"].Request;
    
    if( req.readyState == 4 && 
        req.status == 200 ) 
    {
        var doc = req.responseXML;
        
        var elements = doc.getElementsByTagName("track");
        
        var listBox = o(listboxId);
        
        listBox.options.length = 0;
        
        for( var i=0; i<elements.length; i++ )
        {
           var id = elements[i].getAttribute("id");
           var name = elements[i].getAttribute("name");
           var owner = elements[i].getAttribute("owner");   
           
           var opt = new Option( name + " (" + owner + ")", id+"" );
           
           if( IsIE() )
            listBox.add(opt);
           else
            listBox.add(opt,null);
        }
    }
}

function FindTracksByTag()
{
    var tag = o("FindTracksTextBox").value;
    
    if( tag.length > 0 ) 
    {
        HideTrackPreviewImage("CreateTrackPreviewImage");
        
        o("FindTracksButton").disabled = "disabled";
    
        GetTracksForTag( tag, GetTracksForTagComplete );
    }
}

function FindOverlayTracksByTag()
{
    var tag = o("FindOverlayTracksTextBox").value;
    
    if( tag.length > 0 ) 
    {
        o("FindOverlayTracksButton").disabled = "disabled";
        
        GetTracksForTag( tag, GetOverlayTracksForTagComplete );
    }
}

function HideTrackPreviewImage(imgId)
{
    o(imgId).style.display = "none";
}

function SetTrackPreviewImage( imgId, trackId )
{
    var img = o(imgId);
    img.src = GetApplicationRoot() +"/images/white_pixels.gif";
    img.style.display ="";
    img.src = GetApplicationRoot()+"/images/timeserieschart.aspx?t="+trackId+"&s=0";
}

function SourceTracksChanged()
{
   var list = o("ctl00_cphMainContent_lbxAllTracks");
   
   if( list.selectedIndex >= 0 ) 
   {
        var opt = list.options[list.selectedIndex];
        var trackId = parseInt(opt.value);
        
        if( opt.value > 0 )
            SetTrackPreviewImage( "CreateTrackPreviewImage", parseInt(opt.value) );
   }
   
}

function IsGroupTrack()
{
    var el = o("IsGroupTrack");
    if( el == null ) return false;
    else return parseInt(el.value) > 0 ? true : false;
}

function IsCombinedTrack()
{
    var el = o("IsCombinedTrack");
    if( el == null ) return false;
    else return parseInt(el.value) > 0 ? true : false;
}
