﻿general.namespace('SW.Controls');

(function() {

    var RegionTrail = SW.Controls.RegionTrail = function(map, trailDiv) {

        this.map = map;
        this.trailDiv = trailDiv;
        this.currentLastRegion = null;
        this.headerText = document.getElementById("report-header-title");
        var currentPulldown = null;

        function onClick(evt) {
            var target = evt.target || evt.srcElement;

            if (target.isSearchButton) {
                inspectorManager.showSearch();
                currentPulldown.style.display = 'none';
                currentPulldown = null;
            }
            else {

                // find target and zoom on it if its a region button
                while (true) {
                    if (target.id === trailDiv) { // traversal finished without finding a region button
                        break;
                    }

                    if (target.region) { // if region button found
                        if (currentPulldown) { // a region without children won't have a pulldown
                            currentPulldown.style.display = 'none';
                            currentPulldown = null;
                        }
                        target.region.centerAndZoomOnMe();
                        SWMap.perspectiveView.close(); // perspective view might be open
                        break;
                    }

                    target = target.parentNode;
                }
            }

            // suppress default action
            if (evt.preventDefault) {
                evt.preventDefault();
            }
            else {
                evt.returnValue = false;
            }

            return false;
        }


        function onMouseover(evt) {
            var target = evt.target || evt.srcElement;

            if (target.isRegionButton) {
                if (target.hasChildren) {

                    var newPulldown = target.childNodes[1]; // second node is the pulldown (first node is the button text)

                    if (currentPulldown !== newPulldown) {

                        if (currentPulldown) {
                            currentPulldown.style.display = 'none';
                        }

                        newPulldown.style.marginLeft = '-' + (target.offsetWidth - 20) + 'px';  // has to be set here because offsetWidth is not defined until the region trail is added to the DOM
                        newPulldown.style.display = 'inline';
                        currentPulldown = newPulldown;
                    }

                }
                else { // remove pulldown when hovering over childless region button 
                    if (currentPulldown) {
                        currentPulldown.style.display = 'none';
                        currentPulldown = null;
                    }
                }

            }

            if (target.isHighlightable && !target.isTrailMember && target.hasChildren) {
                target.style.background = 'url(/assets/images/crumbs-more-over-blue.gif) right top no-repeat';
                target.style.border = 'none';
                target.style.color = '#333';
            }

            return false;
        }


        function onMouseout(evt) {
            var target = evt.target || evt.srcElement;
            var entered = evt.relatedTarget || evt.toElement;

            if (currentPulldown) {

                if (!general.isNodeOrChildOf(entered, breadcrumbDiv)) {
                    currentPulldown.style.display = 'none';
                    currentPulldown = null;
                }
            }

            if (target.isHighlightable && !target.isTrailMember && target.hasChildren) {
                target.style.background = 'url(/assets/images/crumbs-more-blue.gif) right top no-repeat';
                target.style.color = '#fff';
            }


            return false;
        }

        var breadcrumbDiv = document.getElementById(trailDiv);

        general.addListener(breadcrumbDiv, 'click', onClick);
        general.addListener(breadcrumbDiv, 'mouseover', onMouseover);
        general.addListener(breadcrumbDiv, 'mouseout', onMouseout);

    };
    RegionTrail.prototype.constructor = RegionTrail;


    /*  
    Return an array of the regions which make up the trail from the center point of the current view. First finds tightest 
    containing region, then goes up the parent hierarchy for the rest. (Effectively, the trail always starts with the world region.)
    */
    RegionTrail.prototype.getRegionTrail = function(region) {
        var trail;

        var map = this.map;
        var zoom = map.getZoom();

        if (zoom > 2 || region) {
            trail = [];
            var container = region || map.getCenter().getTightestContainingRegion(zoom);

            do {
                trail.push(container);
                container = container.parent;
            } while (container !== null);

            trail.reverse();
        }
        else {
            trail = [SWMap.world.regionsByZoom[1][0]]; // region trail is just the world (this logic should change if we ever add any regions at zoom 2)
        }

        return trail;
    };

    RegionTrail.prototype.flashCurrentRegion = function(evenIfSameAsPrevious) {
        var button = this.currentRegionButton;
        if (button) {
            button.style.backgroundColor = '#fc6';

            window.setTimeout(
                    function() {
                        button.style.backgroundColor = '';
                    },
                    1100
                );
        }
    };


    /* display the 3D view associated with the last region in the trail (if it has an associated perspective) */
    RegionTrail.prototype.display3D = function() {
        if (this.currentLastRegion.associatedPerspectiveId) {
            SWMap.perspectiveView.display(this.currentLastRegion.associatedPerspectiveId);
        }
    };

    /* 
    * Places breadcrumb links in trailDiv based upon the current view of the 
    * map  (pass string of a div's id for trailDiv) 
    */
    RegionTrail.prototype.updateTrail = function(region) {
        var map = this.map;
        var trailDiv = this.trailDiv;

        // get the array of regions that is the current trail
        var regionTrail = this.getRegionTrail(region);

        lastRegion = regionTrail[regionTrail.length - 1];
        if (lastRegion !== this.currentLastRegion) {  // only update trail if it has changed
            this.currentLastRegion = lastRegion;

            // add each breadcrumb
            var newChildren = [];

            var regionList = document.createElement('ul');
            regionList.className = "region-list";

            for (var i = 0; i < regionTrail.length; i++) {

                var region = regionTrail[i];

                var item = document.createElement('li');
                item.isRegionButton = true;
                item.hasChildren = (region.children ? true : false);
                item.innerHTML = region.name + (item.hasChildren ? '' : ''); // this is wher > would be
                item.region = region;
                item.isHighlightable = true;
                item.className = item.hasChildren ? 'region-more-button' : '';

                // make the last region name highlight for a moment indicating a region change
                if (i === regionTrail.length - 1) {
                    this.currentRegionButton = item;
					//add current region to header
                    this.headerText.innerHTML = region.name + '&nbsp;&nbsp;Report <small><a href="javascript:general.moveWindow(\'textReport\');">view text report</a></small>';
					SWMap.animationSelectionControl.setButtonTooltips(region.name);
                    if (item.region.associatedPerspectiveId) {
                        SWMap.animationSelectionControl.display3DButton();
                    }
                    else {
                        SWMap.animationSelectionControl.hide3DButton();
                    }
                    this.flashCurrentRegion();
                }

                // add '>' pulldown after all regions except the last region if it doesn't have any children
                if (item.hasChildren) {
                    // create pulldown popup
                    var pulldown = document.createElement('div');
                    pulldown.className = "region-overlay-container";
                    pulldown.style.display = 'none';
                    if (YAHOO.env.ua.webkit !== 0) {
                        pulldown.style.marginTop = '18px';
                    }
                    pulldown.isPulldown = true; // used by mouse handler               
                    var childrenMenu = document.createElement('ul');
                    var nextRegion = ((i === regionTrail.length) ? null : regionTrail[i + 1]);

                    // create region links within the pulldown
                    for (var j in region.children) {
                        var child = region.children[j];
                        var regionLink = document.createElement('li');

                        regionLink.innerHTML = child.name;
                        regionLink.region = child;
                        regionLink.isHighlightable = true;

                        // if child is part of the trail, give it highlight of a selected item
                        if (nextRegion && child.name === nextRegion.name) {
                            regionLink.className = 'selectedListItem';
                            regionLink.isTrailMember = true;
                        }
                        else {
                            regionLink.className = ' unselectedListItem';
                        }

                        childrenMenu.appendChild(regionLink);
                    }

                    pulldown.appendChild(childrenMenu);
                    // add advanced search button at end of pulldown
                    var search = document.createElement('div');
                    search.className = "region-search-box";
                    search.innerHTML = "Can't find your spot? Advanced Search";
                    search.isSearchButton = true;
                    pulldown.appendChild(search);
                    item.appendChild(pulldown);
                }
                regionList.appendChild(item);
            }

            newChildren.push(regionList);
            general.replaceAllChildren(document.getElementById(trailDiv), newChildren);
        }
    };
    //////// END CLASS RegionTrail

})();

