﻿var PopStats = {

    registerUrl: '//iv30.popstats.com.br/api20/Register.ashx',
    flashUrl: '//iv30.popstats.com.br/api20/lib/fltrk4.swf',
    flashVersion: '',
    qssl: '',
    session: '',
    executePost: false,
    executePageView: false,
    executeClick: false,
    pageTitle: '',
    clientName: '',
    params: '',
    fields: '',
    information: '',
    pageId: 0,
    userId: 0,
    smid: '',
    resolutionX: '',
    resolutionY: '',
    startTime: new Date(),
	totalTimeLoad: 0,
	executou_1tracking: 0,
    elementsTrack: new Array(),
    email: '',
    siteId: 1,
    emailOld: '',
    campaign: '',
    campaignSource: '',
    campaignMedium: '',
    campaignTerm: '',
    campaignContent: '',
    flashPlugin: false,
    sessaotp: 1800,
    trk_tp_ant: '',
    millennium: '',
    debug: false,
    paramsPost: '',
    sendFields: false,

    init: function () {

        this.qssl = (("https:" == document.location.protocol) ? "https:" : "http:");

        this.resolutionX = screen.width;
        this.resolutionY = screen.height;

        this.millennium = new Date(2000, 0, 1);

        this.trk_tp_ant = this.getCookie('trk_tp_ant');

        if (this.isNull(this.trk_tp_ant)) {
            this.resetTimeOld();
        }

        this.flashVersion = this.getFlashVersion();

        if (this.flashVersion == '0')
            this.flashPlugin = false;
        else
            this.flashPlugin = true;

        this.setCookie('campaign', this.getQueryString('utm_campaign'), '', "/");
        this.setCookie('campaignSource', this.getQueryString('campaignSource'), '', "/");
        this.setCookie('campaignMedium', this.getQueryString('campaignMedium'), '', "/");
        this.setCookie('campaignTerm', this.getQueryString('campaignTerm'), '', "/");
        this.setCookie('campaignContent', this.getQueryString('campaignContent'), '', "/");

        this.getEmail();
        this.getUserId();
        this.setSessionID();
        this.renderFlash();
    },

    execute: function (sendFields) {
        this.sendFields = sendFields;
        this.executeTracking();
    },

    trackFinish: function () {

        var pageIdTemp = this.getQueryString('pid');
		if( this.executou_1tracking==0 ){
			this.totalTimeLoad = Math.round((new Date() - this.startTime) / 1000);
			this.executou_1tracking=1;
		}else{
			this.totalTimeLoad=0;
		}


        if (this.isNull(this.resolutionX))
            this.resolutionX = screen.width;
        if (this.isNull(this.resolutionY))
            this.resolutionY = screen.height;

        if (this.sendFields) {
            this.getElements(document.getElementsByTagName('input'));
            this.getElements(document.getElementsByTagName('select'));
        }

        if (this.debug)
            this.addParameter("debug", "true");

        this.setCookie('obtxuserID', this.userId, cookie_expire_date, "/");
        cookie_expire_date = new Date();
        cookie_expire_date.setTime(cookie_expire_date.getTime() + (0.5 * 60 * 60 * 1000));

        var trkDateNow = new Date();
        var exp = Math.ceil((trkDateNow.getTime() - this.millennium.getTime()) / 1000 - this.trk_tp_ant);
        if (exp > this.sessaotp) {
            this.resetTimeOld();
            this.session += 'x';
        }

        this.setCookie('trk_tp_ant', Math.ceil((trkDateNow.getTime() - this.millennium.getTime()) / 1000), '', '/');
        this.setCookie('SessionID', this.session, cookie_expire_date, '/');

        this.addParameter("Url", escape(self.location));
        this.addParameter("UrlReferer", escape(document.referrer));
        this.addParameter("clientName", this.clientName);
        this.addParameter("resx", this.resolutionX);
        this.addParameter("resy", this.resolutionY);
        this.addParameter('totalTimeLoad', this.totalTimeLoad.toString());
        this.addParameter('email', this.email);
        this.addParameter('emailOld', this.emailOld);
        this.addParameter('sessionId', this.session);
        this.addParameter('userId', this.userId);
        this.addParameter('siteId', this.siteId);
        if (this.pageTitle == '')
            this.pageTitle = document.getElementsByTagName('title').length > 0 ? document.getElementsByTagName('title')[0].text : '';
			
        this.addParameter("pageTitle", this.fixstr(this.pageTitle));
        this.addParameter("flashVersion", this.flashVersion);
        if (pageIdTemp != '' && !this.executePost && !this.executeClick)
            this.pageId = pageIdTemp;
        this.addParameter("pageId", this.pageId);

        if (this.pageId > 0) {
            this.paramsPost = this.params;

            if (this.fields.length > 0)
                this.paramsPost += "&fields={'fields':[" + this.fields + "]}";

            if (this.information.length > 0)
                this.paramsPost += "&information={" + this.information + "}";

            this.paramsPost += this.getCampaign();

            this.getEmail();
        }
        this.addImage(PopStats.qssl + PopStats.registerUrl + '?' + PopStats.paramsPost);
		this.clear();
    },

    resetTimeOld: function () {
        this.trk_tp_ant = new Date();
        this.setCookie('trk_tp_ant', Math.ceil((this.trk_tp_ant.getTime() - this.millennium.getTime()) / 1000), '', "/");
        this.trk_tp_ant = this.getCookie('trk_tp_ant');
    },

    addImage: function (url) {
        var html_doc = document.getElementsByTagName('body').item(0);
        var idImg = '_imgPopStats_';

        if (!this.isNull(document.getElementById(idImg))) {
            html_doc.removeChild(document.getElementById(idImg))
        }

        var img = new Image(1, 1);
        img.setAttribute('id', idImg);
        img.src = url + "&cache=" + parseInt(Math.random() * 1000000000, 10);

        html_doc.appendChild(img);

        if (this.debug) {
            var strDebug = 'clietName = ' + this.clientName + '\n';
            strDebug += 'pageId = ' + this.pageId + '\n';
            strDebug += 'email = ' + this.email + '\n';
            strDebug += 'flashVersion = ' + this.flashVersion + '\n';
            strDebug += 'userId = ' + this.userId + '\n';
            strDebug += 'sessionId = ' + this.session + '\n';
            alert(strDebug);
        }
    },

    addEvent: function (obj, type, fn) {
        if (obj.attachEvent) {
            obj['e' + type + fn] = fn;
            obj[type + fn] = function () { obj['e' + type + fn](window.event); }
            obj.attachEvent('on' + type, obj[type + fn]);
        } else
            obj.addEventListener(type, fn, false);
    },

    removeEvent: function (obj, type, fn) {
        if (obj.detachEvent) {
            obj.detachEvent('on' + type, obj[type + fn]);
            obj[type + fn] = null;
        } else
            obj.removeEventListener(type, fn, false);
    },

    executeTracking: function () {
        if (!this.isNull(this.pageId)) {
            if (this.flashPlugin) {
                if (this.email != this.emailOld) {
                    this.flashCookie(this.email, this.emailOld, 1, this.session, this.userId); /*Aqui o pulo do gato: se o e-mail identificado via cookie Ã© diferente do e-mail anterior, o terceiro parÃ¢metro sendo 1, forÃ§a o flash a gravar os novos dados*/
                } else {
                    this.flashCookie(this.email, this.emailOld, 0, this.session, this.userId); /*ContrÃ¡rio da situaÃ§Ã£o acima, informa que o flash deve retornar os dados que ele tem armazenado*/
                }
            }
            else {
                this.flashCookie(this.email, this.emailOld, 0, this.session, this.userId); /*ContrÃ¡rio da situaÃ§Ã£o acima, informa que o flash deve retornar os dados que ele tem armazenado*/
            }
        }
    },

    getElements: function (elements) {

        for (var i = 0; i < elements.length; i++) {
            if (elements[i].className != undefined && elements[i].className != '' && elements[i].className.toString().indexOf('PopStats') > -1) {

                var classNames = elements[i].className.toString().split(' ');

                for (var j = 0; j < classNames.length; j++) {
                    if (classNames[j].toString().indexOf('PopStats') > -1) {
                        var fieldIds = classNames[j].toString().split(':');

                        if (fieldIds[1].toString() == 'email')
                            this.email = elements[i].value;

                        if (fieldIds.length != undefined && fieldIds.length == 2 && elements[i].value != '') {
                            if (this.params.length > 0)
                                this.params += '&';

                            if (elements[i].type == 'checkbox') {
                                if (elements[i].checked) {
                                    this.addFields(fieldIds[1].toString(), elements[i].value);
                                }
                            }
                            else if (elements[i].type == 'radio') {
                                if (elements[i].checked) {
                                    this.addFields(fieldIds[1].toString(), elements[i].value);
                                }
                            }
                            else {
                                this.addFields(fieldIds[1].toString(), encodeURI(elements[i].value));
                            }
                        }
                    }
                }
            }
        }

    },

    addParameter: function (key, value) {

        if (this.params.length > 0)
            this.params += '&';
        this.params += key + "=" + encodeURI(value);

    },

    addFields: function (key, value) {

        if (this.fields.length > 0)
            this.fields += ',';

        this.fields += "{'" + key + "'" + ":" + "'" + this.fixstr(encodeURI(value)) + "'}";

    },

    addInformation: function (key, value) {

        if (this.information.length > 0)
            this.information += ',';

        this.information += "'" + key + "'" + ":" + "'" + this.fixstr(encodeURI(value)) + "'";

    },

    getFlashVersion: function () {

        // ie
        try {
            try {
                var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
                try { axo.AllowScriptAccess = 'always'; }
                catch (e) { return '6,0,0'; }
            } catch (e) { }
            return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
            // other browsers
        } catch (e) {
            try {
                if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
                    return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
                }
            } catch (e) { }
        }

        return '0';
    },

    getCampaign: function () {

        var jsonReturn = '';

        this.campaign = this.getQueryString('utm_campaign');
        this.campaignSource = this.getQueryString('utm_source');
        this.campaignMedium = this.getQueryString('utm_medium');
        this.campaignTerm = this.getQueryString('utm_term');
        this.campaignContent = this.getQueryString('utm_content');
		this.smid = this.getQueryString('mid');
        if (this.campaign == '') this.campaign = this.getQueryString('s_cid');
        if (this.campaign == '') this.campaign = this.getQueryString('s_kwcid');
		
		if(this.campaign == '') {
			this.campaign = this.getCookie('campaign');
			this.campaignSource = this.getCookie('campaignSource');
			this.campaignMedium = this.getCookie('campaignMedium');
			this.campaignTerm = this.getCookie('campaignTerm');
			this.campaignContent = this.getCookie('campaignContent');
			this.campaign = this.getCookie('campaign');
		}

		if (isNaN(this.smid) || this.smid == '')
			this.smid = this.getCookie('obtxSMID');

        if (this.campaign != '') {

            jsonReturn += '&campaignData={';
            jsonReturn += '\'campaign\':' + "'" + this.fixstr(this.campaign) + "'";

            if (this.campaignSource != '')
                jsonReturn += ',\'campaignSource\':' + "'" + this.fixstr(this.campaignSource) + "'";

            if (this.campaignMedium != '')
                jsonReturn += ',\'campaignMedium\':' + "'" + this.fixstr(this.campaignMedium) + "'";

            if (this.campaignTerm != '')
                jsonReturn += ',\'campaignTerm\':' + "'" + this.fixstr(this.campaignTerm) + "'";

            if (this.campaignContent != '')
                jsonReturn += ',\'campaignContent\':' + "'" + this.fixstr(this.campaignContent) + "'";

            if (isNaN(this.smid) || this.smid == '' || this.smid == '0' || this.smid == 'null')
                this.smid = 1;

            jsonReturn += ',\'mid\':' + "'" + this.smid + "'";

            jsonReturn += '}';

        }

        this.setCookie('campaign', '', '', "/");
        this.setCookie('campaignSource', '', '', "/");
        this.setCookie('campaignMedium', '', '', "/");
        this.setCookie('campaignTerm', '', '', "/");
        this.setCookie('campaignContent', '', '', "/");
        this.setCookie('obtxSMID', this.smid, '', "/");

        return jsonReturn;
    },

    renderFlash: function () {

        if (this.flashPlugin) {

            var flash = '';

            flash = '<object id="trk_fl" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="' + this.qssl + '//download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0" width="1" height="1">';
            flash += '  <param name="movie" value="' + this.qssl + this.flashUrl + '?email=' + this.email + '&email_ant=' + this.emailOld + '&modo=0&sessao=' + this.session + '&userID=' + this.userId + '&trk_url=' + this.clientName + '" />';
            flash += '  <param name="quality" value="high" />';
            flash += '  <param name="allowScriptAccess" value="always"/>';
            flash += '  <param name="hasPriority" value="true" />';
            flash += '  <embed swliveconnect="true" name="trk_fl" src="' + this.qssl + this.flashUrl + '?email=' + this.email + '&email_ant=' + this.emailOld + '&modo=0&sessao=' + this.session + '&userID=' + this.userId + '&trk_url=' + this.clientName + '" quality="high" pluginspage="' + this.qssl + '//www.macromedia.com/go/getflashplayer" allowScriptAccess="always" type="application/x-shockwave-flash" width="1" height="1"></embed>';
            flash += '</object>';

            var html_doc = document.getElementsByTagName('body').item(0);
            var flashDiv = document.createElement('div');
            flashDiv.setAttribute('id', 'trk');
            flashDiv.setAttribute('style', 'position:absolute; left:0px; top:0px; width:1px; height:1px; z-index:1');
            html_doc.appendChild(flashDiv);

            var divTrk = document.getElementById('trk');

            if (divTrk)
                divTrk.innerHTML = unescape(flash);

        }

    },

    flashCookie: function (semail, semail_ant, modo, sessao, suserID) {

        if (this.flashPlugin) {

            var fm = this.getFlashMovieObject("trk_fl");
            var count = 0;
            if (fm) {
                if (fm.trk) {
                    fm.trk(semail, semail_ant, sessao, suserID, PopStats.clientName);
                    var emailTemp = fm.GetVariable("/:email");
                    if (!PopStats.isNull(emailTemp)) {
                        PopStats.email = fm.GetVariable("/:email");
                        PopStats.emailOld = fm.GetVariable("/:email_ant");
                        PopStats.userId = fm.GetVariable("/:userID");
                        PopStats.resolutionX = fm.GetVariable("/:resx");
                        PopStats.resolutionY = fm.GetVariable("/:resy");
                        PopStats.flashVersion = fm.GetVariable("/:versao");
                    }

                    PopStats.trackFinish();
                }
                else {
                    PopStats.trackFinish();
                }
            }
        } else {
            PopStats.trackFinish();
        }

    },

    getFlashMovieObject: function (movieName) {
        if (window.document[movieName]) {
            return window.document[movieName];
        }
        if (navigator.appName.indexOf("Microsoft Internet") == -1) {
            if (document.embeds && document.embeds[movieName])
                return document.embeds[movieName];
        } else { // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
            return document.getElementById(movieName);
        }
    },

    getEmail: function () {
        this.emailOld = this.getCookie('obtxEMAIL');
        if (this.isNull(this.emailOld))
            this.emailOld = 'tracking@anonimo.com.br';

        if (this.isNull(this.email)) {
            this.email = this.getCookie('obtxEMAIL');
            if (this.isNull(this.email))
                this.email = "tracking@anonimo.com.br";
        }

        cookie_expire_date = new Date();
        cookie_expire_date.setTime(cookie_expire_date.getTime() + (90 * 24 * 60 * 60 * 1000));
        this.setCookie('obtxEMAIL', this.mixString(this.email, 4), cookie_expire_date, "/");
    },

    getUserId: function () {

        this.userId = this.getCookie('obtxuserID'); /*Tenta obter o userid pelo cookie*/

        if (this.isNull(this.userId)) {
            this.userId = parseInt(Math.random() * 1000000000, 10);
        }

    },

    setSessionID: function () {
        /*Cria uma sessÃ£o se nova visita ou se nÃ£o houve atividade dentro de 30 minutos, definido pelo tempo de expiraÃ§Ã£o do cookie*/
        this.session = this.getCookie('SessionID');
        if (!this.session) {
            this.session = parseInt(Math.random() * 1000000000, 10);
            cookie_expire_date = new Date();
            cookie_expire_date.setTime(cookie_expire_date.getTime() + (0.5 * 60 * 60 * 1000));
            this.setCookie('SessionID', this.session, cookie_expire_date, "/");
        }
    },

    getQueryString: function (name) {
        get_string = document.location.search;
        return_value = '';
        name_index = get_string.indexOf('?' + name + '=');
        if (name_index == -1) {
            name_index = get_string.indexOf('&' + name + '=');
        }
        if (name_index != -1) {
            get_string = get_string.substr(name_index + name.length + 2, get_string.length - name_index);
            end_of_value = get_string.indexOf('&');
            if (end_of_value != -1) value = get_string.substr(0, end_of_value);
            else value = get_string;
            return_value = value;
        }
        space = return_value.indexOf('+');
        while (space != -1) {
            return_value = return_value.substr(0, space) + ' ' +
		return_value.substr(space + 1, return_value.length);
            space = return_value.indexOf('+');
        }
        return (return_value);
    },

    getCookie: function (name) {
        var start = document.cookie.indexOf(name + "=");
        var len = start + name.length + 1;
        if ((!start) && (name != document.cookie.substring(0, name.length))) return null;
        if (start == -1) return null;
        var end = document.cookie.indexOf(";", len);
        if (end == -1) end = document.cookie.length;
        return unescape(document.cookie.substring(len, end));
    },

    setCookie: function (name, value, expires, path, domain, secure) {
        var cookieString = name + "=" + escape(value) +
       ((expires) ? ";expires=" + expires.toGMTString() : "") +
       ((path) ? ";path=" + path : "") +
       ((domain) ? ";domain=" + domain : "") +
       ((secure) ? ";secure" : "");
        document.cookie = cookieString;
    },

    addTrack: function (type, elementId, pageId, email, objJson) {

        var objTracks = new Object();

        objTracks.type = type;
        objTracks.elementId = elementId;
        objTracks.pageId = pageId;
        objTracks.objJson = objJson;

        if (!this.isNull(email))
            objTracks.email = email;

        this.elementsTrack.push(objTracks);

    },

    clear: function () {
        this.startTime = new Date();
		this.totalTimeLoad = 0;
        this.params = '';
        this.fields = '';
        this.information = '';

    },

    sleep: function (milliSeconds) {
        var startTime = new Date().getTime(); // get the current time
        while (new Date().getTime() < startTime + milliSeconds); // hog cpu
    },

    isNull: function (qual) {
        if (typeof qual == "undefined")
            return true;
        qual = qual + '-';
        if (qual == '-' || qual == 'undefined-' || qual == 'null-')
            return true;
        else
            return false;
    },

    clickFlash: function () {

        if (!this.isNull(arguments[0])) {
            this.pageId = arguments[0];
        }
        if (!this.isNull(arguments[1])) {
            this.email = arguments[1];
        }

        if (!this.isNull(arguments[2])) {
            var infos = arguments[2];
            for (var info in infos) {
                this.addInformation(info, infos[info]);
            }
        }

        if (!this.isNull(arguments[3])) {
            var fields = arguments[3];
            for (var field in fields) {
                this.addFields(field, fields[field]);
            }
        }

        if (arguments.length > 0) {
            this.executeClick = true;
            this.execute(false);
        }
    },

    mixString: function (originalString, grouper) {
        if (originalString == "" || originalString.substr(0, 3) == "___") {
            return originalString;
        }
        else {
            var aString = originalString.split("");
            var mixedString = "";
            var localMixedString = "";
            for (var i = 0; i < aString.length; i++) {
                localMixedString = aString[i].concat(localMixedString);
                if (localMixedString.length % grouper == 0 || i == aString.length - 1) {
                    mixedString = mixedString.concat(localMixedString);
                    localMixedString = "";
                }
            }
            mixedString = mixedString.replace("@", "[a]");
            mixedString = mixedString.replace(new RegExp("\\.", "g"), "[p]");
            return ("___").concat(mixedString);
        }
    },
	
	fixstr: function (originalString){
		if(this.isNull(originalString)) originalString='';
		originalString = originalString.replace(/\'/g, "");
		originalString = originalString.replace(/\"/g, "");
		originalString = originalString.replace(/\&/g, "e");
		originalString = originalString.replace(/\#/g, " ");
		return originalString;
	}
};

PopStats.init();

PopStats.addEvent(window, 'load', function () {

	PopStats.totalTimeLoad = Math.round((new Date() - PopStats.startTime) / 1000);

	if(PopStats.totalTimeLoad<0) PopStats.totalTimeLoad=0;

    if (PopStats.executePost && PopStats.executePageView) {
        PopStats.execute(true);
    }
    else if (PopStats.executePost) {
        PopStats.execute(true);
    }
    else if (PopStats.executePageView) {
        PopStats.execute(false);
    }

    for (var i = 0; i < PopStats.elementsTrack.length; i++) {

        var element = document.getElementById(PopStats.elementsTrack[i].elementId);

        if (!PopStats.isNull(element)) {

            PopStats.addEvent(element, PopStats.elementsTrack[i].type, function () {
                PopStats.clear();
                PopStats.executeClick = true;

                for (var j = 0; j < PopStats.elementsTrack.length; j++) {
                    if (PopStats.elementsTrack[j].elementId == this.id) {
                        PopStats.pageId = PopStats.elementsTrack[j].pageId;

                        if (!PopStats.isNull(PopStats.elementsTrack[j].email))
                            PopStats.email = PopStats.elementsTrack[j].email;

                        if (!PopStats.isNull(PopStats.elementsTrack[j].objJson)) {
                            var infos = PopStats.elementsTrack[j].objJson;
                            for (var info in infos) {
                                PopStats.addInformation(info, infos[info]);
                            }
                        }

                        break;
                    }
                }

                PopStats.execute(false);
            });
        }
    }

});

