/*
 * pagecounter.js
 *
 * Copyright 2008, Squawkfox.
 * All rights reserved.
 *
 * http://www.squawkfox.com
 *
 *
 * Requires:
 *      jquery.js (http://www.jquery.com)
 *      jquery.cookies.js (http://code.google.com/p/cookies)
 *
 */


function PageCounter() {

    // Names to use for the cookies
    var UserAlreadyPromptedCookieName = "sub_popup_seen";
    var CountCookieName = "sub_popup_pagecount";

    // Prompt after this many views
    var promptCount = 2;

    // Regex for identifying referral sites to start the count.
    var referralRegex = /google\..{2,3}\/search/ig 


    //
    // Apply the specified callback if all criteria match.
    //
    this.DoAction = function(promptCallback) {

        // DISABLED
        //return;

        // Abort if browser does not support cookies
        if (!$.cookies.test()) {
            return;
        }

        // Bail out if the user has already been prompted before.
        if ($.cookies.get(UserAlreadyPromptedCookieName) != null) {
            return;
        }

        // Get the count.  This will be 0 if the cookie is not set.
        count = this.GetCount();

        // Set the cookie if we don't already have one, and if our referral matches.
        if (count == null && this.ReferralPageMatches(this.referralRegex)) {
            this.SetIncrementedCount(1);
            return;
        }

        // Perform the action if we've hit the count.
        if (count != null && count >= promptCount) {
            $.cookies.set(UserAlreadyPromptedCookieName, "1", { hoursToLive: 8640 } ); // 1 year
            promptCallback();
            return;
        }

        // Only increment if there already is a count.
        if (count != null) {
            this.SetIncrementedCount(count);
        }
    }


    //
    // Check if the supplied regex matches the referring URL.
    // Or: return 'true' to always trigger (for debugging).
    //
    this.ReferralPageMatches = function(regex) {
        return true; // --> always do it
//        return false;
//        return regex.test(document.referrer);
    }


    //
    // Clear all cookies.  Use for debugging.
    //
    this.Reset = function() {
        $.cookies.del(UserAlreadyPromptedCookieName);
        $.cookies.del(CountCookieName);
    }


    //
    // Increment the provided value and store it in the count cookie.
    //
    this.SetIncrementedCount = function(value) {
        var count = isNaN(value) ? 1 : value;
        count++;
        $.cookies.set(CountCookieName, count.toString(), { hoursToLive: 8640 }); // 1 year
        return count;
    }


    //
    // Retrieve the value stored in the cookie, or return null if none is found.
    //
    this.GetCount = function() {
        value = $.cookies.get(CountCookieName);

        if (value == null) {
            return value;
        }

        intValue = parseInt(value);

        return isNaN(intValue) ? null : intValue;
    }
}
