///////////////////////////////////////////
var iContactID  = null;
var has_contact_id = false;
//console.log('found flash');
function readCookie(name) {

    var cookiename = name + "=";
    var ca = document.cookie.split(';');

    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(cookiename) == 0) {
            return c.substring(cookiename.length,c.length);
        }
    }
    return null;
}

function fireGUIDPixel() {

    var FormGUID = document.getElementById('cCCGUID').value;
    var site = location.href;

    var tData = {'record':1,'cGUID':FormGUID, 'mExtra':site};
    if(has_contact_id) {
       tData.iContactID = iContactID;
    }

    var req = new Request({
        url: '/plugins/firepixel.php',
        data: tData,
		method: "get"
		//onRequest: function() { alert('Request made. Please wait...'); },
		//onComplete: function(response) { alert('Response: ' + response); }
	}).send();
}

function ajaxObject(url, idx, callbackFunction)
{
    //console.log('calling ajaxObject');
    var uri;
    var that      = this;
    this.updating = false;
    this.abort    = function() {
        if(that.updating) {
            that.updating = false;
            that.AJAX.abort();
            that.AJAX     = null;
        }
    };

    this.update = function(passData, postMethod)
    {
        //console.log('update called');
        if(that.updating) {
            return false;
        }

        that.AJAX = null;

        if(window.XMLHttpRequest) {
            that.AJAX = new XMLHttpRequest();
        } else {
            that.AJAX = new ActiveXObject("Microsoft.XMLHTTP");
        }

        if(that.AJAX === null) {
            return false;
        } else {
            that.AJAX.onreadystatechange = function()
            {
                if (that.AJAX.readyState == 4) {
                    that.updating = false;
                    that.callback(idx,that.AJAX.responseText, that.AJAX.status, that.AJAX.responseXML);
                    that.AJAX = null;
                }
            };

            that.updating = new Date();

            if(/post/i.test(postMethod)) {
                uri = urlCall + '?' + that.updating.getTime();
                that.AJAX.open("POST", uri, true);
                //that.AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                that.AJAX.setRequestHeader("Content-type", "text/plain");
                that.AJAX.setRequestHeader("Content-Length", passData.length);
                //alert('passData: ' + passData);
                that.AJAX.send(passData);
            } else {
                uri = urlCall + '?' + passData + '&timestamp=' + (that.updating.getTime());
                that.AJAX.open("GET", uri, true);
                that.AJAX.send(null);
            }
            return true;
        }
    };

    var urlCall = url;

    this.callback = callbackFunction || function ()
    {
        //console.log('AJAX Request Done');
    };


}

function updateStatID(idx,id) {
    if(id!==undefined && id!==null && id!='') {
        globalStats[idx].StatID = parseInt(id);
    }
}

function itemMonitor(obj)
{
    //console.log("object: " + obj);
    var idx = obj.id;
    if(globalStats[idx].currentItem != obj.index) {
        //console.log(iContactID);
        //console.log(flashvars);
        globalStats[idx].total_watched += globalStats[idx].currentPosition;

        var statistics =
        {
            file:            flashvars[idx].file,
            title:          'ITEM',
            state:            'INITIALIZE',
            //state:            globalStats[idx].currentState,
            watched:          Math.round(globalStats[idx].currentPosition),
            total_watched:    Math.round(globalStats[idx].total_watched),
            skipped:          Math.round(globalStats[idx].skipped),
            total_buffering:  globalStats[idx].total_buffering,
            userid:           globalStats[idx].StatID,
            iContactID:        iContactID,
            cGUID:              (document.getElementById('cCCGUID') !== null ? document.getElementById('cCCGUID').value : '')
        };
        //console.log('first: ' +statistics);
        if(globalStats[idx].currentPosition>0) {
            statistics.duration = obj.duration;
        }
        myRequest[idx].update(JSON.stringify(statistics), 'POST');

          // reset counters
        globalStats[idx].currentPosition = 0;
    }

    //...global for use in other functions and to remember the previous item
    globalStats[idx].currentItem = obj.index;
}

function stateMonitor(obj)
{
    var idx = obj.id;
    var statistics = {};
    // stop
    if((obj.newstate == 'IDLE') && (globalStats[idx].playItem === true)) {
        //console.log("stop");
        globalStats[idx].StatID = null;
        globalStats[idx].currentItem = -1;
        globalStats[idx].total_watched=0;
        globalStats[idx].playItem = false;
    }

    // which states to monitor for changes in the playing item, pausing, skipping, etc.

    // accumulate the total time spent buffering
    // reset per video or accumulate sum total??
    // what sort of time is available during buffering??
    if(obj.newstate == 'BUFFERING' && globalStats[idx].playItem===false) {
        globalStats[idx].playItem=true;
        globalStats[idx].buffering_start = new Date().getTime();
        //console.log('buffering');


    } else if((obj.newstate == 'PLAYING') && (globalStats[idx].buffering_start !== 0)) {
        globalStats[idx].total_buffering += Math.round((new Date().getTime() - globalStats[idx].buffering_start) / 1000);
        //gid('buffer').innerHTML = 'Total Buffering Time: ' + total_buffering;
        globalStats[idx].buffering_start = 0;
        //console.log('done buffering');

    } else if((obj.newstate == 'PLAYING')) {
        //console.log("starting");
        statistics =
        {
            file:               flashvars[idx].file,
            title:              'STATE',
            state:              'BUFFERING',
            watched:            Math.round(globalStats[idx].total_duration),
            total_watched:      Math.round(globalStats[idx].total_watched),
            skipped:            Math.round(globalStats[idx].skipped),
            userid:             globalStats[idx].StatID,
            iContactID:         iContactID,
            cGUID:             (document.getElementById('cCCGUID') !== null ? document.getElementById('cCCGUID').value : '')
        };
        //console.log(statistics);
        //fire ajax call
        myRequest[idx].update(JSON.stringify(statistics), 'POST');
    }

    if(obj.newstate == 'COMPLETED') {
      // drop out of fullscreen
      // this.window.focus();

      //load a new page
      //window.location = 'http://www.google.com';
        statistics =
        {
            file:               flashvars[idx].file,
            title:              'STATE',
            state:              'COMPLETED',
            duration:           Math.round(globalStats[idx].total_duration),
            watched:            Math.round(globalStats[idx].total_duration),
            total_watched:      Math.round(globalStats[idx].total_watched),
            skipped:            Math.round(globalStats[idx].skipped),
            total_buffering:    globalStats[idx].total_buffering,
            userid:             globalStats[idx].StatID,
            iContactID:         iContactID,
            cGUID:              (document.getElementById('cCCGUID') !== null ? document.getElementById('cCCGUID').value : '')
        };
        //console.log(statistics);
        //fire ajax call
        myRequest[idx].update(JSON.stringify(statistics), 'POST');
    }

    //...global for use in other functions and to remember the previous state
    globalStats[idx].currentState = obj.newstate;
}


function timeMonitor(obj)
{
    var idx = obj.id;
    //console.log('time montior');
    //...global for use in other functions and to remember the previous position
    // accumulate position for amount watched
    globalStats[idx].currentPosition = obj.position;
    //console.log(globalStats[idx].currentPosition);
    if(globalStats[idx].previousPosition < globalStats[idx].currentPosition - 0.5) {
        globalStats[idx].skipped += globalStats[idx].currentPosition - globalStats[idx].previousPosition;
    }

    //console.log(globalStats[idx].currentState);

    if(globalStats[idx].currentPosition % 5===0 && globalStats[idx].currentState=='PLAYING' && globalStats[idx].previousPosition <= globalStats[idx].currentPosition) {
        //alert('broken');
        globalStats[idx].total_watched += globalStats[idx].currentPosition;
        globalStats[idx].total_duration = obj.duration;
        var statistics =
        {
            file:               flashvars[idx].file,
            title:              'TIME',
            state:              globalStats[idx].currentState,
            duration:           obj.duration,
            watched:            Math.round(globalStats[idx].currentPosition),
            total_watched:      Math.round(globalStats[idx].total_watched),
            skipped:            Math.round(globalStats[idx].skipped),
            total_buffering:    globalStats[idx].total_buffering,
            userid:             globalStats[idx].StatID,
            iContactID:         iContactID,
            cGUID:              (document.getElementById('cCCGUID') !== null ? document.getElementById('cCCGUID').value : '')
        };
        //console.log(statistics);
        //fire ajax call
        myRequest[idx].update(JSON.stringify(statistics), 'POST');

    }

    globalStats[idx].previousPosition = globalStats[idx].currentPosition;
}


function gid(name)
{
    return document.getElementById(name);
}


///////////////////////////////////////////////////////////////////////////