Ext.onReady(function() {

    // ###############################################
    // 4 SQUARES
    // ###############################################
    
    for (var i=1;i<5;i++) {
        // scaling the 4 hover images to a 0 width
        Ext.get('nav1home' + i + 'hover').scale(0,190);
        // attaching events to the 4 hrefs
        Ext.get('nav1home' + i + 'href').hover(mouseOverHome, mouseOutHome);
    }
    var elAnim = new Array(0,0,0,0);
    
    // mouseover function on the 4 squares on the homepage
    function mouseOverHome(e,t) {
        // current square id
        var elId = t.id;
        // the id could be the id on the href or one of the images...normalizing it here
        elId = elId.substring(0,9);
        // creating a number, that corresponds with the array position in elAnim
        elNumber = parseFloat(elId.substring(8,9))-1;
        // current square image, and hover image
        var el = Ext.get(elId);
        var elHover = Ext.get(elId + 'hover');
        var elParent = Ext.get(elId + 'href');
        // if current square is not doing any effect
        if (elAnim[elNumber] != 1) {
            elAnim[elNumber] = 1;
            // the main images gets scaled to 0 width
            el.sequenceFx();
            elHover.sequenceFx();
            el.scale(0,190,{
                duration: .2,
                callback: function() {
                    // and after that it gets hidden, so the hover image pops in the correct spot
                    el.setVisibilityMode(Ext.Element.DISPLAY);
                    el.setVisible(false, false);
                    // and the hover images gets scaled to be 190 wide
                    elHover.scale(190,190,{
                        duration: .2
                    });
                }
            });
        }
    }
    // mouseout function on the 4 squares on the homepage
    function mouseOutHome(e,t) {
        // current square id
        var elId = t.id;
        // the id could be the id on the href or one of the images...normalizing it here
        elId = elId.substring(0,9);
        // creating a number, that corresponds with the array position in elAnim
        elNumber = parseFloat(elId.substring(8,9))-1;
        // current square image, hover image, and parent/href
        var el = Ext.get(elId);
        var elHover = Ext.get(elId + 'hover');
        var elParent = Ext.get(elId + 'href');
        // finding some coordinates
        var cursorCoords = e.getXY();
        var elParentCoords = elParent.getXY();
        var elParentW = elParent.getWidth();
        var elParentH = elParent.getHeight();
        // if current square is not doing any effect
        if (cursorCoords[0] <= elParentCoords[0] || cursorCoords[0] >= elParentCoords[0]+elParentW || cursorCoords[1] <= elParentCoords[1] || cursorCoords[1] >= elParentCoords[1]+elParentH) {
            elAnim[elNumber] = 0;
            // the hover images gets scaled to 0 width
            el.sequenceFx();
            elHover.sequenceFx();
            elHover.scale(0,190,{
                duration: .2,
                callback: function() {
                    // and after that it the main images gets unhidden, so the main image pops back in the correct spot
                    el.setVisibilityMode(Ext.Element.DISPLAY);
                    el.setVisible(true, false);
                    // and the main image gets scaled to be 190 wide
                    el.scale(190,190,{
                        duration: .2
                    });
                }
            });
        }
    }
    
    // ###############################################
    // IMAGES
    // ###############################################
    
    var currentVisibleImg = new Array();
    var currentVisiblePos = new Array();
    var totalAmountShown = 5;
    for (var i=0;i<imageTotal;i++) {
        // making all the items in this array 0 (image not visible)
        currentVisibleImg[i] = 0;
    }
    for (var i=0;i<totalAmountShown;i++) {
        // making all the items in this array 0 (position not shown)
        currentVisiblePos[i] = -1;
    }
    // showing (totalAmountShown-1) images right away when the page loads (after that, the fading will start)
    for (var i=0;i<totalAmountShown-1;i++) {
        var randomnumber=getRandomImg();
        Ext.fly('home-images').appendChild('home-img-' + randomnumber);
        var imgPos = setImgLeftTop(randomnumber,i);
        Ext.fly('home-img-' + randomnumber).setStyle('left',imgPos[0]+'px'); 
        Ext.fly('home-img-' + randomnumber).setStyle('top',imgPos[1]+'px'); 
        currentVisibleImg[randomnumber] = 1;
        currentVisiblePos[i] = randomnumber;
    }
    
    imageFader();
    
    function imageFader() {
        var fadeIn = 0;
        var fadeOut = 1;
        var fadeTimeIn = 2;
        var fadeTimeOut = 3;
        // finding the current missing position
        for (var i=0;i<currentVisiblePos.length;i++) {
            if (currentVisiblePos[i] == -1) {
                var fadeIn = i;
                break;
            }
        }
        // picking the fade out image randomly
        var fadeOut=Math.floor(Math.random()*currentVisiblePos.length);
        // if they are the same
        if (fadeOut == fadeIn) {
            var coinToss = Math.floor(Math.random()*2);
            if (coinToss == 0) {
                fadeOut = (fadeOut+1 >= currentVisiblePos.length) ? 0 : fadeOut+1;
            }
            else {
                fadeOut = (fadeOut-1 < 0) ? currentVisiblePos.length-1 : fadeOut-1;
            }
        }
        
        var randomnumber=getRandomImg();
        Ext.fly('home-img-' + randomnumber).setOpacity(0);
        Ext.fly('home-images').appendChild('home-img-' + randomnumber);
        var imgPos = setImgLeftTop(randomnumber,fadeIn);
        Ext.fly('home-img-' + randomnumber).setStyle('left',imgPos[0]+'px'); 
        Ext.fly('home-img-' + randomnumber).setStyle('top',imgPos[1]+'px'); 
        Ext.fly('home-img-' + randomnumber).setOpacity(1,{
            duration: fadeTimeIn, easing: 'easeIn',
            callback: function() {
                currentVisibleImg[randomnumber] = 1;
                currentVisiblePos[fadeIn] = randomnumber;
                Ext.fly('home-img-' + currentVisiblePos[fadeOut]).setOpacity(0,{
                    duration: fadeTimeOut, easing: 'easeIn',
                    callback: function() {
                        Ext.fly('homeImgRepos').appendChild('home-img-' + currentVisiblePos[fadeOut]);
                        currentVisibleImg[currentVisiblePos[fadeOut]] = 0;
                        currentVisiblePos[fadeOut] = -1;
// start debug code
/*
var totalImagesShown = 0;
for (var j=0;j<currentVisiblePos.length;j++) {
    if (currentVisiblePos[j] != -1) {
        totalImagesShown++;
    }
}
if (totalImagesShown < 4) {
    debugMe('**********************<br />ALERT!<br />Only ' + totalImagesShown + ' images shown');
}
debugMe('currentVisibleImg = ' + currentVisibleImg + '<br />currentVisiblePos = ' + currentVisiblePos + '<br />fadeIn = ' + fadeIn + '<br />fadeOut = ' + fadeOut + '<br />');
*/
// end debug code
                        imageFader();
                    }
                });
            }
        });
    }
    
    function getRandomImg() {
        var randomnumber=Math.floor(Math.random()*imageTotal);
        if (currentVisibleImg[randomnumber] == 0) {
            return randomnumber;
        }
        else {
            var numberPicked = -1;
            // start counting from the number that was picked
            for (var i=randomnumber;i<imageTotal;i++) {
                if (currentVisibleImg[i] == 0) {
                    numberPicked = i;
                    break;
                }
            }
            if (numberPicked != -1) {
                return numberPicked;
            }
            else {
                // start counting from 0
                for (var i=0;i<imageTotal;i++) {
                    if (currentVisibleImg[i] == 0) {
                        numberPicked = i;
                        break;
                    }
                }
                if (numberPicked != -1) {
                    return numberPicked;
                }
                // return 0 as a last resort
                else {
                    return 0;
                }
            }
        }
    }

    // number: the image
    // pos = position:
    //       0: left top      
    //       1: left bottom   
    //       2: right bottom  
    //       3: right top     
    //       4: center        
    /*
             0 3
              4
             1 2             
    */
    function setImgLeftTop(number,pos) {
        var imgW = Ext.fly('home-img-' + number).getWidth();
        var imgH = Ext.fly('home-img-' + number).getHeight();
        maxW = Math.floor((620-imgW)/100);
        maxH = Math.floor((400-imgH)/100);
        // positioning the image at a random spot. available space is 620x400
        // we'll be snapping it to a grid of 100px increments
        // depending on the position, we'll be assigning values
        if (pos == 0) {
            var randomLeft=Math.floor(Math.random()*3)*25; // 0-25-50
            var randomTop=Math.floor(Math.random()*2)*25; // 0-25
        }
        else if (pos == 1) {
            var randomLeft=Math.floor(Math.random()*3)*20; // 0-20-40
            var randomTop=Math.floor((Math.random()*4)+9)*20; // 180-200-220-240
        }
        else if (pos == 2) {
            var randomLeft=Math.floor((Math.random()*4)+18)*20+10; // 370-390-410
            var randomTop=Math.floor((Math.random()*4)+9)*20+10; // 190-210-230-250
        }
        else if (pos == 3) {
            var randomLeft=Math.floor((Math.random()*4)+18)*20; // 360-380-400
            var randomTop=Math.floor(Math.random()*2)*20; // 0-20
        }
        else if (pos == 4) {
            var randomLeft=Math.floor((Math.random()*4)+7)*20; // 140-160-180-200
            var randomTop=Math.floor((Math.random()*4)+5)*20; // 100-120-140-160
        }
        else {
            var randomLeft=Math.floor(Math.random()*(maxW+1))*100;
            var randomTop=Math.floor(Math.random()*(maxH+1))*100;
        }
        // taking the border into account
        var borderWidth = 0;
        if (randomLeft + imgW >= 620) {
            randomLeft = 620 + borderWidth - imgW;
        }
        if (randomTop + imgH >= 400) {
            randomTop = 400 + borderWidth - imgH;
        }
        if (randomLeft == 0) {
            randomLeft = -borderWidth;
        }
        if (randomTop == 0) {
            randomTop = -borderWidth;
        }
        return [randomLeft, randomTop];
    }
    
    function debugMe(printThis) {
        document.getElementById('debug').innerHTML = printThis + '<br />' + document.getElementById('debug').innerHTML;
    }
});

