/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

//Define imax namespace
if (!imax) {
    var imax = new Object();
}

/**
 * Imax stats class used for storing and calculate website statistics
 *
 * @example
 * //first of all you need to load this file
 * <script type="text/javascript" src="{{ baseUrl() }}/js/imax.stats.js"></script>
 *
 * //after that you need to define configuration with default parameters
 * // also you need to define all parameters here
 *
 *          imax.stats.init({
 *                   "id" : "12345", //default local webmaster id
 *                   "wid": "XYZ",   //default central webmaster id
 *                   "prid": 123,    //default project id
 *                   "cid": 78545,   //central user id
 *                   "username": "lucass", //central username
 *                   "mkid": 15, //marketing id
 *                   "mailid1": 1, //mail id 1
 *                   "mailid2": 2  //mail id 2
 *              });
 *
 *          imax.stats.setTracker("{{ baseUrl() }}/js/imax.stats.awstats_misc_tracker.js");
 *
 *
 * //And put dispatch "hit signal" script, where it's needed, usually at the end of page.
 * <script type="text/javascript">imax.stats.hitRaw();</script>
 * //if you need to create ajax requests then you should write
 * <script type="text/javascript">imax.stats.hitRaw(true);</script>
 *
 */
imax.stats = new function() {

    //tracker url
    this.tracker = '';

    //cookie lifetame in hours
    this.cookieLifetime = 360;

    //is hit request was send flag
    this.sended = false;

    // is unique hit flag
    this.isUnique = false;

    /**
     * Params
     */
    this.params = {
        "id" : null,
        "wid": null,
        "prid": null,
        "mkid": null,
        "mailid1": null,
        "mailid2": null,
        "cid": null,
        "username": null,
        "subdomain" : null,
        "cprid" : null,
        "map": {
            "id": "id",
            "wid": "wid",
            "prid": "prid",
            "mkid": "mkid",
            "mailid1": "mailid1",
            "mailid2": "mailid2"
        }
    },

    /**
     * Raw hit signal
     *
     * @description used for calculate all hits.
     * @return void
     */
    this.hitRaw = function(ajax) {
        this.hit("raw", ajax);
    }

    /**
     * Join hit signal
     *
     * @description used for calculate Join hits
     * @return void
     */
    this.hitJoin = function(ajax) {
        this.hit("join", ajax);
    }

    /**
     * Send hit signal
     *
     * @description used for calculate Send hits
     * @return void
     */
    this.hitSend = function(ajax) {
        this.hit("send", ajax);
    }

    /**
     * Approved hit signal
     *
     * @description used for calculate Approved his registration
     * @return void
     */
    this.hitApproved = function(ajax) {
        this.hit('approved', ajax);
    }

    /**
     * Cpi hit signal
     *
     * @description used for calculate Cpi (central payment initialize) hits
     * @return void
     */
    this.hitCpi = function(ajax) {
        this.hit('cpi', ajax);
    }

    /**
     * function used dispatch hit signal
     *
     * @param type - hit type
     * @param ajax - ajax flag
     *
     * @description Please use functions like hitCpi, hitApproved ..etc instead of this one
     * @private
     */
    this.hit = function(type, ajax) {
        if (this.sended && !ajax) {
            return;
        }
        this.params['hit'] = type;
        this.params['referer'] = window.location.href;

        awstats_hit();
        this.sended = true;
    }

    /**
     * Function used for initialisation of hits library
     *
     * @param params - configration params object
     */
    this.init = function(params) {

        if (!this.getCookieValue("IMAX_STATS_VISIT")) {
            this.isUnique = true;
            var expiredData = new Date();
            var cookieValue = expiredData.getTime();
            expiredData.setTime(expiredData.getTime() + ( 24 * 3600 * 1000));
            document.cookie = "IMAX_STATS_VISIT=" + escape(cookieValue) + "; path=/" + "; expires=" + expiredData.toGMTString();
        } else {
            this.isUnique = false;
        }

        var mapExists = false;

        for(var name in params) {
            if (name != "map") {
                this.params[name] = params[name];
            } else {
                mapExists = true;
            }
        }

        if (mapExists) {
            for(var mapName in params.map) {
                this.params.map[mapName] = params.map[mapName];
            }
        }
        var data = this.loadFromUrl();
        if (data) {
            this.saveData(data);
        } else  {
            this.loadData();
        }
    }

    /**
     * Function returns tracker url
     *
     * @return string
     */
    this.getTracker = function() {
        return this.tracker;
    }

    /**
     * Function used for set tracker url
     *
     * @return void
     */
    this.setTracker = function(trackerPath) {
        this.tracker = trackerPath;
        document.write('<script type="text/javascript" src="' + this.getTracker() + '"></script>');
    }

    /**
     * Function used for building query string according configuration parameters
     *
     * @return string
     */
    this.query = function(asString) {
        if (!asString) {
            return this.params;
        }

        var qString = "";

        for (var key in this.params) {
            if (key != "map") {
                var value = this.params[key];
                if (value) {
                    qString += "&" + key + "=" + encodeURI(value);
                }
            }
        }

        var time = new Date();
        qString += "&hit_timestamp=" + time.getTime();

        if (this.isUnique) {
            qString += "&hit_unique=1";
        }

        return qString;
    }

    /**
     * Function used for decode uri, to object
     *
     * @param url - url query string
     *
     * @return object
     */
    this.decodeUrl = function(url) {
        var result = {};
        if (url.charAt(0) == '?') {
            url = url.substring(1);
        }
        var paramsArray = url.split("&");
        for (var i = 0; i < paramsArray.length; i++) {
            var pair = paramsArray[i].split("=");
            if (pair.length == 2) {
                result[pair[0]] = pair[1];
            }
        }
        return result;
    }

    this.getCookieValue = function(cookieParam) {
        var cookieValue = null;
        if (document.cookie.length > 0){
            var begin = document.cookie.indexOf(cookieParam +"=");
            if (begin != -1) {
                begin += cookieParam.length+1;
                var end = document.cookie.indexOf(";", begin);
                if (end == -1) end = document.cookie.length;
                cookieValue = unescape(document.cookie.substring(begin, end));
            }
        }
        return cookieValue;
    }

    /**
     * loading data from cookies
     */
    this.loadData = function() {
        var result = null;

        var cookieValue = this.getCookieValue("IMAX_STATS");

        if (!cookieValue) {
            return null;
        }

        result = {};
        var data = this.decodeUrl(cookieValue);
        for(var paramName in this.params.map) {
            var newValue = null;
            if (data[paramName]) {
                newValue = data[paramName];
            }
            this.params[paramName] = newValue;
            result[paramName] = newValue;
        }

        return result;
    }

    /**
     * check if some parameter from configuration exists in object
     *
     * @private
     */
    this.isAnyParamExists = function(data) {
        for(var paramName in this.params.map) {
            var mapName = this.params.map[paramName];
            if (data[mapName]) {
                return true;
            }
        }
        return false;
    }

    /**
     * Loading data from url
     */
    this.loadFromUrl = function() {
        var urlData = this.decodeUrl(window.location.search);
        if (this.isAnyParamExists(urlData)) {
            var result = {};
            for(var paramName in this.params.map) {
                var newValue = null;
                var mapName = this.params.map[paramName];
                if (urlData[mapName]) {
                    newValue = urlData[mapName];
                    result[paramName] = newValue;
                }
                this.params[paramName] = newValue;
            }
            if (this.isValid(result)) {
                return result;
            }
        }
        return null;
    }

    /**
     * Validate parameters
     */
    this.isValid = function(result) {
        if (result.id && !result.prid) {
            return false;
        }
        return true;
    }

    /**
     * Save data into cookies
     */
    this.saveData = function(data) {
        var dataString = "";
        for(var param in data) {
            if (dataString) {
                dataString += "&";
            }
            dataString += param + "=" + data[param];
        }
        var expiredData = new Date();
        if (dataString) {
            expiredData.setTime(expiredData.getTime() + (this.cookieLifetime * 3600 * 1000));
        }
  	document.cookie = "IMAX_STATS=" + escape(dataString) + "; path=/" + ((!this.cookieLifetime) ? "" : "; expires=" + expiredData.toGMTString());
    }

}

