/// <reference path="helpers.js" />
/// <reference path="prototype_1602.js" />

function WaitHandler()
{
    this._obj = $('waitHandler');
    this._objShadow = $('waitHeaderShadow');
    //kozvetlenul a body eleme legyen, mert maskulonben nemlesz teljes szelessegu
    this._obj.parentNode.removeChild(this._obj);
    this._objShadow.parentNode.removeChild(this._objShadow);
    document.body.appendChild(this._objShadow);
    document.body.appendChild(this._obj);
    
    
    this._loadedImages = 0;
    this._imagesToLoad =  this._FindImagesToPreload();
    this._img = null;
    this._timer = null;
    this._activateTimer = null;
    this._imgCompleteEventListener = this._ImgComplete.bindAsEventListener(this);
    this._PreloadImages();
}

WaitHandler.prototype._PreloadImages = function()
{
    if(this._imagesToLoad.length > this._loadedImages)
    {
        //alert("_PreloadImages: " + this._loadedImages);
        this._img = new Image();
        Event.observe(this._img, 'error', this._imgCompleteEventListener);
        Event.observe(this._img, 'load', this._imgCompleteEventListener);
        Event.observe(this._img, 'readystatechange', this._imgCompleteEventListener);
        var cnt = this._loadedImages;
        this._loadedImages++;
        this._img.src = this._loadedImages[cnt];
        
        this._CheckImg();
    }
    else
        Helpers.Log('WaitHandler >> _PreloadImages: Finished', null);
        //alert(this._loadedImages + ' images loaded');
}

WaitHandler.prototype._CheckImg = function()
{
    //if(this._img == null)
        //return;
    if(!this._img.complete)
    {
        this._timer = setTimeout(this._imgCompleteEventListener, 100);
        //alert("timer");
    }
    else
    {
        //alert("complete");
        this._ImgComplete();
    }
}

WaitHandler.prototype._ImgComplete = function()
{
    //alert("_ImgComplete");
    clearTimeout(this._timer);
    Event.stopObserving(this._img, 'error', this._imgCompleteEventListener);
    Event.stopObserving(this._img, 'load', this._imgCompleteEventListener);
    Event.stopObserving(this._img, 'readystatechange', this._imgCompleteEventListener);
    //this._img = null;
    this._PreloadImages();
}

WaitHandler.prototype._FindImagesToPreload = function()
{
    var images = new Array();
    for(var i=0; i<document.styleSheets.length; i++){ 
        var styleSheet = document.styleSheets[i];
        var csshref = (styleSheet.href) ? styleSheet.href : window.location.href;
        var baseURLarr = csshref.split('/');//split href at / to make array
        baseURLarr.pop();//remove file path from baseURL array
        baseURL = baseURLarr.join('/');//create base url for the images in this sheet (css file's dir)
        if (baseURL) {
            baseURL += '/'; //tack on a / if needed
        }
        
        var sheetRules;
        try{
        sheetRules = (styleSheet.cssRules)  //->>> http://www.quirksmode.org/dom/w3c_css.html
                    ? styleSheet.cssRules //w3
                    : styleSheet.rules; //ie 
        }catch(ex){
            continue;
        }
        for(var j=0; j<sheetRules.length; j++)
        {
            var rule = sheetRules[j];
            if(rule.selectorText && rule.selectorText.indexOf('#waitHandler') != -1)
            {
                //parse cssPile for image urls
                var tmpImage = rule.style.cssText.match(/[^\("]+\.(gif|jpg|jpeg|png)/g);//reg ex to get a string of between a "(" and a ".filename" / '"' for opera-bugfix
                if(tmpImage)
                {
                    for(var k=0; k<tmpImage.length; k++)
                    {
                        var imgSrc = (tmpImage[k].charAt(0) == '/' || tmpImage[k].match('://')) ? // protocol-bug fixed
                            tmpImage[k] : 
                            baseURL + tmpImage[k];
                        Helpers.Log('WaitHandler >> _FindImagesToPreload: %s', imgSrc);
                        images.push(imgSrc);
                    }
                }
            }     
        }
    }
    return images;
}

WaitHandler.prototype.Activate = function()
{
    this._activateTimer = setTimeout(this._Activate.bindAsEventListener(this), 0); 
}
WaitHandler.prototype._Activate = function()
{
    var offs = document.viewport.getScrollOffsets();
    var dim = document.viewport.getDimensions();
    
    this._obj.style.left = offs.left + dim.width/2 - this._obj.getWidth()/2 + 'px';
    this._obj.style.top = offs.top + dim.height/2 - this._obj.getHeight()/2 + 'px';
    
    this._objShadow.style.left = offs.left + 'px';
    this._objShadow.style.top = offs.top + 'px';
    this._objShadow.style.width = dim.width + 'px';
    this._objShadow.style.height = dim.height + 'px';
    
    this._obj.style.display = 'block';
    this._objShadow.style.display = 'block';
}

WaitHandler.prototype.Deactivate = function()
{
    clearTimeout(this._activateTimer); 
    this._obj.hide();
    this._objShadow.hide();
}


/*
Position.center = function(element){
        var options = Object.extend({
            zIndex: 999,
            update: false
        }, arguments[1] || {});
        element = $(element)
        if(!element._centered){
            Element.setStyle(element, {position: 'absolute', zIndex: options.zIndex });
            element._centered = true;
        }
        var dims = Element.getDimensions(element);
        Position.prepare();
        var winWidth = self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;
        var winHeight = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
        var offLeft = (Position.deltaX + Math.floor((winWidth-dims.width)/2));
        var offTop = (Position.deltaY + Math.floor((winHeight-dims.height)/2));
        element.style.top = ((offTop != null && offTop > 0) ? offTop : '0') + 'px';
        element.style.left = ((offLeft != null && offLeft > 0) ? offLeft : '0') + 'px';
        if(options.update){
            Event.observe(window, 'resize', function(evt){ Position.center(element); }, false);
            Event.observe(window, 'scroll', function(evt){ Position.center(element); }, false);
        }
    }
*/