﻿// Isolated functions
var OHE = (function (window) {

    // http://staging.aionline.edu 
    var siteRoot = '/json/json.axd',
    cookies = {
        setCookie: function (c_name, value, exdays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
        },
        getCookie: function (c_name) {
            var i, x, y, ARRcookies = document.cookie.split(";");
            for (i = 0; i < ARRcookies.length; i++) {
                x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
                y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
                x = x.replace(/^\s+|\s+$/g, "");
                if (x == c_name) {
                    return unescape(y);
                }
            }
        }
    },
    Student = {
        isStudent: function () {
            return cookies.getCookie('isStudent') == 'true';
        },
        setAsStudent: function () {
            cookies.setCookie('isStudent', 'true', 360);
        }
    },
    AJAX = {
        get: function (url, callback) {
            var xmlhttp;
            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    callback(xmlhttp.responseText);
                }
            }
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        },
        GetJSONP: function (url, callbackName) {    // Add to the doc the script tag to go get the data...
            this.x = document.createElement('script');
            this.x.src = url;
            this.x.ID = 'OHE.JSONP';
            this.x['class'] = 'OHE.JSONP';

            this.div = document.createElement('div');
            this.div.id = 'OHE.JSONP';

            if (url.indexOf('?') > -1) {
                this.x.src += '&jsonp=' + callbackName;
            }
            else {
                this.x.src += '?jsonp=' + callbackName;
            }

            this.div.appendChild(this.x);

            document.body.appendChild(this.div);
        },
        // Here for the people who care to clean up afterthemselves
        CleanUP: function () {
            var script;
            while (script = document.getElementById('OHE.JSONP')) {
                script.parentNode.removeChild(script);
                for (var prop in script) {
                    delete script[prop];
                }
            }
        }
        // TODO - array push for qstring variables?
        // TODO - build qstrings from single place...


    },
    CMS = {
        Tables: ['ArticlesResourcesContent', 'Blog', 'Chunk', 'CurriculumItem', 'CurriculumItemDetail', 'DegreeSnapshotsContent'],

        GetCMSContent: function (table, ID, callbackName) {
            var url = CMS.BuildURL(table, ID);
            AJAX.GetJSONP(url, callbackName);
        },
        BuildURL: function (tableName, ID) {
            return siteRoot + '?tableName=' + tableName + '&contentID=' + ID;
        }
    },

    StateList = {
        Names: [
        'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Florida', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'
                ],
        Abbreviations: [
        'AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL', 'GA', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'OH', 'OK', 'OR', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'PA', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VA', 'WA', 'WV', 'WI', 'WY'
        ]
    },

    // Neccessary functions for facebook...
    Facebook = function (FBappID) {
        this.appID = FBappID;
        //this.LoggedIncallback = UserAvailableCallbackFunction;
        var getUserCallback;  // holder for what could be passed in later

        // optionally used to hold html mappings to the rif
        RIFMap = function (email, first_name, last_name, state, city) {

            this.email = email;
            this.first_name = first_name;
            this.last_name = last_name;
            this.state = state;
            this.city = city;
        }

        IsUserLoggedIn = function () {
            return !(FB._userStatus == "unknown");
        }

        //        LoginUser = function (callback) {
        //            FB.getLoginStatus(function (response) {
        //                if (response.authResponse) {
        //                    callback();
        //                } else {
        //                    FB.login(function (response) {
        //                        if (response.authResponse) {
        //                            callback();
        //                        }
        //                    }, { scope: 'email, user_location' });
        //                }
        //            });
        //        }

        LoginUser = function (callback) {
            //FB.getLoginStatus(function (response) {
                //if (response.authResponse) {
                //    callback();
                //} else {
                FB.login(function (response) {
                    if (response.authResponse) {
                        callback();
                    }
                }, { scope: 'email, user_location' });
                //}
           // });
        }


        GetCurrentUser = function (userCallback) {
            if (isNaN(window.name)) { window.name = ''; }   // FF fix

            if (!getUserCallback) {  // Save this to call back to the original
                getUserCallback = userCallback;
            }

            if (!IsUserLoggedIn()) {
                LoginUser(GetCurrentUser);
            }
            else {
                FB.api('/me', function (response) {
                    var fbUser = response;
                    if (fbUser.location) {
                        fbUser.city = fbUser.location.name.split(', ')[0];  // add city property
                        fbUser.stateAbbreviation = fbUser.location.name.split(', ')[1]; // add state property
                        fbUser.state = OHE.StateList.Abbreviations[OHE.StateList.Names.indexOf(fbUser.stateAbbreviation)];
                    }
                    else {
                        fbUser.city = "";
                        fbUser.state = "";
                    }
                    getUserCallback(fbUser);  // sent from UI deliver user back
                });
           }
        }


        // Ensure FB is loaded and initialized
        if (FBappID) {
            (function (appID) {
                if (window.FB == undefined) {
                    (function () {
                        var e = document.createElement('script'); e.async = true;
                        e.src = document.location.protocol +
                    '//connect.facebook.net/en_US/all.js';
                        document.getElementById('fb-root').appendChild(e);
                    } ());

                    // This is the callback function that will get called when the script above gets loaded on the page
                    window.fbAsyncInit = function () {
                        FB.init({ appId: appID,
                            status: true,
                            cookie: true,
                            xfbml: true,
                            oauth: true
                        });

                        FB.Event.subscribe('auth.authResponseChange', function (response) {
                            if (response.status == 'connected') {
                                if (typeof getUserCallback === "function") { getUserCallback(); }
                            }
                        });
                    };
                }
            } (this.appID));

            return {
                appID: this.appID,
                RIFMap: RIFMap,
                GetCurrentUser: GetCurrentUser
            }
        } else {
            return {
                Error: 'Facebook not initialized properly'
            }
        }
    }


    return {
        cookies: cookies,
        Student: Student,
        Ajax: AJAX,
        CMS: CMS,
        StateList: StateList,
        Facebook: Facebook
    }
} (window));


callBackGetter = function (response) {
    return response;
}
