﻿
var PWSC = function() {
    var popupMarginBottom = 50;
    var heightSet = false;

    return {
        OpenOverlay: function(url) {
            //we explicitly set the height to make it work in IE6
            $("#overlay").height($(document).height());
            $("#iframe_wrapper").height($(document).height());
            // Position the overlay so it's visible even if the user has scrolled down the page.
            $("#iframe_wrapper").css({ "top": $(document).scrollTop() + "px" });
            $("#overlay").show();
            $("#iframe_wrapper").show();
            frames["iframe_overlay"].location = url;
            return false;
        },


        CloseOverlay: function(update, location) {

            // Wrapping in a try/catch block to make sure the overlay doesn't get stuck.
            try {
                if (update) {
                    //reload the pages to grab the changes
                    if (location) {
                        window.location = location;
                    } else {
                        if (window.location.pathname.toLowerCase() == '/signedout.aspx') {
                            window.location = '/';
                        } else {
                            window.location = window.location;
                        }
                    }
                } else {
                    $("#iframe_wrapper").hide();
                    $("#overlay").hide();
                    frames["iframe_overlay"].location = "/blank.htm";
                }
            }
            catch (err) {
                // Something went wrong. Make a last-ditch effort hide the overlay.
                $("#iframe_wrapper").hide();
                $("#overlay").hide();
            }
            return false;
        },

        SetOverlayWidth: function(newWidth) {
            $("#iframe_container").animate({ width: newWidth });
        },

        SetOverlayHeight: function(height) {
            //var wrapperHeight = $("#wrapper").height();
            //if (!heightSet) {
            var wrapperHeight = $(window).height();
            // Overlay is always at least window height.
            if (height < wrapperHeight) height = wrapperHeight;


            //$("#iframe_container").css("max-height", wrapperHeight - 50);
            //$("#iframe_container").animate({ height: (height + popupMarginBottom) }, function() {
            //$("#iframe_overlay").height($("#iframe_container").height() - 35);
            //frames["iframe_overlay"].location = frames["iframe_overlay"].location;
            //});
            $("#iframe_container").animate({ height: (height - popupMarginBottom) }, function() {
                $("#iframe_overlay").height($("#iframe_container").height() - 35);
            });
            heightSet = true;
            //}
        },

        //POPUP MANAGEMENT
        //----------------------------------------
        hidePopup: function PWSC$hidePopup(e, popUpDivId) {
            ///<summary>
            ///Hides a popup div in such a way that it does not hide if the click event came from the popup itself
            ///</summary>       

            //get the source DOM element for the event
            var target = (e && e.target) || (event && event.srcElement);
            var hideDiv = true;

            //determine whether the source of the click event is the popup itself
            if (target.id == popUpDivId) {
                hideDiv = false;
            }
            if (target.parentNode != null && target.parentNode.id == popUpDivId) {
                hideDiv = false;
            }
            //hide the popup as appropriate
            if (hideDiv) {
                PWSC.setDOMElementVisibility(false, popUpDivId);
            }
        },

        setDOMElementVisibility: function PWSC$setDOMElementVisibility(isVisible, elementName) {
            ///<summary>Shows or hides a DOM element, such as a pop up div</summary> 

            var display = (isVisible ? "block" : "none");
            var domElement = document.getElementById(elementName);
            if (domElement) {
                domElement.style.display = display;
            }
        },

        attachEvent: function PWSC$attachEvent(pwsConstantEventType, eventHandler, srcElement) {
            ///<summary>
            ///Provides an implementation of attachEvent that can handle IE and all other browsers
            ///Other browsers use addEventListener and IE uses attachEvent.            
            ///</summary> 
            var eventAsString = "";
            var isIE = navigator.appName == "Microsoft Internet Explorer";
            switch (pwsConstantEventType) {
                case (PWSConstants.Events.CLICK):
                    {
                        eventAsString = (isIE ? "onclick" : "click");
                    }
            }
            if (eventAsString == "") {
                return; //no event in our list was sent
            }
            if (isIE) {
                srcElement.attachEvent("onclick", eventHandler);
            }
            else {
                srcElement.addEventListener("click", eventHandler, false);
            }
        },


        isKeywordMatch: function PWSC$isKeywordMatch(searchString, keywordArray, includeAppearanceWithinWord) {
            ///<summary>
            ///Used for profanity/spam filter in Share a Thought.
            ///If one of the keywords in keywordArray is found in searchString then this routine returns true.
            ///Otherwise, it returns false.
            ///</summary>
            var keywordLength = keywordArray.length;
            for (var i = 0; i < keywordLength; i++) {

                //We cannot simply look for the string if includeAppearanceWithinWord is false
                // because 'Hell' for example, is found in 'Hello'
            
                //So we look for the keyword lead by a space, 
                var keyword = keywordArray[i];
                if (keyword == "") {
                    continue;
                }
                var searchKeyword = keyword;
                if (!includeAppearanceWithinWord) {
                    searchKeyword = " " + keyword;
                }
                if (searchString.indexOf(searchKeyword) > -1) {
                    return true;
                }
                
                //or at the beginning, followed by a space or common punctuation
                if (!includeAppearanceWithinWord) {
                    var index = searchString.indexOf(keyword + " ");
                    if(index > -1)
                    if (index > -1) {
                        return true;
                    }
                    var index = searchString.indexOf(keyword + ".");
                    if (index > -1) {
                        return true;
                    }
                    var index = searchString.indexOf(keyword + ",");
                    if (index > -1) {
                        return true;
                    }
                    var index = searchString.indexOf(keyword + "-");
                    if (index > -1) {
                        return true;
                    }
                    var index = searchString.indexOf(keyword + "!");
                    if (index > -1) {
                        return true;
                    }                     
                }
            }
            return false;
        },

        //change the src attribute of an element
        /*
        e.g.
        PWSCommon.changeSrc('imgHeader', '/testimage.jpg');
        */
        changeSrc: function(objectID, value) {
            document.getElementById(objectID).setAttribute('src', value);
        }
    }
} ();



function $elt(elementId) {
    /// <summary>
    /// A quick way to retrieve a pure (non jquery) DOM element
    /// </summary>
    return document.getElementById(elementId);
}

//// Constants ///////////////
var PWSConstants = {};
PWSConstants.Events = {
    CLICK: 1
};
PWSConstants.KeyCodes = {
    RETURN: 13,
    BACKSPACE: 8,
    DELETE: 46
};
PWSConstants.UpArrow = "arrow-up.gif";
PWSConstants.DownArrow = "arrow-down.gif";
PWSConstants.UpArrowSmall = "arrow-up-sml.gif";
PWSConstants.DownArrowSmall = "arrow-down-sml.gif";
PWSConstants.FromTwitter = "from-twitter.gif";
PWSConstants.NoPredictionImage = "no-prediction.gif";
PWSConstants.TimeFrames = { OneDay: 1, OneWeek: 7, OneMonth: 30, ThreeMonth: 90 };
PWSConstants.TimeFrameStrings = { OneDay: "OneDay", OneWeek: "OneWeek", OneMonth: "OneMonth", ThreeMonth: "ThreeMonth" };
PWSConstants.PredictionDirection = { NotProvided: -1, Down: 0, Up: 1 };


/*Delegate - allows the specification of a method within a particular instance of an object*/
function Delegate() { }

Delegate.Null = function() {
    /// <summary>
    /// Represents an Empty function.
    /// </summary>
}

Delegate._create = function Delegate$_create(targets) {
    var delegate = function() {
        if (targets.length == 2) {
            return targets[1].apply(targets[0], arguments);
        }
        else {
            for (var i = 0; i < targets.length; i += 2) {
                targets[i + 1].apply(targets[i], arguments);
            }

            return null;
        }
    };
    delegate.invoke = delegate;
    delegate._targets = targets;

    return delegate;
}


Delegate.Create = function Delegate$create(object, method) {
    if (!object) {
        method.invoke = method;
        return method;
    }
    return Delegate._create([object, method]);
}




/*TAB CONTROL*/
function TabControl(instanceName) {
    /// <summary>
    /// Manages tab switching (and in the future any other manipulations) related to client-side tabs
    /// </summary>

    this._instanceName = instanceName;
}

TabControl.prototype =
    {
        //private properties
        //--------------------
        _instanceName: "",

        //public properties
        //--------------------
        tabBaseNameArray: [],
        activeClassName: "active",
        inactiveClassName: "",

        //public methods
        //------------------
        switchTabs: function TabControl$switchTabs(tabIndex) {

            /// <summary>
            /// Switches tabs
            /// </summary>

            //clear tab and body settings
            var length = this.tabBaseNameArray.length;
            for (var i = 0; i < length; i++) {
                $elt(this.tabBaseNameArray[i] + "-tab").className = this.inactiveClassName;
                var body = $elt(this.tabBaseNameArray[i] + "-body");
                if (body) {
                    body.style.display = "none";
                }
            }

            //set active tab and body settings
            $elt(this.tabBaseNameArray[tabIndex] + "-tab").className = this.activeClassName;
            body = $elt(this.tabBaseNameArray[tabIndex] + "-body");
            if (body) {
                body.style.display = "block";
            }
        }
    }


//show/hide superstar stocks on People Landing and Profile pages
function showAllSuperstarStocks() {
    $("#all-superstar-stocks").css("display", "block");
    $("#first-superstar-stock").css("display", "none");
}
function hideAllSuperstarStocks() {
    $("#all-superstar-stocks").css("display", "none");
    $("#first-superstar-stock").css("display", "block");
}

//******************************
// Contest client side script

function ContestSymbolPrediction() {
    // constructor for ContestSymbolPrediction objects
}

ContestSymbolPrediction.prototype = {
    _prediction: PWSConstants.PredictionDirection.NotProvided,
    _backingStore: null,
    _imgUp: null,
    _imgDown: null,
    _id: '',
    _txt: null,
    _isReadOnly: false,
    _initializing: false,
    _targetDate: '',
    _cookieKey: null,
    _cookieValueSeparator: '|',

    initialize: function(id, backingStore, imgUp, imgDown, txt, isReadOnly, targetDate, cookieKey) {
        this._id = id;
        this._backingStore = $elt(backingStore);
        this._txt = $elt(txt);
        this._targetDate = targetDate;
        this._cookieKey = cookieKey;

        this._imgUp = $elt(imgUp);
        this._imgUp._prediction = this;

        this._imgDown = $elt(imgDown);
        this._imgDown._prediction = this;

        this._initializing = true;
        try {
            var priorPrediction = readCookie(this._cookieKey);
            if (priorPrediction) {
                var predArray = priorPrediction.split(this._cookieValueSeparator);
                this.set_symbol(predArray[0]);
                this.set_prediction(predArray[1]);
            }
            else {
                this.set_prediction(parseInt(this._backingStore.value));
            }
        } finally {
            this._initializing = false;
        }

        this._isReadOnly = isReadOnly;
    },
    get_isReadOnly: function() {
        return this._isReadOnly;
    },

    _mouseOver: function(pred) {
        if (this.get_canPredict()) {
            if (pred == PWSConstants.PredictionDirection.Up) {
                if (this._prediction == PWSConstants.PredictionDirection.Up) {
                    this._imgUp.src = '/Images/contest_prediction_up_hover_selected.gif';
                } else {
                    this._imgUp.src = '/Images/contest_prediction_up_hover.gif';
                }
            } else if (pred == PWSConstants.PredictionDirection.Down) {
                if (this._prediction == PWSConstants.PredictionDirection.Down) {
                    this._imgDown.src = '/Images/contest_prediction_down_hover_selected.gif';
                } else {
                    this._imgDown.src = '/Images/contest_prediction_down_hover.gif';
                }
            }
        }
    },
    _mouseOut: function(pred) {
        if (this.get_canPredict()) {
            if (pred == PWSConstants.PredictionDirection.Up) {
                if (this._prediction == PWSConstants.PredictionDirection.Up) {
                    this._imgUp.src = '/Images/contest_prediction_up_selected.gif';
                } else {
                    this._imgUp.src = '/Images/contest_prediction_up.gif';
                }
            } else if (pred == PWSConstants.PredictionDirection.Down) {
                if (this._prediction == PWSConstants.PredictionDirection.Down) {
                    this._imgDown.src = '/Images/contest_prediction_down_selected.gif';
                } else {
                    this._imgDown.src = '/Images/contest_prediction_down.gif';
                }
            }
        }
    },
    get_id: function() {
        return this._id;
    },
    get_isPredicted: function() {
        return this._prediction != PWSConstants.PredictionDirection.NotProvided;
    },
    get_symbol: function() {
        return this._txt.value;
    },
    set_symbol: function(symbol) {
        this._txt.value = symbol;
        this._imgUp.title = 'Click to predict that ' + symbol + ' will go Up between now and market close on ' + this._targetDate;
        this._imgDown.title = 'Click to predict that ' + symbol + ' will go Down between now and market close on ' + this._targetDate;
    },
    get_canPredict: function() {
        return this.get_symbol() != '';
    },
    get_prediction: function() {
        return this._prediction;
    },
    set_prediction: function(predictionDirection) {
        if (!this.get_isReadOnly()) {
            if (this.get_canPredict()) {
                if (predictionDirection == PWSConstants.PredictionDirection.Up) { // user clicked UP
                    this._prediction = PWSConstants.PredictionDirection.Up;
                    this._imgUp.src = '/Images/contest_prediction_up_selected.gif';
                    this._imgDown.src = '/Images/contest_prediction_down.gif';
                    this._imgUp.title = 'You have predicted that ' + this.get_symbol() + ' will go Up between now and market close on ' + this._targetDate;
                    this._imgDown.title = '';
                    this._backingStore.value = PWSConstants.PredictionDirection.Up;
                } else if (predictionDirection == PWSConstants.PredictionDirection.Down) { // user clicked DOWN
                    this._prediction = PWSConstants.PredictionDirection.Down;
                    this._imgUp.src = '/Images/contest_prediction_up.gif';
                    this._imgDown.src = '/Images/contest_prediction_down_selected.gif';
                    this._imgDown.title = 'You have predicted that ' + this.get_symbol() + ' will go Down between now and market close on ' + this._targetDate;
                    this._imgUp.title = '';
                    this._backingStore.value = PWSConstants.PredictionDirection.Down;
                }

                createCookie(this._cookieKey, this.get_symbol() + this._cookieValueSeparator + this._prediction);

                // todo: add event and decouple global function call
                validatePredictionSubmit();
            } else {
                if (!this._initializing)
                    alert('Please select a symbol before predicting up or down');
            }
        }
    }
};

//******************************

//******************************
// Simple (very simple) cookie functionality


function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

//******************************