/* flickr show generator
 * b.js, version 2.4.1, 2007-01-23
 * copyright 2005-2007 Patrick Quinn-Graham
 *
 * 1.2 added left/right navigation
 * 1.3 added pausing + tidy up
 * 1.4 fixed bug {pause then navigate makes screwy
 * 2.0 added preferences + photo bar
 * 2.1 special release for im.irate.net.nz, 6 photos in bar
 * 2.2 made the changing bar size generic
 * 2.3 changed picture bar to use CSS classes, rather than direct styling
 * 2.4 added ability to set XML endpoint (where to find the flickr proxy)  
 * 2.4.1 
 */
 
// configuration
var kSecs = 20;
var kUsername = "thepatrick";
var kTag = "favourite";
var kPhotosInBar = 10;
var kPhotoSelector = 4;  
var kXmlEndPoint = 'xml';

// runtime
var req;
var passback = "";
var nsid = "";
var photos = null;
var thisPhoto = 0;
var loadInto = 0;
var key = "";
var timerID = null;
var timerRunning = false;
var delay = kSecs * 1000;
var state = 0;
var paused = false;
var size = "";

function setUsername(username) {
    kUsername = username;
}
function setTag(tag) {
    kTag = tag;
}
function setPhotosInBarAndSelector(inBar, selector) {
    kPhotosInBar = inBar;
    kPhotoSelector = selector;  
}
function setXmlEndPoint(url) {
    kXmlEndPoint = url;
}

function loadXMLDoc(url, pathr, passBack) 
{
    passback = passBack;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if(req) {
        req.onreadystatechange = processReqChange;
        req.open("POST", url, true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.send(pathr);    
    } else {
        alert("Hi. This page won't work for you right now. Sorry.");
    }
}

function processReqChange() 
{
    if (req.readyState == 4) {
        if (req.status == 200) {
              response  = req.responseXML.documentElement;        
              eval(passback + '(response)');      
        } else {
            alert("There was a problem retrieving the XML data:\n" 
            + req.statusText);
        }
    }
}

function go(theKey) {
    key = theKey;
	if(kUsername == "pftqg") kUsername == "thepatrick";
    loadXMLDoc(kXmlEndPoint,'key=' + key + '&method=findUser&username=' + kUsername, 'gotUserName');
}

function gotUserName(res) {
    if(res.attributes.getNamedItem("stat").value != "ok") {
        if(res.getElementsByTagName('key')[0].attributes.getNamedItem("invalid").value == "True") {
                  window.location.reload( true );
        }
    } else {    
        nsid = res.getElementsByTagName('user')[0].attributes.getNamedItem("nsid").value;
        loadXMLDoc(kXmlEndPoint + '?key=' + key + '&method=findPhotos&nsid=' + nsid + '&tag=' + kTag, null, 'gotPhotos');
    }
}

function gotPhotos(res) {
    if(res.attributes.getNamedItem("stat").value != "ok") {
        if(res.getElementsByTagName('key')[0].attributes.getNamedItem("invalid").value == "True") {
            window.location.reload( true );
        }
    } else {    
        photos = res.getElementsByTagName('photo');
        startTheTimer();
    }
        
    document.captureEvents(Event.KEYPRESS);
    document.onkeypress=processKey;
}

function constructUrl(photo) {
	farm = photo.attributes.getNamedItem("farm").value;
    url = "http://farm" + farm + ".static.flickr.com/" + photo.attributes.getNamedItem("server").value;
    url = url + "/" + photo.attributes.getNamedItem("id").value;
    url = url + "_" + photo.attributes.getNamedItem("secret").value;
    url = url + size;
    url = url + ".jpg";
    return(url);
}
function constructUrlSmall(photo) {
    if(photo) {	
	farm = photo.attributes.getNamedItem("farm").value;
    url = "http://farm"+farm+".static.flickr.com/" + photo.attributes.getNamedItem("server").value;
    url = url + "/" + photo.attributes.getNamedItem("id").value;
    url = url + "_" + photo.attributes.getNamedItem("secret").value;
    url = url + "_s";
    url = url + ".jpg";
    return(url);
    }
}
function constructLink(photo) {
    url = "http://www.flickr.com/photos/" + photo.attributes.getNamedItem("owner").value;
    url = url + "/" + photo.attributes.getNamedItem("id").value;
    url = url + "/";
    return(url);
}
function replaceImage(photo) {
    document.getElementById('imgholder').src = constructUrl(photo);
    document.getElementById('imgLink').href = constructLink(photo);
}

function startTheTimer() {
    if(!paused) {
        swapPhoto();
        runTimer();
    }
}
function runTimer() {
    timerRunning = true;
    timerID = self.setTimeout("startTheTimer()", delay);
}
function swapPhoto() {
    replaceImage(photos[thisPhoto]);
    populateUpcoming();
    if(thisPhoto == (photos.length - 1))
        thisPhoto = 0;
    else
        thisPhoto++;
}



function populateUpcoming() {
    if((thisPhoto + (kPhotosInBar - kPhotoSelector)) > (photos.length - 1)) {
        basePhoto = photos.length - kPhotosInBar;
    } else if(thisPhoto > (kPhotoSelector - 1)) {
        basePhoto = thisPhoto - (kPhotoSelector - 1);
    } else {
        basePhoto = 0;
    }
    
    for(pui = 0; pui < kPhotosInBar; pui++) {        
        replaceUpcomingImage(photos[basePhoto + pui],pui+1,basePhoto);
    }
}


function replaceUpcomingImage(photo, slot, base) {    
//
    document.getElementById('upIm' + slot).src = "http://is.patrick.geek.nz/macnz/b/upcoming-loading.png";
    document.getElementById('upIm' + slot).src = constructUrlSmall(photo);
    document.getElementById('upLn' + slot).href = 'javascript:goTo(' + ((base + slot) - 1) + ');';
    if(((base + slot) - 1) == thisPhoto) {
        document.getElementById('upIm' + slot).className = 'upcomingActive';
    } else {
        document.getElementById('upIm' + slot).className = 'upcomingOther';
    }
}

function changePhotoSize(newSize) {
    if(newSize == '_m') newSize = ''; 
    size = newSize;
    replaceImage(photos[thisPhoto - 1]);
}

function goTo(photo) {
    thisPhoto = photo + 1;
    pauseSlideshow();
    resumeSlideshow()
}

function pauseSlideshow() {
    paused = true;
    if(timerID) {
      clearTimeout(timerID);
      timerID  = null;
    }
}

function resetTimer() {
    if(timerID) {
      clearTimeout(timerID);
      timerID  = null;
      runTimer();
    }
}

function previousPhoto() {
    thisPhoto = thisPhoto - 2;
    if (thisPhoto < 0) thisPhoto = 0;
    swapPhoto();
}
function resumeSlideshow() {
    thisPhoto = thisPhoto - 1;
    paused = false;
    startTheTimer();
}
function processKey(e){
    doPrev = 0;
    doNext = 0;
    if(e.which == 63234) { // safari!
        if(state) {
            state = 0;
            doPrev = 1;
        } else {
            state = 1;
            doPrev = 0;
        }
    }
    if (e.keyCode == 37 || doPrev == 1) {
        previousPhoto();
        if(!paused)
            resetTimer();
    }
    if(e.which == 63235) { // safari!
        if(state) {
            state = 0;
            doNext = 1;
        } else {
            state = 1;
            doPrev = 0;
        }
    }
    if (e.keyCode == 39 || doNext == 1) {
        swapPhoto();
        if(!paused)
            resetTimer();
    }
    if (e.keyCode == 32 || e.which == 32) {
        if(paused) {
            document.getElementById('imgholder').className = "imageHolder";
            resumeSlideshow();
        } else {
            document.getElementById('imgholder').className = "imageHolderPaused";
            pauseSlideshow();
        }
    }
    //alert(e.which + ", " + e.keyCode);
}

function showPreferences() {
    document.getElementById('preferences').style.display = 'block';
}
function dismissPreferences() {
    document.getElementById('preferences').style.display = 'none';
}

function showPictureBar(doIt) {
    if (doIt) {
        document.getElementById('upcomingphotos').style.display = 'block';
        document.getElementsByTagName('body')[0].className = 'experimentBWithPictureBar';
        
        
    } else {
        document.getElementById('upcomingphotos').style.display = 'none';
        document.getElementsByTagName('body')[0].className = 'experimentB';
    }
}
