general.namespace('SW.Controls');

(function () {

    //////CLASS PerspectiveView
    
        /* The 3d animated view of a region.
        
            When a 3d view is selected, sets its date and timezone properties, makes the
            view3d view visible, then passes itself to AnimationControl as an animation.
        */
        var PerspectiveView = SW.Controls.PerspectiveView = function (animSelectionControlContainer) {
            var me = this;
        
            // create the 3d view div
			//document.body.appendChild(
			document.getElementById("mapOverlayContainer").appendChild(
                this.containerDiv = 
                $C('div', null, {id: 'perspective-view'},
                    this.backgroundImg = 
                    $C('img', {position: 'absolute'}, {src: '/assets/images/spacer.gif', width: 512, height: 384}),
                    this.div = 
                    $C('div', {width: '512px', height: '384px', position: 'absolute'},
                        this.blankImg = 
                        $C('img', null, {src: '/assets/images/spacer.gif', width: 512, height: 384})
                    )
                )                
            );
            general.disableScrolling(this.containerDiv);
            

            // TEMP fix that makes 3d view switching not so ugly            
            this.defaultBackgroundImgHolder = new Image();
            this.defaultBackgroundImgHolder.src = '/assets/images/perspective-default-background.png';
            
            $id('map-control-subcontainer').appendChild(
                this.perspectiveControl = 
                $C('div', {display: 'none'}, {id: 'perspective-view-control'},
                    $C('div', null, {id: 'perspective-throbber-container'},
                        $C('img', null, {src: '/assets/images/loading-map-still.gif', id: 'perspective-throbber', width: 32, height: 32})
                    ),
                    $C('div', null, {id: 'perspective-view-control-name-container'},
                        this.perspectiveMenuButton = 
                        $C('div', null, {id: 'perspective-view-control-menu-button'},
                            this.nameField =
                            $C('span'),
                            this.nearbyPerspectivesMenu = 
                            $C('div', null, {id: 'perspective-view-control-menu'})
                        )
                    ),
                    this.leftButton = 
                    $C('img', null, {classes: 'perspectiveButton'}),
                    this.centerButton = 
                    $C('img', null, {classes: 'perspectiveButton'}),
                    this.rightButton = 
                    $C('img', null, {classes: 'perspectiveButton'}),
                    this.backButton = 
                    $C('img', null, {classes: 'perspectiveButtonClose', src: '/assets/images/btn-3d-close.gif'})
                )            
            );
            
            
            $handler(this.perspectiveMenuButton, 'click', 
                function (evt) {
                    YAHOO.util.Event.preventDefault(evt); return false;
                }
            );
            $handler(this.perspectiveMenuButton, 'mousedown', 
                function (evt) {
                    var target = evt.target || evt.srcElement;
                    
                    if (target.perspectiveId) {
                        me.nearbyPerspectivesMenu.style.display = 'none';
                        me.display(target.perspectiveId);
                    }
                    else {
                        me.nearbyPerspectivesMenu.style.display = 'block';
                    }
                    YAHOO.util.Event.preventDefault(evt);
                    return false;
                }
            );
            $handler(this.perspectiveMenuButton, 'mouseout', 
                function (evt) {
                    var entered = evt.relatedTarget || evt.toElement;
                    
                    if (!general.isNodeOrChildOf(entered, me.nearbyPerspectivesMenu)) {
                        me.nearbyPerspectivesMenu.style.display = 'none';
                    }
                    YAHOO.util.Event.preventDefault(evt);
                    return false;
                } 
            );                        
            
            this.leftButton.buttonType = 'left';
            this.centerButton.buttonType = 'center';
            this.rightButton.buttonType = 'right';           
            this.backButton.buttonType = 'off';
            
            $handler(this.leftButton, 'click', function (evt) {me.display(null, 'left');} );
            $handler(this.centerButton, 'click', function (evt) {me.display(null, 'center');} );
            $handler(this.rightButton, 'click', function (evt) {me.display(null, 'right');} );
            $handler(this.backButton, 'click', function (evt) {me.back();} );
            
            $handler(this.perspectiveControl, 'mouseover', function (evt) {me.onMouseOver(evt);} );
            $handler(this.perspectiveControl, 'mouseout', function (evt) {me.onMouseOut(evt);} );
            
            SW.Markers.DataType.PerspectiveView.clickHandler = function (pointId) {
                me.display(pointId);
            };
            
            this.mapControl = animSelectionControlContainer;
            this.perspectivesById = {};
            this.isPerspective = true; // used by the AnimationControl to distinguish perspective from regions
            this.isVisible = false;
            this.currentType = 'off';
        };
        
        
        /**/
        PerspectiveView.prototype.requestPerspective = function (pointId, type) {
            var me = this;
            
            function onRequestPerspectiveViewSuccess (response) {
                SWMap.loadingIndicator.removeLoad();
                var pointId = response.argument.pointId;
                var perspective = general.deserializeJSON(response.responseText);
                if (perspective) {
                    me.perspectivesById[pointId] = perspective;
                    me.display(pointId, response.argument.type);
                }
                else {
                    onRequestPerspectiveViewFailure(response);
                }
            }
        
            function onRequestPerspectiveViewFailure (error) {
                SWMap.loadingIndicator.removeLoad();
            }
            
            if (this.perspectivesById[pointId]) {
                this.display(pointId);
            }
            else {
        	    YAHOO.util.Connect.asyncRequest(
                    'POST',
                    '/WebServices/DataPoints.asmx/GetPerspectiveViewDetails?r=' + general.rand(), // url
                    {
                        success: onRequestPerspectiveViewSuccess,
                        failure: onRequestPerspectiveViewFailure,
                        argument: {
                            pointId: pointId,
                            type: type
                        }
                    },
                    JSON.encode({dataPointId: pointId})  // POST data
                );
                
                SWMap.loadingIndicator.addLoad();
            }
        };
        
        /*
            if pointId not already known, triggers request; successful request triggers display
        */
        PerspectiveView.prototype.display = function (pointId, type) {
            var animationControl = SWMap.animationControl;
        
            pointId = pointId || this.currentPointId;
            var newPoint = (pointId !== this.currentPointId);
            
            var perspective = this.perspectivesById[pointId];
            if (perspective) {
                this.currentPointId = pointId;
                    
                this.perspectiveId = pointId;
                this.timezoneName = perspective.TimeZoneName;
                this.timezoneOffset = perspective.UtcOffset;
                this.perspectiveName = perspective.Name;
                this.region2d = SWMap.world.regionsById[perspective.RegionId]; // this might be null in the future when some 3d views don't have associated 2d views
                
                if (this.region2d) {
                    SWMap.regionTrail.updateTrail(this.region2d);
                    SWMap.regionDataTabs.displayRegionData(this.region2d);
                }
                
                this.firstFrameDate =  (perspective.DateFirstAnimation) ? parseInt(perspective.DateFirstAnimation) * 1000 : null; // convert to millisecond
                this.lastFrameDate = (perspective.DateLatestAnimation) ? parseInt(perspective.DateLatestAnimation) * 1000 : null; // convert to millisecond
                
                this.left = perspective.HasLeft;
                this.center = perspective.HasCenter;
                this.right = perspective.HasRight;
                this.basePath = perspective.BasePath;
                
                if (!this.isVisible) {
                    this.mapControl.style.display = 'none';
                    this.perspectiveControl.style.display = 'block';
                }
                                
                this.setType(type, newPoint);
                this.setNearbyPerspectivesMenu(perspective);
                
                this.containerDiv.style.visibility = 'visible';
                this.isVisible = true;
            }
            else {
                this.requestPerspective(pointId, type);
            }
        };
        
        /**/
        PerspectiveView.prototype.setNearbyPerspectivesMenu = function (perspective) {
            this.nameField.innerHTML = perspective.Name;
            
            var listItems = [];
            var idx;
            for (var i = 0; i < perspective.NearbyPerspectiveNames.length; i++) {
                var name = perspective.NearbyPerspectiveNames[i];
                var perspectiveId = perspective.NearbyPerspectiveIds[i];
                
                var div = document.createElement('div');
                
                var viewButton = $createEl('a', div);
                viewButton.href = '#';
                viewButton.className = 'name-saved-view';
                viewButton.innerHTML = name;
                viewButton.perspectiveId = perspectiveId;
                
                listItems.push(div);
                
                if (name === perspective.Name) {
                    idx = i;
                }
            }
            
            this.nearbyPerspectivesMenu.style.top = (idx * 5) + 'px';
            general.replaceAllChildren(this.nearbyPerspectivesMenu, listItems);
        };
        
        /**/        
        PerspectiveView.prototype.setType = function (type, newPoint) {
            
            if (!this[type]) {
                if (this.center) {
                    type = 'center';
                } else if (this.right) {
                    type = 'right';
                } else {
                    type = 'left';
                }
            }
            
            if (this.currentType !== type || this.currentType === 'off' || newPoint) {
                this.currentType = type;
                
                this.setButtons(type);
                this.setBackground(this.basePath, type);
                SWMap.animationControl.setAnimation(this, type + '_height', null, null, newPoint);
                SWMap.historyControl.addState();
            }
        };
        
        
        /**/
        PerspectiveView.prototype.setButtons = function (type, hovered) {
            this.leftButton.className = 'perspectiveButton';
            this.centerButton.className = 'perspectiveButton';
            this.rightButton.className = 'perspectiveButton';
        
        
            if (type === 'left') {
                this.leftButton.src = '/assets/images/btn-3d-left-on.gif';
                this.leftButton.className = 'perspectiveButtonSelected';
            }
            else if (this.left && hovered === 'left') {
                this.leftButton.src = '/assets/images/btn-3d-left-hovered.gif';
            }
            else if (this.left) {  
                this.leftButton.src = '/assets/images/btn-3d-left-off.gif';
            }
            else { // disabled button
                this.leftButton.src = '/assets/images/btn-3d-left-disabled.gif';
                this.leftButton.style.cursor = 'default';
            }
            
            
            if (type === 'center') {
                this.centerButton.src = '/assets/images/btn-3d-center-on.gif';
                this.centerButton.className = 'perspectiveButtonSelected';
            }
            else if (this.center && hovered === 'center') {
                this.centerButton.src = '/assets/images/btn-3d-center-hovered.gif';
            }
            else if (this.center) {
                this.centerButton.src = '/assets/images/btn-3d-center-off.gif';
            }
            else {
                this.centerButton.src = '/assets/images/btn-3d-center-disabled.gif';
                this.centerButton.style.cursor = 'default';
            }
            
            
            if (type === 'right') {
                this.rightButton.src = '/assets/images/btn-3d-right-on.gif';
                this.rightButton.className = 'perspectiveButtonSelected';
            }
            else if (this.right && hovered === 'right') {
                this.rightButton.src = '/assets/images/btn-3d-right-hovered.gif';
            }
            else if (this.right) {
                this.rightButton.src = '/assets/images/btn-3d-right-off.gif';
            }
            else {
                this.rightButton.src = '/assets/images/btn-3d-right-disabled.gif';
                this.rightButton.style.cursor = 'default';
            }
            
            if (hovered === 'off') {
                this.backButton.src = '/assets/images/btn-3d-close-hovered.gif';
            } else {
                this.backButton.src = '/assets/images/btn-3d-close.gif';
            }
        };
        
        
        /**/
        PerspectiveView.prototype.onMouseOver = function (evt) {
            var target = evt.target || evt.srcElement;
            
            if (target.buttonType) {
                this.setButtons(this.currentType, target.buttonType);
            }
        };
        
        
        /**/
        PerspectiveView.prototype.onMouseOut = function (evt) {
            var relatedTarget = evt.relatedTarget || evt.toElement;
            
            if (!relatedTarget.buttonType) {
                this.setButtons(this.currentType, null);
            }
            
        };
        
        /* only gets rid of the 3d view; doesn't take you anywhere */
        PerspectiveView.prototype.close = function () {
            if (this.isVisible) {
                this.mapControl.style.display = 'block';
                this.perspectiveControl.style.display = 'none';
                this.containerDiv.style.visibility = 'hidden';
                this.isVisible = false;
                this.currentType = 'off';
            }
        };

        /*  */        
        PerspectiveView.prototype.back = function () {
            mapGeneral.centerAndZoomOnRegionAnimation(this.region2d, 'height');
            this.close();
        };
        
        
        /* set the landscape image; when ready,  */
        PerspectiveView.prototype.setBackground = function (basePath, viewDirection) {
            this.backgroundImg.src = '/assets/images/perspective-default-background.png';
            this.backgroundImg.src = 'http://st2.swellwatch.wetsand.com/3d/base/' + 
                basePath + '_' + viewDirection + '_base.jpg';
        };
    //////END CLASS
})();
