// encapsulate access to XMLHttpRequest
//

function XMLDoc() {
    var me = this;
    this.getRequest = function() {
        var req = null;
        if ( window.XMLHttpRequest ) {
            try {
                req = new XMLHttpRequest();
            } catch(e) {
            }
        } else if ( window.ActiveXObject) {
            try {
                req = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                try {
                    req = new ActiveXobject("Microsoft.XMLHTTP");
                } catch(e) {
                }
            }
        } else {
            alert("ajax fail");
        }
        return req;
    }
    this.loadXMLDoc = function( url, loadHandler ) {
        this.request=this.getRequest();
        if ( this.request ) {
            // findme
            this.request.open( "GET", url, true );
            this.request.setRequestHeader("Content-Type", "text/xml");
            this.request.onreadystatechange = function () { loadHandler( me ) };
            this.request.send(null);
        }
    }
}

function AutoQueue( size ) {
    var that = this;
    this.size = size;
    this.queued = [];
    this.currentImg= null;
    this.history = [];
    this.fullCallbackFunc = null;
    this.someCallbackFunc = null;
    this.busy=false;

    this.update = function () {
    /*
        if ( that.hasSome() ) {
            that.someCallback();
        }
        */
        if ( that.hasAll() ) {
            //console.log("load complete.................................................");
        //    that.fullCallback();
        } else {
            if ( this.busy ) {
                //console.log("already busy, no action at this time");
            } else {
                this.busy=true;
                //console.log("kicking off another load");
                blah = new XMLDoc();
                var url = "http://www.appulsus.com/autoprompt/autopromptgui.php?cmd=randomphoto&"+Math.random();
                blah.loadXMLDoc( url, this.handleResponse );
            }
        }
    }

    this.length = function () {
        return that.queued.length;
    }
/*
    this.onSomeQueue = function ( callback ) {
        that.someCallbackFunc = callback;
        that.someCallback();
    }

    this.onFullQueue = function ( callback ) {
        that.fullCallbackFunc = callback;
        that.fullCallback();
    }

    this.fullCallback = function () {
        if ( that.fullCallbackFunc != null && that.hasAll() ) {
            that.fullCallbackFunc();
            that.fullCallbackFunc= null;
        }
    }

    this.someCallback = function () {
        if ( that.someCallbackFunc != null && that.hasSome() ) {
            that.someCallbackFunc();
            that.someCallbackFunc= null;
        }
    }
*/

    this.get = function( x ) {
        //console.log("trying to get "+x+" with length at "+that.queued.length );
        if ( x < that.queued.length && x >= 0 ) {
            that.currentImg = that.queued[x];
            return that.queued[x];
        }
        return null;
    }

    this.hasSome = function () {
        return ( that.queued.length > 0 );
    }

    this.hasAll= function () {
        return ( that.queued.length > (that.size) );
    }
    
    this.shift = function () {
        if ( ! that.hasSome() ) {
            return null;
        }
        var popped = that.queued[0];
        //console.log( "pre-shift:  size is now: "+that.queued.length );
        that.queued.splice(0,1);
        //console.log( "post-shift:  size is now: "+that.queued.length );
        that.history[that.history.length]=popped;
        that.currentImg=popped;
        that.update();
        return popped;
    }

    this.current = function () {
        return that.currentImg;
    }

    this.handleResponse = function ( initxml ) {
        req = initxml.request;
        if ( req.readyState == 4 && req.status==200) {
            //console.log("adding a new url");
            jsonobj = eval( '('+req.responseText+')' );
            jsonobj.img = document.createElement("img");
            jsonobj.img_m = document.createElement("img");
            //jsonobj.img = new Image();
            //jsonobj.img_m = new Image();
            jsonobj.img.src = jsonobj.url;
            jsonobj.img_m.src = jsonobj.url_m;
            that.queued[that.queued.length] = jsonobj;
            // this load is complete.. tell update it can call again if it wants
            //console.log( "queued size is now: "+that.queued.length );
            that.busy=false;
            that.update();
        }
    }

    // call update
    this.update();
}

function Autoprompt() {
    var that = this;
    this.el = document.getElementById('autoprompt-container');
    // create the structure
    var ul = document.createElement("ul");
    this.el.appendChild(ul); 
    this.el.id="ap-container";
    var slot1 = document.createElement("li");
    var slot2 = document.createElement("li");
    var slot3 = document.createElement("li");
    var button = document.createElement("img");
    button.src="res/go.png";
    button.style.display="block";
    button.style.marginTop="10px";
    button.style.marginLeft="5px";
    //button.type="button";
    button.onclick=function() { button.src="res/go.png"; that.cycle(); };
    button.onmouseover=function() { button.src="res/go-over.png"; };
    button.onmouseout=function() { button.src="res/go.png"; };

    //button.value="cycle";

    ul.appendChild(slot1);
    ul.appendChild(slot2);
    ul.appendChild(slot3);
    this.el.appendChild(button);

    this.pslot1 = new PromptSlot( this, slot1 );
    this.pslot2 = new PromptSlot( this, slot2 );
    this.pslot3 = new PromptSlot( this, slot3 );

    this.cycle = function () {
        this.unzoom();
        this.pslot1.setPhoto();
        this.pslot2.setPhoto();
        this.pslot3.setPhoto();
    }

    this.unzoom = function () {
        this.pslot1.unzoom();
        this.pslot2.unzoom();
        this.pslot3.unzoom();
    }

    this.cycle();
}

function PromptSlot( autoprompt, el ) {
    var that = this;
    this.autoQueue = new AutoQueue( 6 );

    this.autoprompt = autoprompt;
    this.locked = false;
    this.el = el;
    var padlock = document.createElement("div");
    var magnifier = document.createElement("div");
    padlock.className="ap-padlock";
    magnifier.className="ap-magnifier";
    var zoombox = document.createElement("div");
    var zoomimg = document.createElement("img");
    zoombox.className="ap-zoombox";
    zoomimg.className="ap-zoomimg";
    this.el.appendChild(padlock);
    this.el.appendChild(magnifier);
    this.el.appendChild(zoombox);
    zoombox.appendChild(zoomimg);
    this.img = document.createElement("img");
    this.el.appendChild( this.img );
    this.full=6;

    this.activate = function () {
        padlock.style.visibility  ="visible";
        magnifier.style.visibility="visible";
    }

    this.deactivate = function () {
        padlock.style.visibility  ="hidden";
        magnifier.style.visibility="hidden";
    }

    this.togglePadlock = function () {
        if ( that.locked ) {
            that.locked = false;
            padlock.style.backgroundImage="url(res/lock-open.png)";
        } else {
            that.locked = true;
            padlock.style.backgroundImage="url(res/lock-closed.png)";
        }
    }

    this.zoom = function () {
        that.autoprompt.unzoom();
        zoomimg.src="";
        zoomimg.src=that.current().url_m;
        zoombox.style.visibility="visible";
    }

    this.unzoom = function () {
        zoombox.style.visibility="hidden";
    }

    padlock.onclick=that.togglePadlock;
    magnifier.onclick=this.zoom;
    zoomimg.onclick=this.unzoom;
    //magnifier.onmouseout=this.unzoom;
    this.el.onmouseover=that.activate;
    this.el.onmouseout=that.deactivate;
/*
    this.processRandomPhoto = function ( initxml ) {
        req = initxml.request;
        if ( req.readyState == 4 && req.status==200) {
            //alert(req.responseText);
            jsonobj = eval( '('+req.responseText+')' );
            jsonobj.img = document.createElement("img");
            jsonobj.img_m = document.createElement("img");
            jsonobj.img.src = jsonobj.url;
            //alert(jsonobj.url);
            jsonobj.img_m.src = jsonobj.url_m;
            that.queued[that.queued.length] = jsonobj;

            if ( that.queued.length < that.full ) {
                alert("adding another");
                that.callRandomPhoto();
            } else {
                that.setPhoto();
            }
            req.abort();
        }
    }
    */


/*
    this.getSetFunc() {
        var myimg = that.img;
        return function () {
            var mydata = that.autoQueue.get(x); 
            if ( mydata != null ) {
                var myurl = mydata.url;
                myimg.src = myurl;
            }
        }
    }

    this.doSet = function ( x ) {
        that.autoQueue.onReady(
            that.getSetFunc( x );    
        );
    }
 */   

    this.current = function () {
        return that.autoQueue.current();
    }

    this.doJitter = function( ) {
        var num = 1;
        var myimg = that.img;
        if ( ! that.autoQueue.hasSome() ) {
            setTimeout( that.doJitter, 50 );
            return;
        } else {
            for ( var x=that.autoQueue.length()-1; x>=0; x--,num++ ) {
                setTimeout( 
                    function ( thisx ) {
                        return function () {
                            var mydata = that.autoQueue.get( thisx ); 
                            //console.log("setting url: "+thisx);
                            myimg.src = mydata.url;
                            if ( thisx == 0 ) {
                                // shift off the bottom one if we're at it
                                //console.log("shifting the last");
                                //that.autoQueue.shift();
                                that.delayShift();
                                //that.autoQueue.shift();
                            }
                        }
                    }( x ),
                    num*50);
            }
        }
    }

    this.delayShift = function () {
        setTimeout( that.autoQueue.shift, 2000 );
    }
/*
    this.doShift = function () {
        //console.log("doShift called.. but wait for callback");
        var myimg = that.img;
        that.autoQueue.onSomeQueue(
            function () {
                //console.log("doShift callback invoked");
                var mydata = that.autoQueue.shift(); 
                if ( mydata != null ) {
                    var myurl = mydata.url;
                    myimg.src = myurl;
                }
            }
        );
    }
*/

    this.setPhoto = function () {
        if ( this.locked ) {
            that.activate();
            setTimeout( that.deactivate, 500 );
            return;
        }
        //console.log("setPhoto called" );
        //that.doShift();
        that.doJitter();
        /*
        that.doSet( 0 );
        that.autoQueue.shift();
        if ( that.queued.length >= 1 ) {
            //that.jitter();

            //var popped = that.queued[0];
            //str = "";
            //for ( x=0; x<that.queued.length; x++ ) {
            //    str += that.queued[x].url+"\n";
            //}
            //alert( str );
            //that.queued.splice(0,1);
            //that.history[that.history.length]=popped;
            //that.current=popped;
            //that.waiting=false;
        } else {
            that.waiting=true;
        }
        //that.callRandomPhoto();
        */
    }
/*
    this.callRandomPhoto = function () {
        blah = new XMLDoc();
        var url = "http://www.appulsus.com/autoprompt/autopromptgui.php?cmd=randomphoto&"+Math.random();
        //alert( url );
        blah.loadXMLDoc( url, this.processRandomPhoto );
    }
    */
}

if ( ! document.getElementById('autoprompt-container') ) {
    alert("js must be contained within a div with id ('autoprompt-container')");
} else {
    ap = new Autoprompt();
}
/*


    testproc = function ( initxml ) {
        //findme
        req = initxml.request;
        if ( req.readyState == 4 && req.status==200) {
            alert(req.responseText);
        }
    }

        blah = new XMLDoc();
        blah.loadXMLDoc("http://www.appulsus.com/autoprompt/autopromptgui.php?cmd=randomphoto", testproc );


        blah = new XMLDoc();
        blah.loadXMLDoc("http://www.appulsus.com/autoprompt/autopromptgui.php?cmd=randomphoto", testproc );

        blah = new XMLDoc();
        blah.loadXMLDoc("http://www.appulsus.com/autoprompt/autopromptgui.php?cmd=randomphoto", testproc );
*/

