//------------------------------------------------------------
// $Id: campopup.js 1539 2007-05-30 00:33:36Z samuel_igc $
// Supports campopup.jsp, cameras.jsp, and index.jsp.
//------------------------------------------------------------

// Globals
// var initialCamId;  // cam id we were called with
// var groupId; // camera group id we are displaying
// var currentDetails;  // current camera group data (xml)


// Fetch list of cams for current user
function ajaxGetUserCams(callback) {
    var ajaxComponent = new Object();
    setAjaxStatusMsg("LOADING MYCAMERAS");

    ajaxComponent.ajaxUpdate = function(request) {
        //alert("AjaxGetuserCams got back " + request.responseText );
        setAjaxStatusMsg("");
        callback(request.responseXML);
    };

    ajaxComponent.handleError = function(request) {
        //alert("Ajax error loading user cameras");
        alert("Ajax error: " + " status " + request.status + ", "
                + request.statusText);
        setAjaxStatusMsg("");
    };

    this.ajaxRequest = null;
    ajaxRequest = new
            AjaxHelper(ajaxComponent, "/accma/cameraFave?action=userCams");
    ajaxRequest.sendRequest();
}


// Get camera's (entire group's) details from WS.
// (camId, groupId, r are passed through)
function ajaxGetCameraDetails(callback, camId, groupId, r)
{
    var ajaxComponent = new Object();
    ajaxComponent.viewer = this;

    ajaxComponent.ajaxUpdate = function(request)
    {
        //alert("Ajax got back " + request.responseText );
        callback(request.responseXML, camId, groupId, r)
    };

    ajaxComponent.handleError = function(request)
    {
        //alert("Ajax error loading camera details");
        alert("Ajax error: " + " status " + request.status + ", "
                + request.statusText);
        //setAjaxStatusMsg("");
    };

    var url = "/accma/cameraFave?action=details";
    if (camId != null)
        url += "&camId=" + camId;
    else
        if (groupId != null)
            url += "&groupId=" + groupId;
        else {
            alert("Ajax error in ajaxGetCameraDetails: no valid params");
            return;
        }
    var ajaxRequest = new AjaxHelper(ajaxComponent, url);
    ajaxRequest.sendRequest();
}


// Returns cam we're supposed to display initially.
// This is either the one we were called with (if given camId)
// or the first valid one in the camera group we were called with.
function determineCurrentCam(details, camId)
{
    if (camId != null) // easy case, just look up that one
    {
        var c = details.getElementsByTagName("camera");
        for (var i = 0; i < c.length; i++) {
            if (c[i].getAttribute("camId") == camId) {
                return c[i];
            }
        }
        alert("Error: current cam doesn't exist"); // Should never see this
    }

    else // Look up first valid one in group
    {
        // Lazy way would be just to take the first element
        // in the list, but the order is indeterminate (xml!).
        // Here we go in clockwise order.
        var c = getCameraDetailsForDirection(details, "N");
        if (c != null)
            return c;

        c = getCameraDetailsForDirection(details, "E");
        if (c != null)
            return c;

        c = getCameraDetailsForDirection(details, "S");
        if (c != null)
            return c;

        c = getCameraDetailsForDirection(details, "W");
        if (c != null)
            return c;

        alert("Error: unable to determine current cam.");
        return null;
    }
}

function redrawCamera(currentCam)
{
    var streamType = currentCam.getAttribute("streamType");
    sizeVideoWrapper(1);

    if(streamType != "Other")
    {
        launchCam(document, currentCam.getAttribute("url"));
    }else
    {
        launchOtherCam(document, currentCam.getAttribute("url"));
    }
}


// Popup one camera 
// (cam + compass format -- user clicked on map icon)
function drawCameraPopup(id, group) {
    var uri = 'campopup.jsp';
    if (id != null)
        uri += "?" + id;
    else
        uri += "?-1";

    if (group != null)
        uri += "&" + group;

    window.open(uri, '_blank',
            "width=414,height=450,scrollbars=0,toolbar=0,"
                    + "titlebar=0,directories=0,menubar=0,resizable=1,status=0");
}


// Return compass element for a given direction
function getCompassElement(dir)
{
    if (dir == "N")
        return document.getElementById("northCam");
    else if (dir == "S")
        return document.getElementById("southCam");
    else if (dir == "E")
            return document.getElementById("eastCam");
        else if (dir == "W")
                return document.getElementById("westCam");
            else if (dir == "ALL")
                    return document.getElementById("allCam");
                else
                    alert("Error in getCompassElement: bad dir " + dir);
}


// Set up the compass
function populateCompass(details, camXml)
{
    // Set them all to grey
    getCompassElement("N").firstChild.className = "off";
    getCompassElement("S").firstChild.className = "off";
    getCompassElement("E").firstChild.className = "off";
    getCompassElement("W").firstChild.className = "off";

    // Whatever directions we have a camera for, turn blue
    if (details != null)
    {
        var c = details.getElementsByTagName("camera");
        for (var i = 0; i < c.length; i++) {
            var direction = c[i].getAttribute("direction");
            if (getCameraDetailsForDirection(details, direction) != null) {
                getCompassElement(direction).firstChild.className = "";
            }
        }

        var e = getCompassElement("ALL");
        if (e != null)
            e.firstChild.className = "";

        // Make the current cam's pointer orange
        if (camXml != null) {
            getCompassElement(camXml.getAttribute("direction"))
                    .firstChild.className = "at";
        }
    }
}


// campopup.jsp: Set the location header (and page title)
function setHeadingText(details)
{
    var s = details.getElementsByTagName("cameraGroup")[0].getAttribute("location");
    document.getElementById("description").innerHTML = s;
    document.title = "Live Camera - " + s;
}


// Return ref to camera details for a given direction
function getCameraDetailsForDirection(details, d)
{
    var c = details.getElementsByTagName("camera");
    for (var i = 0; i < c.length; i++) {
        if ((c[i].getAttribute("direction") == d)
                && (c[i].getAttribute("isDown") != "true"))
            return c[i];
    }
    return null;
}


// Handle user clicks on compass elements
function handleCompassClick(direction)
{
    var camEl = getCameraDetailsForDirection(currentDetails, direction);
    //alert("The url for " + direction + " is " + camEl.getAttribute("url") );
    if (camEl != null) {
        populateCompass(currentDetails, camEl); // make current one orange
        redrawCamera(camEl);
        //sizeVideoWrapper(1);
        //launchCam(document, camEl.getAttribute("url"));
    }
}


// Handle user clicks on ALL compass element
function handleCompassClickAll()
{
    sizeVideoWrapper(4);

    populateCompass(currentDetails);
    getCompassElement("ALL").firstChild.className = "at";

    // Order of camera windows is determined here
    // (NEWS gives diagonal opposites, like compass on a tilt)
    var camEl = getCameraDetailsForDirection(currentDetails, "N");
    if (camEl != null)
       launchAllCam(document, camEl,camEl.getAttribute("url"));
        //redrawCamera(camEl);
        //launchCam(document, camEl.getAttribute("url"));

    camEl = getCameraDetailsForDirection(currentDetails, "E");
    if (camEl != null)
        launchAllCam(document, camEl,camEl.getAttribute("url"));
       // launchCam(document, camEl.getAttribute("url"));

    camEl = getCameraDetailsForDirection(currentDetails, "W");
    if (camEl != null)
        launchAllCam(document, camEl,camEl.getAttribute("url"));
        //launchCam(document, camEl.getAttribute("url"));

    camEl = getCameraDetailsForDirection(currentDetails, "S");
    if (camEl != null)
        launchAllCam(document, camEl,camEl.getAttribute("url"));
        //launchCam(document, camEl.getAttribute("url"));
}


// Resize the window and main DIV for four or one cam views
function sizeVideoWrapper(num)
{
    var vWrapper = document.getElementById('videoWrapper');

    // Remove all subsidiary DIVs
    for (var i = 0; i < vWrapper.childNodes.length;) {
        vWrapper.removeChild(vWrapper.childNodes[i]);
    }


    // Set styles for wrapper DIVs to set their size
    var wrapper = document.getElementById('wrapper');
    var header = document.getElementById('header');
    var footer = document.getElementById('footer');
    var cWrapper = document.getElementById('contentWrapper');
    if (num > 1)
    {
        window.resizeTo(760, 820);
        wrapper.className = 'fourCam';
        header.className = 'fourCam';
        footer.className = 'fourCam';
        cWrapper.className = 'wideContent';
        vWrapper.className = 'wideContent';
    }
    else  // default (num == 1)
    {
        window.resizeTo(400, 470);
        wrapper.className = '';
        header.className = '';
        footer.className = '';
        cWrapper.className = 'content';
        vWrapper.className = 'content';
    }
}

function launchAllCam(doc, camera,url)
{
    var streamType = camera.getAttribute("streamType");

    if(streamType != "Other")
    {
        launchCam(document, url);
    }else
    {
        launchOtherCam(document, url);
    }
}

function launchOtherCam(doc, url)
{
    var vWrapper = doc.getElementById("videoWrapper");
    var element = doc.createElement('div');
    element.className = 'video';
    element.innerHTML = generateIFrame(url);
    vWrapper.appendChild(element);
}

function generateIFrame(url)
{
    var iFrame;

    iFrame = "<iframe style=\"width:360px;height:250px;\" ";
    iFrame += "src = \"" + url + "\"";
    iFrame += "scrolling = \"no\"";
    iFrame += "/>";
    return iFrame;
}
// Launch viewer for current cam
function launchCam(doc, url)
{
    var vWrapper = doc.getElementById("videoWrapper");
    var element = doc.createElement('div');
    element.className = 'video';
    element.innerHTML = generatePlayerHTML(url);
    vWrapper.appendChild(element);
}


// Secret sauce for launching Windows Media in a window
function generatePlayerHTML(uri) {
    var playerHTML =
            '<OBJECT id="WMP" CLASSID="CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95"'
                    + ' TYPE="application/x-oleobject"'
                    + ' HEIGHT="320"'
                    + ' WIDTH="350">'
                    + '<PARAM name="ShowStatusBar" value="1">'
                    + '<PARAM name="ShowAudioControls" value="0">'
                    + '<PARAM name="ShowPositionControls" value="0">'
                    + '<PARAM name="ShowTracker" value="0">'
                    + '<PARAM name="filename" value="' + uri + '">'
                    + '<PARAM name="AutoStart" value="1">'
                    + '<PARAM NAME="EnableContextMenu" VALUE="false">'
                    + '<PARAM name="codebase" value="http://www.microsoft.com/windows/mediaplayer/">'
                    + '<EMBED type="application/x-mplayer2"'
                    + ' name="WMP"'
                    + ' pluginspage="http://www.microsoft.com/windows/mediaplayer/"'
                    + ' SRC="' + uri + '"'
                    + ' width=350'
                    + ' height=320'
                    + ' ShowStatusBar="1"'
                    + ' ShowAudioControls="0"'
                    + ' ShowPositionControls="0"'
                    + ' ShowTracker="0">'
                    + '</EMBED>'
                    + '</OBJECT>';

    return playerHTML;
}


//------------------------------------------------------------
// Support camera icons building and displaying
//------------------------------------------------------------
//var oCameras;  // This has to exist in calling code already

//-----
// parseCameras: build the cameras array from the cam list XML
//-----
function parseCameras(cameraXML)
{
    var cameras = new Array();
    var elements = cameraXML.getElementsByTagName('cameraSummary');
    for (var i = 0; i < elements.length; i++) {
        var summaryId = elements[i].getAttribute('id');
        var longitude = elements[i].getAttribute('long');
        var latitude = elements[i].getAttribute('lat');
        var location = elements[i].getAttribute('location');

        longitude = parseFloat(longitude.replace(',', '.'));
        latitude = parseFloat(latitude.replace(',', '.'));
        // elements are not really cameras but groups so we were really
        // parsing groups not cameras.
        // Now parse the cameras in the group
        // S.D.
        var cameraEntries = new Array();
        var cameraEntryElements =
                elements[i].getElementsByTagName("cameraEntry");
        for (var j = 0; j < cameraEntryElements.length; j++)
        {
            var id = cameraEntryElements[j].getAttribute("id");
            var direction = cameraEntryElements[j].getAttribute("direction");
            var url = cameraEntryElements[j].getAttribute("url");
            cameraEntries[id] = new CameraEntry(id, direction, url);
        }

        // TODO: add new attribs  corridor, mount, streamType
        cameras[id] = new Camera(longitude, latitude, location, summaryId, cameraEntries);
    }

    return cameras;
}


//-----
// getCameras:
// Perform Ajax transaction to get camera list XML
//-----
function getCameras()
{
    var ajaxComponent = new Object();
    ajaxComponent.ajaxUpdate =
    function(request)
    {
        oCameras = parseCameras(request.responseXML);
        //debugger;
        addIcons(oCameras);
    };

    ajaxComponent.handleError =
    function(request)
    {
        alert("Ajax error");
    };

    var ajaxRequest = new AjaxHelper(ajaxComponent,
            '/accma/cameraFave?action=cameraSet');
    ajaxRequest.sendRequest();
}
