general.namespace('SW.Controls');

(function () {
    /**
     * ctor
     */
    var BuoyChart = SW.Controls.BuoyChart = function(chartContainerParent, initialDataPointId){
        //alert( "BuoyChart.Constructor" );
        //alert( "chartContainerParent: " + chartContainerParent );
        //alert( "initialDataPointId: " + initialDataPointId );
        this.uniqueId = YAHOO.util.Dom.generateId();
        this.currentDataPointId = initialDataPointId; // holds the id buoy that is currently displayed
        this.className = "buoy-chart-container";
        this.chartContainerParent = chartContainerParent;
        this.userSavedBuoyId = null;
        this.onAddSuccess = new YAHOO.util.CustomEvent("onAddSuccess", this, false, YAHOO.util.CustomEvent.FLAT);
        this.onDeleteSuccess = new YAHOO.util.CustomEvent("onDeleteSuccess", this, false, YAHOO.util.CustomEvent.FLAT);
    };
    BuoyChart.prototype.constructor = BuoyChart;
    
    /**
     * handles clicking on the add link
     *
     * @return void
     */
    BuoyChart.prototype.onClickAddLink = function (evt) {
        YAHOO.util.Event.preventDefault(evt);
        if (SWMap.userPrefs.isUserLoggedIn) {
            this.showActivity();
            var cObj = YAHOO.util.Connect.asyncRequest(
                'POST',
                '/WebServices/UserSavedBuoy.asmx/AddBuoy?r=' + general.rand(),
                // callback object
                {
                    argument: {},
                    success: this.addSuccess, 
                    failure: this.addFailure,
                    scope: this
                }, 
                // POST body
                "{dataPointId:" + this.currentDataPointId + "}" 
            );
        }
        else {
            this.displayError('<div style="text-align:left">You must be signed in to save buoys<br />&raquo <a href="/login/">Sign In</a><br />&raquo <a href="/signup/">Create an Account</a></div>');
        }
    };
    
    /**
     * success of add
     *
     * @return void
     */
    BuoyChart.prototype.addSuccess = function (response) {
        this.hideActivity();
        this.displayMessage("Added to Saved Buoys");
        this.onAddSuccess.fire();
    };
    
    /**
     * failure of add
     *
     * @return void
     */
    BuoyChart.prototype.addFailure = function (response) {
        this.hideActivity();
        this.showAddLink();
        this.displayError("Failed adding");
    };
    
    /**
     * handles clicking on the remove link
     *
     * @return void
     */
    BuoyChart.prototype.onClickRemoveLink = function (evt) {
        YAHOO.util.Event.preventDefault(evt);
        this.showActivity();
        if (confirm("Are you sure you want to remove this buoy?")) {
            var cObj = YAHOO.util.Connect.asyncRequest(
                'POST',
                '/WebServices/UserSavedBuoy.asmx/DeleteBuoy?r=' + general.rand(),
                // callback object
                {
                    argument: {},
                    success: this.deleteSuccess, 
                    failure: this.deleteFailure,
                    scope: this
                }, 
                // POST body
                "{userSavedBuoyId:" + this.userSavedBuoyId + "}" 
            );
        }
        else {
            this.showRemoveLink();
        }
    };
    
    /**
     * success of add
     *
     * @return void
     */
    BuoyChart.prototype.deleteSuccess = function (response) {
        this.hideActivity();
        this.chartContainer.style.display = "none";
        this.onDeleteSuccess.fire();
    };
    
    /**
     * failure of add
     *
     * @return void
     */
    BuoyChart.prototype.deleteFailure = function (response) {
        this.hideActivity();
        this.showRemoveLink();
        this.displayError("Failed removing");
    };
    
    /**
     * attaches an iframe, which contains the chart flash, to the container
     *
     * @return void
     */
    BuoyChart.prototype.render = function () {
        //alert( "BuoyChart.render" );
        this.chartContainer = document.createElement("div");
        this.chartContainer.style.position = "relative";
        if (this.className) this.chartContainer.className = this.className;
                
        this.message = document.createElement("div");
        this.message.className = "buoy-message-notice";
        
        this.addLink = document.createElement("a");
        this.addLink.innerHTML = "Save Buoy";
        this.addLink.href = "#";
        this.addLink.className = "buoy-add-link";
        this.addLink.style.display = "none";
        YAHOO.util.Event.addListener(this.addLink, "click", this.onClickAddLink, this, true);
        
        this.removeLink = document.createElement("a");
        this.removeLink.innerHTML = "Remove Buoy";
        this.removeLink.href = "#";
        this.removeLink.className = "buoy-remove-link";
        this.removeLink.style.display = "none";
        YAHOO.util.Event.addListener(this.removeLink, "click", this.onClickRemoveLink, this, true);
                        
        this.activityIndicator = document.createElement("img");
        this.activityIndicator.src = "/assets/images/loading.gif";
        this.activityIndicator.width = "20";
        this.activityIndicator.height = "20";
        this.activityIndicator.alt = "";
        this.activityIndicator.className = "buoy-activity-indicator";
        this.activityIndicator.style.display = "none";
        
        this.iframe = general.createIFrame(this.uniqueId + "_chartContainer", 256, 403, "/dep/buoy.aspx");
        //alert( this.iframe );

        // add items to container
        this.chartContainer.appendChild(this.iframe);
        this.chartContainer.appendChild(this.addLink);
        this.chartContainer.appendChild(this.removeLink);
        this.chartContainer.appendChild(this.activityIndicator);
        this.chartContainer.appendChild(this.message);
        // add to doc
        this.chartContainerParent.appendChild(this.chartContainer);
        
        this.iframeWindow = general.getFrameWindow(this.iframe);
        var iframeOnload = function(){
            //alert( "BuoyChart.render.writeFlash" );
            BuoyChart.writeFlash(this.iframeWindow.document.getElementById("flashContainer"));
            //alert( "BuoyChart.render.displayData" );
            this.displayData();
        };    
        var listenerAdded = YAHOO.util.Event.addListener(this.iframeWindow, "load", iframeOnload, this, true);
        //alert( "Listener added? " + listenerAdded.toString() );
    };
       
    
    /**
     * gets the DOM element of the flash chart object
     *
     * @return object  the DOM element
     */
    BuoyChart.prototype.getFlashInstance = function () {
        return this.iframeWindow.document.getElementById("flashObjectCharts");
    };
    
    
    /**
     * show a message
     *
     * @param string  if blank, screen will still be obscured
     * @param bool  if it is an error, default false
     *
     * @return void
     */
    BuoyChart.prototype.displayMessage = function (message, isError) {

        var msgObj = this.message;
        setTimeout(function() {msgObj.style.display = "none";}, 0);
        if (message) {
            setTimeout(
                function() {
                    msgObj.className = (isError ? "buoy-message-error" : "buoy-message-notice");
                    msgObj.innerHTML = message;
                    msgObj.style.display = "block";
                },
                0
            );
        }
    };
    
    BuoyChart.prototype.displayError = function (message) {
        this.displayMessage(message, true);
    };
    
    
    
    /**
     * hides message
     *
     * @return void
     */
    BuoyChart.prototype.hideMessage = function () {
        this.message.style.display = "none";
    };
        
    
    /**
     * show add button
     *
     * @return void
     */
    BuoyChart.prototype.showAddLink = function () {
        this.addLink.style.display = "block";
        this.hideRemoveLink();
        this.hideActivity();
    };
    
    /**
     * show add button
     *
     * @return void
     */
    BuoyChart.prototype.hideAddLink = function () {
        this.addLink.style.display = "none";
    };
    
    /**
     * show remove button
     *
     * @return void
     */
    BuoyChart.prototype.showRemoveLink = function () { 
        this.removeLink.style.display = "block";
        this.hideAddLink();
        this.hideActivity();
    };
    

    
    /**
     * show remove button
     *
     * @return void
     */
    BuoyChart.prototype.hideRemoveLink = function () {
        this.removeLink.style.display = "none";
    };
        
    /**
     * show activity
     *
     * @return void
     */
    BuoyChart.prototype.showActivity = function () { 
        this.hideAddLink();
        this.hideRemoveLink();
        this.activityIndicator.style.display = "block";
    };
    
    /**
     * hide activity
     *
     * @return void
     */
    BuoyChart.prototype.hideActivity = function () { 
        this.activityIndicator.style.display = "none";
    };
    
    
    /**
     * sets the dataPointId of the buoy
     *
     * @return void
     */
    BuoyChart.prototype.displayData = function (dataPointId) {
        //alert( "BuoyChart.displayData" );
        if (!dataPointId) {
            //alert( "displayData: if( !dataPointId )" );
            dataPointId = this.currentDataPointId;
        }
        if (dataPointId) {
            //alert( "displayData: if( dataPointId )" );
            var attemptDrawCount = 0;
            var me = this;
            // closure for retries
            var attemptDraw = function () {
                //alert( "displayData: attemptDraw - Count: " + attemptDrawCount );
                var theFlashInstance = me.getFlashInstance();
                if (theFlashInstance && theFlashInstance.setBuoy) {
                    setTimeout(
                        function(){
                            theFlashInstance.setBuoy(dataPointId);
                        },
                        0
                    );
                    // save the successful dataPointId
                    me.currentDataPointId = dataPointId;
                    me.hideMessage();
                }
                else if (attemptDrawCount++ < 250) { // try a lot of times (2 minutes about)
                    setTimeout(attemptDraw, 250);
                }
                // if first attempt hasn't been made, ask user to click to show
                // this fixes bugs with browser not being able to call flash functions when off screen the first time
                else if (false && !me.firstAttempt) {
                    me.displayMessage("<a href='#' onclick='top.SWMap.regionDataTabs.displayRegionData();return false;'>Click to Load Charts</a><br />The charts will load automatically when you change regions from now on.");
                    me.firstAttempt = true;
                }
                else {
                    me.displayMessage("Failed drawing chart", true);
                }
                
            }; // end of closure
            attemptDraw();
        }
    };
    
    /**
     * static method for writing out flash object
     * depends on deconcept flash object
     *
     * @param object  DOM element to write flash into
     *
     * @return void
     */
    BuoyChart.writeFlash = function (flashContainer) {
        
        var so = new SWFObject(
            "/assets/flash/buoy.swf?r=1&unit=" + SWMap.userPrefs.uom + "&time=" + SWMap.userPrefs.timeFormat,
            "flashObjectCharts", 
            "256", 
            "403", 
            "8", 
            "#FFFFFF"
        );
        so.addParam("wmode", "transparent"); 
        so.addParam("quality", "high"); 
        so.write(flashContainer);
        
        //alert( "/assets/flash/buoy.swf?r=1&unit=" + SWMap.userPrefs.uom + "&time=" + SWMap.userPrefs.timeFormat );
        //alert( "END: BuoyChart.writeFlash" );
        //alert( "ATTEMPT: this.prototype.displayData()" );
        this.protoype.displayData();
    };

    
   
    
})();