var BEXAPI = new function() {
    this.AccessKey = 'D284GKCqFKKU42dbzDSITJxB/duGBaj2Zbf5Uwj8ub4=';
    this.IsLoggedIn = false;
    if ($.cookie != undefined) {
        var accKey = $.cookie("AccessKey");
        if (accKey != null && accKey != '') {
        	this.IsLoggedIn = true;
            this.AccessKey = accKey;
        }
    }

    this.setAccessKey = function(accessKey) {
    	this.AccessKey = accessKey;
    	var dateObj = new Date();
        dateObj.setTime(dateObj.getTime() + (30 * 24 * 60 * 60 * 1000)); // 30 days
    	var options = { path: '/', expires: dateObj, domain: document.domain.substring(document.domain.indexOf('.') + 1) }; 
    	$.cookie("AccessKey", accessKey, options);
    	this.IsLoggedIn = true;
    };
    
    this.LogFrame = null;
    this.DEBUG = true;

    this.AJAXTimeout = 30000; // 30 seconds
    this.AJAXURL = '/api/index.php';

    this.sequence = 1;
    this.fnChain = new Array();
    this.fnUserData = new Array();

    this.saveFnChain = function(apiFunction, callbackFn, userData) {
        if (callbackFn !== undefined) {
            fnKey = BEXAPI.sequence++;
            this.fnChain[fnKey] = callbackFn;
            this.fnUserData[fnKey] = userData;
            return (fnKey);
        }
        return null;
    };

    this.clearChain = function() {
        this.fnChain = new Array();
        this.fnUserData = new Array();
    };

    this.doFnChain = function(response, apiFunction) {
        if (response.Guid) {
            fnKey = response.Guid;
            if (BEXAPI.fnChain[fnKey] !== undefined) {
                BEXAPI.fnChain[fnKey](response, BEXAPI.fnUserData[fnKey]);
                //delete BEXAPI.fnChain[fnKey];
                //delete BEXAPI.fnUserData[fnKey];
            }
        }
    };

    this.FromJSON = function(rawAPIResponse) {
        this.RawLog(rawAPIResponse);
        apiResponse = JSON.parse(rawAPIResponse);
        if (apiResponse.IsSuccess) {
            BEXAPI.Log('Success' + apiResponse.Guid);
        } else {
            BEXAPI.Log('Failure - ' + apiResponse.FailureMsg);
        }
        return apiResponse;
    };

    this.GetCurrentLocalDate = function(year, mon, day, hour, min, sec) {
        year = year === undefined ? true : year;
        mon = mon === undefined ? true : mon;
        day = day === undefined ? true : day;
        hour = hour === undefined ? true : hour;
        min = min === undefined ? false : min;
        sec = sec === undefined ? false : sec;

        str = '';
        var now = new Date();
        if (year) { str += (now.getFullYear() + ''); }
        if (mon) { str += (now.getMonth() < 10 ? '0' : '') + (now.getUTCMonth() + 1); }
        if (day) { str += (now.getDate() < 10 ? '0' : '') + now.getUTCDate(); }
        if (hour) { str += (now.getHours() + ''); }
        if (min) { str += (now.getMinutes() < 10 ? '0' : '') + now.getUTCMinutes(); }
        if (sec) { str += (now.getSeconds() < 10 ? '0' : '') + now.getUTCSeconds(); }
        return str;
    };


    this.RawLog = function(jsonObj) {
        if (BEXAPI.DEBUG) {
            BEXAPI.Log('----- RAW -----');
            BEXAPI.Log(jsonObj);
            BEXAPI.Log('--- END RAW ---');
        }
    };

    this.Log = function(text) {
        if (BEXAPI.LogFrame && BEXAPI.DEBUG) {
            BEXAPI.LogFrame.innerHTML += text + '<br />';
            BEXAPI.LogFrame.scrollTop = BEXAPI.LogFrame.scrollHeight;
        }
    };

    this.SendShareLinkEmail = function( friendEmail, friendName, shareLink, ipAddress, message, fromName, fromEmail, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('SendShareLinkEmail', callbackFn, userData);
        var jsonObj = {
            Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            FriendName: friendName,
            FriendEmail: friendEmail,
            ShareLink: shareLink,
            IPAddress: ipAddress,
            Message: message,
            FromName: fromName,
            FromEmail: fromEmail 
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: {
            	    event: 'api_SendShareLinkEmail',
            	    jsonblock: JSON.stringify(jsonObj)
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'SendShareLinkEmail');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                BEXAPI.doFnChain(response, 'SendShareLinkEmail');
            }
        });    	    
    }    
    
    this.EmailSubscribe = function(email, source, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('EmailSubscribe', callbackFn, userData);
        var jsonObj = {
            Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            Email: email,
            SubscribeSource: source
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: {
            	    event: 'api_EmailSubscribe',
            	    jsonblock: JSON.stringify(jsonObj)
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'EmailSubscribe');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                BEXAPI.doFnChain(response, 'EmailSubscribe');
            }
        });    	    
    }
    
    // 1a
    this.CreateAccount = function(email, password, zip, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('CreateAccount', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            Email: email,
            Password: password,
            Zip: zip
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_CreateAccount', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'CreateAccount');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                    BEXAPI.AccessKey = response.ResponseData.AccessKey;
                    BEXAPI.Log('New access key: ' + BEXAPI.AccessKey);
                }
                BEXAPI.doFnChain(response, 'CreateAccount');
            }
        });
    };

    // 1a - for Plan site only
    this.CreateSaveFullAccount = function(jsonObj, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('CreateSaveFullAccount', callbackFn, userData);
        // mark the object with a few extra things
        jsonObj.Guid = guid;
        jsonObj.Source = 'WEB';
        jsonObj.AccessKey = BEXAPI.AccessKey;
        $.ajax({
            type: 'POST',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_CreateSaveFullAccount', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'CreateSaveFullAccount');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                BEXAPI.doFnChain(response, 'CreateSaveFullAccount');
            }
        });
    };

    // no number, quit form
    this.WriteQuitForm = function(callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('WriteQuitForm', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            quitDate: $('#selectedQuitDate').val(),
            triedToQuitBefore: $('input[name=triedToQuitBefore]:checked').val(),
            howManyTimes: $('#howManyTimes').val(),
            didUseMedication: $('input[name=didUseMedication]:checked').val(),
            whichMedication: $('#whichMedication').val(),
            haveMajorLifeEvent: $('input[name=haveMajorLifeEvent]:checked').val(),
            haveStartedTracking: $('input[name=haveStartedTracking]:checked').val(),
            willUseMedication: $('input[name=willUseMedication]:checked').val()
        };
        $.ajax({
            type: 'POST',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_WriteQuitForm', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'WriteQuitForm');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                BEXAPI.doFnChain(response, 'WriteQuitForm');
            }
        });
    };

    // field by field update of user's profile
    this.updateProfileField = function(jsonObj, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('updateProfileField', callbackFn, userData);
        // mark the object with a few extra things
        jsonObj.Guid = guid;
        jsonObj.Source = 'WEB';
        jsonObj.AccessKey = BEXAPI.AccessKey;
        $.ajax({
            type: 'POST',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_updateProfileField', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'updateProfileField');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                BEXAPI.doFnChain(response, 'updateProfileField');
            }
        });
    };

    this.SetQuitDate = function(quitDate, isGoodDate, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('SetQuitDate', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            QuitDate: quitDate,
            IsGoodDate: isGoodDate
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_SetQuitDate', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'SetQuitDate');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                BEXAPI.doFnChain(response, 'SetQuitDate');
            }
        });
    };

    this.GetQuitDateRanges = function(yearMonth, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('GetQuitDateRanges', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            YearMonth: yearMonth
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_GetQuitDateRanges', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'GetQuitDateRanges');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                BEXAPI.doFnChain(response, 'GetQuitDateRanges');
            }
        });
    };

    // 1b
    this.LoginAccount = function(email, password, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('LoginAccount', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            Email: email,
            Password: password
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_LoginAccount', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'LoginAccount');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                    BEXAPI.AccessKey = response.ResponseData.AccessKey;
                    BEXAPI.Log('New access key: ' + BEXAPI.AccessKey);
                }
                BEXAPI.doFnChain(response, 'LoginAccount');
            }
        });
    };

    // 1c
    this.DoesEmailExist = function(email, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('DoesEmailExist', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            Email: email
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_DoesEmailExist', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'DoesEmailExist');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.ResponseData.DoesExist) {
                    BEXAPI.Log('Email exists');
                } else {
                    BEXAPI.Log('Email does not exist');
                }
                BEXAPI.doFnChain(response, 'DoesEmailExist');
            }
        });
    };

    // 1d
    this.TriggerPasswordReset = function(email, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('TriggerPasswordReset', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            Email: email
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_TriggerPasswordReset', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'TriggerPasswordReset');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                    BEXAPI.Log('Password reset requested');
                }
                BEXAPI.doFnChain(response, 'TriggerPasswordReset');
            }
        });
    };

    // 1e
    this.QueryUserAccount = function(callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('QueryUserAccount', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_QueryUserAccount', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'QueryUserAccount');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                    BEXAPI.Log('Username=' + response.ResponseData.Username);
                    BEXAPI.Log('QuitDate=' + response.ResponseData.QuitDate);
                }
                BEXAPI.doFnChain(response, 'QueryUserAccount');
            }
        });
    };

    this.QueryUserStats = function(callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('QueryUserStats', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_QueryUserStats', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'QueryUserStats');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                }
                BEXAPI.doFnChain(response, 'QueryUserStats');
            }
        });
    };

    // 2a
    this.GetSmokingEvents = function(startDate, endDate, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('GetSmokingEvents', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            StartDate: startDate,
            EndDate: endDate
        };

        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_GetSmokingEvents', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'GetSmokingEvents');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                    if (BEXAPI.DEBUG) {
                        var logLine = 'Returned SmokingEventIDs: ';
                        $.each(response.ResponseData.SmokingEvents,
							function() {
							    logLine += this.SmokingEventID + ' ';
							}
				  		);
                        BEXAPI.Log(logLine);
                    }
                }
                BEXAPI.doFnChain(response, 'GetSmokingEvents');
            }
        });
    };

    // 2b
    this.GetTriggers = function(callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('GetTriggers', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB', AccessKey: BEXAPI.AccessKey
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_GetTriggers', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'GetTriggers');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                    if (BEXAPI.DEBUG) {
                        BEXAPI.Log('Triggers List:');
                        $.each(response.ResponseData.Triggers,
							function(tKey) {
							    BEXAPI.Log(tKey + "=" + this);
							}
				  		);
                        BEXAPI.Log('End of Trigger List');
                    }
                }
                BEXAPI.doFnChain(response, 'GetTriggers');
            }
        });
    };

    // 2c
    this.GetUrges = function(callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('GetUrges', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB', AccessKey: BEXAPI.AccessKey
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_GetUrges', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'GetUrges');
            },
            success: function(rawAPIResponse, textStatus) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                    if (BEXAPI.DEBUG) {
                        BEXAPI.Log('Urge List:');
                        $.each(response.ResponseData.Urges,
							function(uKey) {
							    BEXAPI.Log(uKey + "=" + this);
							}
				  		);
                        BEXAPI.Log('End of Urge List');
                    }
                }
                BEXAPI.doFnChain(response, 'GetUrges');
            }
        });
    };

    // 2d
    this.DeleteSmokingEvent = function(smokingEventID, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('DeleteSmokingEvent', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            SmokingEventID: smokingEventID
        };
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_DeleteSmokingEvent', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'DeleteSmokingEvent');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                    BEXAPI.Log('Deleted');
                }
                BEXAPI.doFnChain(response, 'DeleteSmokingEvent');
            }
        });
    };

    // 2e
    this.WriteSmokingEvent = function(smokingEventID, dateTime, number, triggerID, urgeID, comment,
			callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('WriteSmokingEvent', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            Number: number,
            TriggerID: triggerID,
            UrgeID: urgeID
        };
        if (smokingEventID) {
            jsonObj.SmokingEventID = smokingEventID;
        }
        if (dateTime) {
            jsonObj.DateTime = dateTime;
        } else {
            jsonObj.DateTime = this.GetCurrentLocalDate();
        }
        if (comment !== undefined && comment !== null) {
            jsonObj.Comment = comment;
        }
        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_WriteSmokingEvent', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'WriteSmokingEvent');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                    BEXAPI.Log('New SmokingEventID: ' + response.ResponseData.SmokingEventID);
                }
                BEXAPI.doFnChain(response, 'WriteSmokingEvent');
            }
        });
    };

    // 2f
    this.GetMontlyCigaretteCounts = function(yearMonth, callbackFn, userData) {
        var guid = BEXAPI.saveFnChain('GetMontlyCigaretteCounts', callbackFn, userData);

        var jsonObj = { Guid: guid,
            Source: 'WEB',
            AccessKey: BEXAPI.AccessKey,
            YearMonth: yearMonth
        };

        $.ajax({
            type: 'GET',
            url: BEXAPI.AJAXURL,
            timeout: BEXAPI.AJAXTimeout,
            data: { event: 'api_GetMonthlyCigaretteCounts', jsonblock: JSON.stringify(jsonObj) },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                response = { IsSuccess: false, FailureMsg: 'HTTPERROR' };
                BEXAPI.doFnChain(response, 'GetMontlyCigaretteCounts');
            },
            success: function(rawAPIResponse) {
                var response = BEXAPI.FromJSON(rawAPIResponse);
                if (response.IsSuccess) {
                    if (BEXAPI.DEBUG) {
                        BEXAPI.Log('Daily Cigarette Counts:');
                        $.each(response.ResponseData.CigaretteCounts,
							function(cigKey) {
							    BEXAPI.Log('Day ' + cigKey + ': ' + this + ' cigarettes');
							}
				  		);
                        BEXAPI.Log('End Cigarette Counts');
                    }
                }
                BEXAPI.doFnChain(response, 'GetMontlyCigaretteCounts');
            }
        });
    };


    if (window.addEventListener) {
        window.addEventListener("load", function() {
            BEXAPI.LogFrame = document.getElementById('DebugFrame');
        }, false);
    } else if (window.attachEvent) {
        window.attachEvent("onload", function() {
            BEXAPI.LogFrame = document.getElementById('DebugFrame');
        });
    };

};
