///<reference path='MicrosoftAjax.js' />

/*ImageGallery.js*/
var ScrollTop = 0;

function NodeListToArray(nodeList)
{
    var array = new Array();
    for (var i = 0; i < nodeList.length; i++)
    {   
        var clone = nodeList[i].cloneNode(false);
        if (clone._events)
            $clearHandlers(clone);
        array[i] = clone;
    }
    return array;
}

function CreateImageListCopy(listOfImages)
{
    var array = new Array();
    for (var i = 0; i < listOfImages.length; i++)
    {
        var image = document.createElement('img');
        image.className = 'singleGalleryImage';
        $clearHandlers(listOfImages[i]);
        image.src = listOfImages[i].src;
        array[i] = image;
    }
    
    return array;
}

Type.registerNamespace('VikingLine');

VikingLine.ImageGallery = function(element)
{
    VikingLine.ImageGallery.initializeBase(this, [element]);
    
    this._images = null;
    this._timer = null;
    this._galleryBackground = null;
    this._galleryContainer = null;
    this._preloader = null;
}

VikingLine.ImageGallery.prototype = 
{
    initialize : function()
    {
        VikingLine.ImageGallery.callBaseMethod(this, 'initialize');
        // Node list returned by "getElementsByTagName" converted to array
        // because cloning node within this list also adds cloned node to list
        // this is undesired behavior
        this._images = NodeListToArray(this.get_element().getElementsByTagName('img'));
        var firstImage = this._images[0].cloneNode(false);  
        firstImage.className = 'imageThumbnail';    
        $addHandlers(firstImage, { 'click' : this._showGallery }, this);

        var link = $get('ImageGalleryLink', this.get_element());
        if (link)
        {
            $addHandlers(link, { 'click' : this._showGallery }, this);
        }
        $addHandlers(document, { 'keypress' : function(eventArgs)
                                            {
                                                if(eventArgs.charCode == Sys.UI.Key.esc || eventArgs.charCode == Sys.UI.Key.enter)
                                                {
                                                   if (this._galleryBackground != null)
                                                    {
                                                        this._closeGallery(eventArgs);
                                                    }
                                                }
                                            } 
                                }, this);
        $addHandlers(window, {'resize' : this._onWindowResize}, this);
        $addHandlers(window, {'scroll' : this._onWindowScroll}, this);
        this.get_element().insertBefore(firstImage, this.get_element().firstChild);
    },
    
    dispose : function()
    {
        Array.forEach(this._images, this._clearImageHandlers, null);
        delete this._images;
        this._images = null;
        
        VikingLine.ImageGallery.callBaseMethod(this, 'dispose');
    },
    
    _onWindowResize : function(eventArgs)
    {
        if (this._galleryContainer != null)
        {
            //this._galleryContainer.style.top = ScrollTop + 10 + 'px';
            var bounds = Sys.UI.DomElement.getBounds(this._galleryContainer);
            if (bounds.height + 25 >= PageSize.getWindowSize().windowHeight)
            {
                this._galleryContainer.style.top = '20px';
            }
            else
            {
                this._galleryContainer.style.top = (PageSize.getWindowSize().windowHeight/2) - (bounds.height / 2 - ScrollingOffset.Get().y) - 20 + 'px';
            }
            
            this._galleryContainer.style.left = (PageSize.getWindowSize().pageWidth/2) - 250 + 'px';
            var bounds = Sys.UI.DomElement.getBounds(document.body);
            this._galleryBackground.style.width = PageSize.getScroll().x + 'px';
            var height = PageSize.getWindowSize().pageHeight;
            if (Sys.Browser.agent == Sys.Browser.InternetExplorer)
                height += 6;
            this._galleryBackground.style.height = height + 'px';  //bounds.height + 5 + 'px'; //PageSize.getScroll().y + ScrollingOffset.Get().y + 5 + 'px';
        }
    },
    
    _onWindowScroll : function(eventArgs)
    {
        var scrollPos = 0;
        if (window.pageYOffset)
            scrollPos = window.pageYOffset;
        else
            scrollPos = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
            
        if (this._galleryContainer != null)
        {
            var bounds = Sys.UI.DomElement.getBounds(this._galleryContainer);
            if (bounds.height + 25 >= PageSize.getWindowSize().windowHeight)
            {
                this._galleryContainer.style.top = '20px';
            }
            else
            {
                this._galleryContainer.style.top = (PageSize.getWindowSize().windowHeight/2) - (bounds.height / 2 - ScrollingOffset.Get().y) - 20 + 'px';
            }
        }
    },
    
    _showGallery : function(eventArgs)
    {
        var div = document.createElement('div');
        div.className = 'imageGalleryBackground';
        var preloader = document.createElement('div');
        preloader.className = 'preloader';
        preloader.style.top = PageSize.getWindowSize().windowHeight/2 + 'px';
        preloader.style.left = PageSize.getWindowSize().pageWidth /2 + 'px';
        preloader.appendChild(document.createTextNode('Laddar...'));
        this._preloader = preloader;
        document.body.appendChild(this._preloader);
        
//        var bBounds = Sys.UI.DomElement.getBounds(document);
//        if (bBounds && bBounds.width > 0 && bBounds.height > 0)
//        {
//            div.style.width = bBounds.width + 'px';
//            div.style.height = bBounds.height + 'px';
//        }
        
        var bounds = Sys.UI.DomElement.getBounds(document.body);
        div.style.width = PageSize.getScroll().x + 'px';
        var height = PageSize.getWindowSize().pageHeight;
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer)
            height += 6;
        div.style.height = height + 'px';  //bounds.height + 5 + 'px'; //PageSize.getScroll().y + ScrollingOffset.Get().y + 5 + 'px';
        this._galleryBackground = div;
        $addHandlers(this._galleryBackground, { 'click' : this._closeGallery }, this);
        document.body.appendChild(div);
        this._createGalleryContainer();
    },
    
    _setRequiredStyles : function()
    {
        this._galleryContainer.style.display = 'block';
        document.body.removeChild(this._preloader);
        
        /* ------------ IE6 'select' overlapping fix ----------------- */
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version == 6)
        {
            var selects = $get('bookOnlineContainer').getElementsByTagName('select');
            Array.forEach(selects, function(elem, index, array) {elem.style.visibility = 'hidden'; }, null);
        }
    },
    
    _createGalleryContainer : function()
    {
        var containerDiv = document.createElement('div');
        containerDiv.className = 'imageContainer';
        this._galleryContainer = containerDiv;
        this._galleryContainer.setAttribute('id', 'GalleryContainerDivElement');
        var bounds = Sys.UI.DomElement.getBounds(this._galleryBackground);
//        this._galleryContainer.style.top = bounds.height > 0 ? (bounds.height / 2) - 250 + 'px': '100px';
//        this._galleryContainer.style.left = bounds.width > 0 ? (bounds.width / 2) - 250 + 'px' : '100px';
//        this._galleryContainer.style.top = (PageSize.getWindowSize().windowHeight/2) - Sys.UI.DomElement.getBounds(containerDiv).height/2 - ScrollingOffset.Get().y - 10 + 'px';
//        this._galleryContainer.style.left = (PageSize.getWindowSize().pageWidth/2)- Sys.UI.DomElement.getBounds(containerDiv).width/2 - ScrollingOffset.Get().x + 'px';
        
        // ----------- Creating gallery divs ----------------
        
        var imageDisplayDiv = document.createElement('div');
        imageDisplayDiv.className = 'imageDisplay';
        
            /* ----------- Delayed displaying functionality ------------- */
        this._galleryContainer.style.display = 'none';
        var theCallBack = Function.createDelegate(this, this._setRequiredStyles);
        this._timer = setTimeout(theCallBack, 1000);
            /* ----------------------------------------------------------- */
        
        imageDisplayDiv.appendChild(this._createCloseDiv());
        
        var imageList = document.createElement('div');
        imageList.className = 'imageList';
        
        this._galleryContainer.appendChild(imageList);
        this._galleryContainer.appendChild(imageDisplayDiv);
                
        var firstImage = this._images[1].cloneNode(false);
       
        imageDisplayDiv.appendChild(firstImage);
        
        Array.forEach(this._images, this._addImageToImageList, this);
        
        // --------------------------------------------------
        
        document.body.appendChild(this._galleryContainer);
        //this._galleryContainer.style.top = ScrollTop + 30 + 'px';
        if (this._galleryContainer != null)
        {
            var bounds = $(this._galleryContainer).getDimensions(); //Sys.UI.DomElement.getBounds(this._galleryContainer);
            if (bounds.height == 0) bounds = Sys.UI.DomElement.getBounds(this._galleryContainer);
            var windowHeight = PageSize.getWindowSize().windowHeight;
            if (bounds.height + 25 >= PageSize.getWindowSize().windowHeight)
            {
                this._galleryContainer.style.top = '20px';
            }
            else
            {
                var documentBounds = Sys.UI.DomElement.getBounds(document.body);
                var requiredTop = (windowHeight/2) - (bounds.height/2 - ScrollingOffset.Get().y) - 20;
                
                //document.title = String.format("{0} - {1} - {2} - {3} - {4}", requiredTop, bounds.height, bounds.width, windowHeight, ScrollingOffset.Get().y);
                //document.title = String.format("{0} - {1}", documentBounds.height, documentBounds.width);
                //this._galleryContainer.style.top = Math.round(requiredTop) + 'px';      
                var left = (PageSize.getWindowSize().pageWidth/2) - 250;          
                new Effect.Move(this._galleryContainer, { x : left, y : requiredTop, mode : 'absolute' });
            }
        }
        this._galleryContainer.style.left = (PageSize.getWindowSize().pageWidth/2) - 250 + 'px';
        $addHandlers(this._galleryContainer, { 'click' : this._closeGallery }, this);
    },
    
    _createCloseDiv : function()
    {
        var closeDiv = document.createElement('div');
        closeDiv.className = 'closeDiv';
        return closeDiv;
    },
    
    _addImageToImageList : function(arrayElement, index, array)
    {
        /*if (index == 0) return;
        var copy = arrayElement.cloneNode(false);
        copy.className = 'singeGalleryImage';
        $addHandlers(copy, { 'click' : this._imageClicked }, this);
        this._galleryContainer.childNodes[0].appendChild(copy);*/ 
        // Above is old code when preloaded images were used for both generating
        // thumbnails and big pictures
        
        if (index == 0) return;
        var image = document.createElement('img');
        image.src = arrayElement.src.replace(/_big/, '_thumb');
        image.alt = arrayElement.alt;
        image.title = arrayElement.alt;
        $addHandlers(image, { 'click' : this._imageClicked }, this);
        this._galleryContainer.childNodes[0].appendChild(image);
    },
    
    _findImageIndex : function(img)
    {
        var src = img.src;
        src = src.replace(/_thumb/, '_big');
        for (var i = 0; i < this._images.length; i++)
        {
            if (this._images[i].src == src)
                return i;
        }
        return 1;
    },
    
    _clearImageHandlers : function (arrayElement, index, array)
    {
        if (arrayElement._events)
            $clearHandlers(arrayElement);
    },
    
    _imageClicked : function(eventArgs)
    {
        var index = this._findImageIndex(eventArgs.target);
        
        //bottom is old line of code see comment in _addImageToImageList function
        //var image = eventArgs.target.cloneNode(false);
        
        var image = this._images[index].cloneNode(false);
        
        while (this._galleryContainer.childNodes[1].hasChildNodes())
        {
            this._galleryContainer.childNodes[1].removeChild(this._galleryContainer.childNodes[1].firstChild);
        }
        
        this._galleryContainer.childNodes[1].appendChild(this._createCloseDiv());
        this._galleryContainer.childNodes[1].appendChild(image);
        
        eventArgs.stopPropagation();
    },
    
    _closeGallery : function(eventArgs)
    {
        document.body.removeChild(this._galleryBackground);
        this._galleryBackground = null;
        
        document.body.removeChild(this._galleryContainer);
        this._galleryContainer = null;
        
        /* ------------ IE6 'select' overlapping fix ----------------- */
        if (Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version == 6)
        {
            var selects = $get('bookOnlineContainer').getElementsByTagName('select');
            Array.forEach(selects, function(elem, index, array) {elem.style.visibility = 'visible'; }, null);
        }
        
        if (eventArgs.charCode)
        {
            if (eventArgs.charCode == Sys.UI.Key.enter)
            {
                eventArgs.preventDefault();
                //eventArgs.stopPropagation();
            }
        }
    }
}

VikingLine.ImageGallery.registerClass('VikingLine.ImageGallery', Sys.UI.Control);

function pageLoad()
{
    var igContainer = $get('ImageGalleryContainer');
    if (igContainer)
    {
        $create(VikingLine.ImageGallery, null, null, null, igContainer);       
    }
    
    ScrollTop = document.body.scrollTop;
    if (ScrollTop == 0)
    {
        if (window.pageYOffset)
            ScrollTop = window.pageYOffset;
        else
            ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
    }
}

function OnWindowResize(eventArgs)
{
    var theGContainer = $get('ImageGalleryContainer');
}









/*MoviePlay.js*/
var MovieSize = 
{ 
    width : null,
    height : null
}

function MoviePlay(movieIdNumber, width, height)
{
    MovieSize.width = width;
    MovieSize.height = height;
    //alert(movieIdNumber); return;
    var wRequest = new Sys.Net.WebRequest();
    // could be extended with size and other necessary params?
    var body = 'MovieIdNumber=' + movieIdNumber;
    wRequest.set_body(body);
    wRequest.set_httpVerb('POST');
    wRequest.add_completed(OnGetMovieContentCompleted);
    wRequest.set_url('/Pages/mogul/Dummies/mogul/movieContentGen.asp');

    $get('ProgressIndicatorDiv').style.display = 'block';
    wRequest.invoke();
    
    $addHandler(window, 'scroll', OnWindowScroll);
    $addHandler(window, 'resize', OnWindowResize);
    $addHandler(document, 'keypress', function(eventArgs){
        if(eventArgs.charCode == Sys.UI.Key.esc || eventArgs.charCode == Sys.UI.Key.enter)
        {
            var background = $get('MoviePlayBackground');
            if (background)
            {
                CloseMovie(eventArgs);
            }
            if (eventArgs.charCode == Sys.UI.Key.enter)
            {
                eventArgs.preventDefault();
            }
        }
    });
}

function ExecuteMovie()
{
    AddBackground();
    $addHandler($get('closeDiv'), 'click', CloseMovie);
    Effect.Appear($('MoviePlayBackground'),{duration: 0.9, from : 0.0 , to : 0.2, afterFinish : function()
                                                                                                {
                                                                                                     SetMovieVisibility(true); 
                                                                                                } });
}

function OnWindowScroll(eventArgs)
{
    
    var mpw = $get('MoviePlayWrapper');
    if (mpw)
    {   
        var scrollPos = 0;
        if (window.pageYOffset)
            scrollPos = window.pageYOffset;
        else
            scrollPos = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
        
        var bounds = Sys.UI.DomElement.getBounds(mpw);
        if (bounds.height + 25 >= PageSize.getWindowSize().windowHeight)
        {
            mpw.style.top = '10px';
        }
        else
        {
            mpw.style.top = (PageSize.getWindowSize().windowHeight/2) - (MovieSize.height/2 - ScrollingOffset.Get().y) - 20 + 'px';
        }
        //mpw.style.top = ScrollTopPosition() + 75 + 'px';
        //mpw.style.top = (PageSize.getWindowSize().windowHeight/2) - (MovieSize.height/2 - ScrollingOffset.Get().y) - 20 + 'px';
    }
}

function OnWindowResize(eventArgs)
{
    var mpw = $get('MoviePlayWrapper');
    if (mpw)
    {   
        //mpw.style.top = ScrollTopPosition() + 75 + 'px';
        mpw.style.top = (PageSize.getWindowSize().windowHeight/2) - (MovieSize.height/2 - ScrollingOffset.Get().y) - 20 + 'px';
        mpw.style.left = (PageSize.getWindowSize().pageWidth/2) - (MovieSize.width/2 - ScrollingOffset.Get().x) + 'px';
        var background = $get('MoviePlayBackground');
        if (background)
        {
            background.style.width = PageSize.getScroll().x+'px';
            background.style.height = Sys.Browser.agent == Sys.Browser.InternetExplorer? PageSize.getWindowSize().pageHeight + 6 + 'px' : PageSize.getWindowSize().pageHeight + 'px';
        }
    }
}

function SetMovieVisibility(visible)
{
    var moviePlayWrapper = $get('MoviePlayWrapper');
    if (visible == true)
    {
        var background = $get('MoviePlayBackground');
        if (typeof(background) != 'undefined')
        {
            var bounds = Sys.UI.DomElement.getBounds(background);
//            moviePlayWrapper.style.top = (bounds.height/2 - MovieSize.height/2) + 5 + 'px';
            //moviePlayWrapper.style.top = ScrollTopPosition() + 75 + 'px';
            //moviePlayWrapper.style.left = (bounds.width/2 - MovieSize.width/2) + 'px';
            
            moviePlayWrapper.style.top = (PageSize.getWindowSize().windowHeight/2) - (MovieSize.height/2 - ScrollingOffset.Get().y) - 20 + 'px';
            moviePlayWrapper.style.left = (PageSize.getWindowSize().pageWidth/2) - (MovieSize.width/2 - ScrollingOffset.Get().x) + 'px';
            
            moviePlayWrapper.style.width = MovieSize.width + 21 + 'px';
            moviePlayWrapper.style.height = MovieSize.height + 21 + 'px';
        }
        moviePlayWrapper.style.display = 'block';
    }
    else
    {
        moviePlayWrapper.style.display = 'none';
    }
}

function AddBackground()
{
    var background = document.createElement('div');
    background.id = 'MoviePlayBackground';
    background.className = 'imageGalleryBackground';
    background.style.width = PageSize.getScroll().x+'px';
    background.style.height = Sys.Browser.agent == Sys.Browser.InternetExplorer? PageSize.getWindowSize().pageHeight + 6 + 'px' : PageSize.getWindowSize().pageHeight + 'px';  
    // previous version: PageSize.getScroll().y+ScrollingOffset.Get().y + 5 + 'px';
    
    document.body.appendChild(background);
    $addHandler(background, 'click', CloseMovie);
}

function RemoveBackground()
{
    var background = $get('MoviePlayBackground');
    
    if (background)
    {
        $clearHandlers(background);
        document.body.removeChild(background);
    }
}

function  CloseMovie(eventArgs)
{
    RemoveBackground();
    eventArgs.stopPropagation();
    var moviePlayWrapper = $get('MoviePlayWrapper');
    var closeDiv = $get('closeDiv');
    $clearHandlers(closeDiv);
    SetMovieVisibility(false);
    var movieContentPH = $get('MoviePlayContentPlaceHolder');
    while (movieContentPH.hasChildNodes())
    {
        movieContentPH.removeChild(movieContentPH.firstChild);
    }
}

function OnGetMovieContentCompleted(executor, eventArgs)
{
    var contentDiv = $get('MoviePlayContentPlaceHolder');
    $get('ProgressIndicatorDiv').style.display = 'none';
    var ok = (executor.get_statusCode() >= 200) && (executor.get_statusCode() <= 299)
    if (ok)
    {
        contentDiv.innerHTML = executor.get_responseData();
        ExecuteMovie();
    }
    else
    {
        contentDiv.innerHTML = String.format('Error during getting movie content: {0}', executor.get_statusText());
    }
}

function ScrollTopPosition()
{
    if (window.pageYOffset)
        return window.pageYOffset;
    else
        return (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
}
