    /* -----------------------------------------------------------------------------
    -------------------------------------------------------------------------------/
    |
    |     Client-side processing for  RamonaDesignStudio.Com | Projects page
    |     
    |     Author: Miky Dinescu
    |
    /-------------------------------------------------------------------------------    
    ----------------------------------------------------------------------------- */

function prjAsset()
{
    this.imageid = 0;
    this.image = null;
    this.title = "";
    this.description = "";
    this.previous = null;
    this.next = null;
}

function prjAssetsCollection()
{
    var _current = 0;
    var _assets = new Array();
    var _subscribers = new Array();
    
    // define internal array of possible events
    _subscribers["SELECTION_CHANGED"] = new Array();


    function fireSelectionChanged(selectionChangeType)
    {
        if(_subscribers["SELECTION_CHANGED"].length > 0)
        {
            for(k=0; k<_subscribers["SELECTION_CHANGED"].length; k++)
            {
                cbk = _subscribers["SELECTION_CHANGED"][k][1];
                cbk(_subscribers["SELECTION_CHANGED"][k][0], _current, selectionChangeType);
            }
        }    
    }


    this.addAsset = function(imageid, image, title, description)
    {
        k = _assets.length;

        pa = new prjAsset();
        pa.image = image;
        pa.imageid = imageid;
        pa.title = title;
        pa.description = description;
        
        if(k>0)
        {
            _assets[k-1].next = pa;
            pa.previous = _assets[k-1];
        }
        _assets[k] = pa;
    }

    
    this.count = function()
    {
        return _assets.length;
    }
    
    this.subscribeToEvent = function(who, callback, eventName)
    {
        if(eventName == "SELECTION_CHANGED")
            _subscribers["SELECTION_CHANGED"].push([who, callback]);
    }
    
    this.selectPrevious = function()
    {
        if(_current>0)
        {
            _current--;
            fireSelectionChanged(-1);
        }
    }

    this.selectNext = function()
    {
        if(_current < (_assets.length - 1))
        {
            _current++;
            fireSelectionChanged(1);
        }
    }
    
    this.selectedIndex = function()
    {
        return _current;
    }    
    
    
    this.getItemAt = function(position)
    {
        return _assets[position];
    }
    
    
    this.selectItemAt = function(position)
    {
        _current = position;
        fireSelectionChanged(0);
    }
    

    
    this.selectedItem = function()
    {
        return _assets[_current];
    }
    
    this.updateSelectedItem = function(propertyName, newValue)
    {
        switch(propertyName)
        {
            case "image":
                _assets[_current].image = newValue;
                break;
            case "title":
                _assets[_current].title = newValue;
                break;
            case "description":
                _assets[_current].description = newValue;
                break;                
        }    
    }
    
    this.updateItemAt = function(itemID, propertyName, newValue)
    {
        switch(propertyName)
        {
            case "image":
                _assets[itemID].image = newValue;
                break;
            case "title":
                _assets[itemID].title = newValue;
                break;
            case "description":
                _assets[itemID].description = newValue;
                break;                
        }
    }
}

prjAssetsCollection.prototype = {
    previous: function()
    {
        this._assets[this._current-1];
    },
    
    next: function()
    {
        this._assets[this._current+1];
    }           
}



function clsThumbStrip(containerElement, prjItems)
{
    // establish our contaier
    this._currentlySelectedThumbnail = null;
    this._viewStateStartIndex = 0;
    this._prjItems = prjItems;
    this._prjItems.subscribeToEvent(this, this.onProjectItemsSelectionChanged, "SELECTION_CHANGED");
    this._container = $(containerElement);    
}

clsThumbStrip.prototype = {
    onProjectItemsSelectionChanged: function(__myclass, newSelectionIndex, changeType)
    {        
        var newThumb;
        
        if(__myclass._currentlySelectedThumbnail)
            __myclass._currentlySelectedThumbnail.style.border = "2px solid #000000";        

        if(changeType == -1) // selection moved to previous
        {
            if(__myclass.ensureThumbnailVisible())        
                __myclass.render();
        }else if(changeType == 1) // selection moved to next
        {            
            if(__myclass.ensureThumbnailVisible())
                __myclass.render();
        }else // the user selected an item
        {            
            if(__myclass.ensureThumbnailVisible())
                __myclass.render();
        }
        
        if((newThumb = __myclass.getThumbByIndex(newSelectionIndex)) != null)
        {
            __myclass._currentlySelectedThumbnail = newThumb;
            newThumb.style.border = "2px solid #dcf7ca";
        }
    },
    
    
    scrollLeft: function()
    {
        if(this._viewStateStartIndex > 0)
        {
            this._viewStateStartIndex--;
            this.render();
        }
    },
    
    
    scrollRight: function()    
    {
        var howMany = 7;
        if(this._viewStateStartIndex < (this._prjItems.count() - howMany))
        {        
            this._viewStateStartIndex++;
            this.render();
        }
    },
    
    ensureThumbnailVisible: function()
    {
        var howMany = 7;
        var newStartIdx = -1;
        
        if(this._prjItems.selectedIndex() >= this._viewStateStartIndex)
        {
            while(this._viewStateStartIndex < (this._prjItems.count() - howMany))
            {
                if(this._prjItems.selectedIndex() < (this._viewStateStartIndex + howMany))
                     break;
                this._viewStateStartIndex++;
                newStartIdx = this._viewStateStartIndex;
            }           
        }else
        {
            while(this._viewStateStartIndex > 0)
            {
                if(this._prjItems.selectedIndex() >= this._viewStateStartIndex)
                     break;
                this._viewStateStartIndex--;
                newStartIdx = this._viewStateStartIndex;
            }
        }
                
        // return TRUE if view needs to be updated
        return (newStartIdx != -1); 
    },
    
    render: function()
    {                 
        this.clearThumbnails();
        this.addImgThumbnails();
    },
    
    getThumbByIndex: function(thumbIndex)
    {
        var k;
        for(k=0; k<this._container.childNodes.length; k++)
        {
            if(this._container.childNodes[k].imageIndex == thumbIndex)
                return this._container.childNodes[k];
        }
        return this._container.firstChild;
    },
    
    clearThumbnails: function()
    {
        var aux;
        
        while(this._container.childNodes.length)
        {
            aux = this._container.firstChild;
            this._container.removeChild(aux);
            aux = null;
        }
    },

    _addImgThumb: function(imageIndex, selected)
    {
        var imgNode;
        
        imgNode = document.createElement("IMG");
        imgNode.src = this._prjItems.getItemAt(imageIndex).image.src;
        imgNode.className = "projectsThumbnail";
        imgNode.imageIndex = imageIndex;
        imgNode.owner = this;
        imgNode.setAttribute("alt", this._prjItems.getItemAt(imageIndex).title);
        this._container.appendChild(imgNode);
        if(selected)
        {
            if(this._currentlySelectedThumbnail)
                this._currentlySelectedThumbnail.style.border = "2px solid #000000";
            imgNode.style.border = "2px solid #dcf7ca";
            this._currentlySelectedThumbnail = imgNode;
        }        
        
        imgNode.onmouseover = function() { this.oldBorderStyle = this.style.border; this.style.border = "2px solid #b7e19a"; };
        imgNode.onmouseout = function() { this.style.border = this.oldBorderStyle; };
        imgNode.onmousedown = function() { gotoThumbnail(this.imageIndex); this.oldBorderStyle = this.border.style; };
        
        return imgNode.clientWidth;
    },
    
    addImgThumbnails: function()
    {    
        var i;
        var totalWidth;
        var maxWidth = 6 * 93;
        
        totalWidth = 0;
        for(i = this._viewStateStartIndex; i < this._prjItems.count(); i++)
        {    
            totalWidth += this._addImgThumb(i, (i == this._prjItems.selectedIndex()));
            
            if(totalWidth > maxWidth)
                break;
        }
    }    
}



function clsDisplayImage(canvasElement, titleElement, descriptionElement, prjItems)
{
    // establish our contaier
    this._prjItems = prjItems;
    this._prjItems.subscribeToEvent(this, this.onProjectItemsSelectionChanged, "SELECTION_CHANGED");
    this._canvas = $(canvasElement);
    this._titleElement = $(titleElement);
    this._descriptionElement = $(descriptionElement);
}

clsDisplayImage.prototype = {
    onProjectItemsSelectionChanged: function(__myclass, newSelectionIndex, changeType)
    {
        if(changeType == -1) // selection moved to previous
        {
            __myclass.render();
        }else if(changeType == 1) // selection moved to next
        {
            __myclass.render();
        }else // the user selected an item
        {
            __myclass.render();
        }
    },
    
    
    render: function()
    {
        this._canvas.style.backgroundImage = "url('" + this._prjItems.selectedItem().image.src + "')";
        if(this._titleElement)
            prj_UIUpdateElementText(this._titleElement, this._prjItems.selectedItem().title);
        if(this._descriptionElement)
            prj_UIUpdateElementText(this._descriptionElement, this._prjItems.selectedItem().description);
        document.getElementById('prj_span_currentImage').innerHTML = " " + (this._prjItems.selectedIndex() + 1) + " of " + this._prjItems.count() + " ";
    }        
}



function ShowPageBusy()
{
    var icon = document.getElementById("pageBusyIcon");
    icon.style.visibility = "visible";
}



function HidePageBusy()
{
    var icon = document.getElementById("pageBusyIcon");
    icon.style.visibility = "hidden";
}



function initializeProjectsDisplay(dispList)
{
    var k;      // counter
    var ip;     // image preloader object
    var _imgLocationList;
    
    // show the busy indicator
    ShowPageBusy();
    
    
    // initialize variables
    _imgLocationList = new Array();
    
    window.prjAssets = new prjAssetsCollection();    
    for(k = 0; k < dispList.length/3; k++)
    {
        _imgLocationList[k] = dispList[k*3];
        window.prjAssets.addAsset(k, null, dispList[k*3+1], dispList[k*3+2]);
    }            
    
    disableSelection($('prj_btnPrev'));
    disableSelection($('prj_btnNext'));
    disableSelection($('prj_btnPlayPause'));
    
    // start the preloading process, and give it 10s to load all images
    ip = new ImagePreloader(_imgLocationList, preloadComplete, 0);
}


function preloadComplete(processedList, cnt)
{    
    for(i=0; i<cnt; i++)
        window.prjAssets.updateItemAt(i, "image", processedList[i]);
    
    window.thumbList = new clsThumbStrip('div_thumbStrip', prjAssets);
    window.mainImage = new clsDisplayImage('imgT_prev', 'imageTitleText', 'imageDescriptionText', prjAssets);
    
    window.setTimeout("HidePageBusy();", 600);
    window.prjAssets.selectItemAt(0);
    window.thumbList.render();
    
    urchinTracker();
}






function fadeDownImage()
{
    if(window.imageStep != 20)
    {                
        setOpacity(document.getElementById('imgT'), Math.sin(Math.PI * ((20 - parseFloat(window.imageStep)) / 20) /2));
        window.imageStep++;                
        window.setTimeout("fadeDownImage();", 30);
    }else if(window.imageStep == 20)
    {
        window.imageStep = 0;
        window.setTimeout("fadeUpImage();", 30);
        document.getElementById('imgT').src = window.imageList[window.nextImage].src;
    }
}
function fadeUpImage()
{
    if(window.imageStep != 20)
    {                
        setOpacity(document.getElementById('imgT'), Math.sin(Math.PI * (parseFloat(window.imageStep) / 20) /2));
        window.imageStep++;                
        window.setTimeout("fadeUpImage();", 30);
    }else if(window.imageStep == 20)
    {
        window.imageStep = 0;
        window.nextImage++;
        if(window.nextImage != window.imageList.length)
        {
            window.setTimeout("fadeDownImage();", 3500);    
        }else{
            CallServer('getNextImageList','');        
        }
    }            
}





    /* ------------------------------------------------------------------
        AJAX Callback that receives out of band response from server
   ------------------------------------------------------------------ */
function ReceiveServerData(rValue)
{   
    if((rValue != "ERROR") && (rValue != "SUCCESS"))
    {
        initializeProjectsDisplay(eval(rValue));
    }
}


    /* ------------------------------------------------------------------
        AJAX Callback that handles outofband calls' errors
    ------------------------------------------------------------------ */
function ProcessCallBackError(arg, context)
{
    alert('An error occured while trying to process your request!');
}


    /* ------------------------------------------------------------------
        Handles MOUSE CLICK event on thumbnails
    ------------------------------------------------------------------ */
function gotoThumbnail(thumbIndex)
{
    window.prjAssets.selectItemAt(thumbIndex);
}


    /* ------------------------------------------------------------------
        Handles MOUSE DOWN event for LEFT ThumbStrip button
    ------------------------------------------------------------------ */
function prj_btnThumbStripLeft_mouseDown(sender, evt)
{
    window.thumbList.scrollLeft();
}


    /* ------------------------------------------------------------------
        Handles MOUSE DOWN event for RIGHT ThumbStrip button
    ------------------------------------------------------------------ */
function prj_btnThumbStripRight_mouseDown(sender, evt)
{
    window.thumbList.scrollRight();
}


