//thefilterclient.js vesion 1.0.1

var TheFilter = function () {

    function Dbug(data) {
        if (TheFilter.Debug) {
            if (typeof(console) != 'undefined') {
                console.log(data);
            } else {
                alert(data);
            }
        }
    }

    //General get cookie call
    function GetCookie(cookieName) {
        if (document.cookie.length > 0) {
            var results = document.cookie.match('(^|;) ?' + cookieName + '=([^;]*)(;|$)');
            if (results)
                return unescape(results[2]);
        }
        return null;
    }

    //General set cookie call
    function SetCookie(name, value, hours) {
        if (hours != null) {
            var date = new Date();
            date.setHours(date.getHours() + hours);
            document.cookie = name + "=" + escape(value) + "; expires=" + date.toGMTString() + "; path=/";
        }
        else {
            document.cookie = name + "=" + escape(value) + "; path=/";
        }
    }

    //General Guid generator
    function GenerateGuid() {

        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    return {
        //public methods and properties (with default values)
        Debug: false,

        ServiceLocation: 'http://api212.thefilter.com/sbs/sandbox',

        ExtUserId: null,

        UserGroup: null,

        ErrorHandler: null,

        LoadHandler: null,

        // Performs an Evidence Capture API call
        // eventType : The name of the event to be captured
        // itemId : The id of the item for which the event has occured
        // itemType : The item type of the item in the event
        // params : An object describing the query string parameters to append to the call
        // eventContext : An optional context value for the event
        CaptureEvidence: function (eventType, itemId, itemType, params, eventContext) {
            if (document.createElement) {
                var img = new Image();

                var url = TheFilter.ServiceLocation + '/' + escape(itemType) + '(' + escape(itemId) + ')/event/' + escape(eventType);
                if (eventContext != null) {
                    url += '/' + escape(eventContext);
                }

                url += '?extanonid=' + TheFilter.GetAnonymousUserGuid() + (TheFilter.UserGroup ? '&g=' + escape(TheFilter.UserGroup) : '')
                url += (TheFilter.ExtUserId ? '&extuserid=' + escape(TheFilter.ExtUserId) : '');
                url += '&domain=' + document.domain + '&lang=' + TheFilter.GetLanguage();
                url += '&session=' + TheFilter.GetSessionGuid();
                url += '&tzo=' + (new Date()).getTimezoneOffset() + '&ms=' + (new Date()).getTime();

                var key;
                for (key in params) {
                    url += (params[key] ? '&' + key + '=' + escape(params[key]) : '');
                }

                //if error occurs client can handle it if they wish by assigning a function to TheFilter.ErrorHandler
                img.onerror = function (e) { if (TheFilter.ErrorHandler) { TheFilter.ErrorHandler(this.src); } };
                img.onload = function (e) { if (TheFilter.LoadHandler) { TheFilter.LoadHandler(this.src); } };

                img.src = url;

                Dbug(img.src);
            }
        },

        // Builds the API URL for a single seed recommendation call
        // itemId : The id of the seed item for which to retrieve the recommendation
        // seedItemType : The item type of the seed item
        // recItemType : The item type of items to be recommended (usually the same as the seed Item Type)
        // params : An object describing the query string parameters to append to the call
        // format : Specifies the format of the response. One of : xml, xmlverbose, json, jsonverbose
        SingleSeedRecommendationUrl: function (data) {

            Dbug('SingleSeedRecommendationUrl');
            Dbug(data);

            var url = TheFilter.ServiceLocation + '/' + escape(data.seedItemType) + '(' + escape(data.itemId) + ')/recommendation/' + escape(data.recItemType);

            url += '?extanonid=' + TheFilter.GetAnonymousUserGuid() + (TheFilter.UserGroup ? '&g=' + escape(TheFilter.UserGroup) : '')
            url += (TheFilter.ExtUserId ? '&extuserid=' + escape(TheFilter.ExtUserId) : '');
            url += '&domain=' + document.domain + '&lang=' + TheFilter.GetLanguage();
            url += '&session=' + TheFilter.GetSessionGuid();
            url += '&tzo=' + (new Date()).getTimezoneOffset() + '&ms=' + (new Date()).getTime();

            var key;
            for (key in data.params) {
                url += (data.params[key] ? '&' + key + '=' + escape(data.params[key]) : '');
            }

            if (data.format) {
                url += '&$format=' + data.format;
            }

            Dbug(url);

            return url;
        },

        // Builds the API URL for a seedless catalogue call
        // rootItemType : The item type of the items to query
        // params : An object describing the query string parameters to append to the call
        // format : Specifies the format of the response. One of : xml, xmlverbose, json, jsonverbose
        SeedlessCatalogueUrl: function (data) {

            Dbug('SeedlessCatalogueUrl');
            Dbug(data);

            var url = TheFilter.ServiceLocation + '/' + escape(data.rootItemType);

            url += '?extanonid=' + TheFilter.GetAnonymousUserGuid() + (TheFilter.UserGroup ? '&g=' + escape(TheFilter.UserGroup) : '')
            url += (TheFilter.ExtUserId ? '&extuserid=' + escape(TheFilter.ExtUserId) : '');
            url += '&domain=' + document.domain + '&lang=' + TheFilter.GetLanguage();
            url += '&session=' + TheFilter.GetSessionGuid();
            url += '&tzo=' + (new Date()).getTimezoneOffset() + '&ms=' + (new Date()).getTime();

            var key;
            for (key in data.params) {
                url += (data.params[key] ? '&' + key + '=' + escape(data.params[key]) : '');
            }

            if (data.format) {
                url += '&$format=' + data.format;
            }

            Dbug(url);

            return url;
        },

        // Builds the API URL for a seeded catalogue call
        // itemId : The id of the item to retrieve
        // rootItemType : The item type of the items to query
        // params : An object describing the query string parameters to append to the call
        // format : Specifies the format of the response. One of : xml, xmlverbose, json, jsonverbose
        SingleSeedCatalogueUrl: function (data) {

            Dbug('SeedlessCatalogueUrl');
            Dbug(data);

            var url = TheFilter.ServiceLocation + '/' + escape(data.seedItemType) + '(' + escape(data.itemId) + ')';

            url += '?extanonid=' + TheFilter.GetAnonymousUserGuid() + (TheFilter.UserGroup ? '&g=' + escape(TheFilter.UserGroup) : '')
            url += (TheFilter.ExtUserId ? '&extuserid=' + escape(TheFilter.ExtUserId) : '');
            url += '&domain=' + document.domain + '&lang=' + TheFilter.GetLanguage();
            url += '&session=' + TheFilter.GetSessionGuid();
            url += '&tzo=' + (new Date()).getTimezoneOffset() + '&ms=' + (new Date()).getTime();

            var key;
            for (key in data.params) {
                url += (data.params[key] ? '&' + key + '=' + escape(data.params[key]) : '');
            }

            if (data.format) {
                url += '&$format=' + data.format;
            }

            Dbug(url);

            return url;
        },

        // get language - used by actionscript
        GetLanguage: function () {
            return navigator.language || navigator.userLanguage;
        },

        // return domain - used by actionscript
        GetDomain: function () {
            return document.domain;
        },

        //Get anonymous id from cookie, and set it if it doesn't already exist
        GetAnonymousUserGuid: function () {
            var userGuid = GetCookie('FilterUserGuid');
            if (userGuid === null || userGuid.indexOf("-") === -1) {
                SetCookie('FilterUserGuid', GenerateGuid(), (1000 * 24));
                userGuid = GetCookie('FilterUserGuid');
            }
            return userGuid;
        },

        //Get user session id from cookie
        GetSessionGuid: function () {
            var userSession = GetCookie('FilterUserSession');
            if (userSession === null || userSession.indexOf("-") === -1) {
                SetCookie('FilterUserSession', GenerateGuid(), 1);
                userSession = GetCookie('FilterUserSession');
            } else {
                //update the expiration for our sessions cookie
                SetCookie('FilterUserSession', userSession, 1);
            }
            return userSession;
        }
    };
} ();


