﻿var flashCookieMovie;
var retries = 0;
var retriesLimit = 5;
var flashVersion = 'Unknown';

// Start the Flash cookie function on document load
if (bindWindowEvent("load", addFlashCookieMovie) == false)
{
    window.onload = addFlashCookieMovie;
}

// Fixes potential IE error with flash events by removing Flash movie from document
window.onunload = function()
{
    var flashCookieMovieContainer = document.getElementById('divFlashCookiesContainer');
    
    if (flashCookieMovieContainer)
    {
        flashCookieMovieContainer.innerHTML = "";
    }
}

function addFlashCookieMovie()
{
    if (checkIfFileExists("/fc.swf"))
    {
		var flashCookieMovieContainer = document.getElementById('divFlashCookiesContainer');
	
        flashCookieMovieContainer.innerHTML =
            '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="1" height="1" id="FlashCookies">' + 
	            '<param name="allowScriptAccess" value="always" /> ' + 
                '<param name="swliveconnect" value="true">' + 
	            '<param name="movie" value="/fc.swf" /> ' + 
                '<embed ' + 
                    'allowScriptAccess="always"' + 
                    'swliveconnect="true"  ' +           
                    'name="FlashCookies"' + 
                    'src="/fc.swf"' + 
                    'type="application/x-shockwave-flash"' + 
                    'width="1"' + 
                    'height="1">' + 
                '</embed>' + 
            '</object>';
    }
    else
    {
        reportError('addFlashCookieMovie', 'Flash cookies movie does not exists or is not accessible.');
    }
}

function trace(message)
{
    if(message == 'External Interface OK')
    {
        flashCookieMovie = getFlashMovieObject("FlashCookies");

        // Check if Flash movie exists
        if (isObjectValid(flashCookieMovie.GetCookie))
        {
            setTimeout(runFlashCookie, 100);
        }
        else
        {
            reportError('validateFlashCookie', 'Can\'t access Flash cookies movie internal methods.');
        }
    }
}

function runFlashCookie()
{
    var cookieName = "fct";
    var cookieValue = "true";
    var isBlockingCookies = (document.cookie == '');
    var hasRegularCookie = (readCookie(cookieName) == cookieValue);        
    var hasFlashCookie = false;
    
	try
	{
		var hasFlashCookie = (flashCookieMovie.GetCookie(cookieName) == cookieValue);
	}
	catch (e)
	{
		reportError('GetCookie', e);
	}
	
    if(!hasFlashCookie && !hasRegularCookie)
    {
       if(!isBlockingCookies && canEnterFlashCookie)
       {
			try
			{
				flashCookieMovie.SetCookie(cookieName, cookieValue);
			}
			catch (e)
			{
				reportError('SetCookie', e);
			}
            
            createCookie(cookieName, cookieValue, 9999);
            asyncRequest("/" + S_SITE_LANG + "/app/?tag=Flash_Cookie_Count_User");
        }
    }
    else
    {
        CountWebAd('605354');
        
        if (hasFlashCookie)
        {
            CountWebAd('605352');
        }
        
        if (hasRegularCookie)
        {
            CountWebAd('605353');
        }
    }
}  

// Binds event to window
function bindWindowEvent(eventName, method)
{
    if (window.addEventListener)
    {
        window.addEventListener(eventName, method, false)
        return true;
    }
    else if (window.attachEvent)
    {
        window.attachEvent("on" + eventName, method)
        return true;
    }
    
    return false;
}

// Reports Flash cookie errors
function reportError(method, message)
{
    asyncRequest("/" + S_SITE_LANG + "/app/?tag=Flash_Cookie_Error&method=" + method + "&message=" + message + "&flash_version=" + flashVersion);
}

// Flash internal flash version report
function getVersion(version)
{
    flashVersion = version;
}

// Gets Flash movie according to browser
function getFlashMovieObject(movieName)
{
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName]; 
  }
  else
  {
    return document.getElementById(movieName);
  }
}    

// Checks if and object is loaded correctly
function isObjectValid(object)
{
    if (object == null || typeof(object) == "undefined" || undefined == object)
    {
        return false;
    }
    
    return true;
}

function checkIfFileExists(url)
{
    var request = new createXMLHttpRequest();
    request.open("HEAD", url, false);
    request.send();
    
    return (request.status==404) ? false : true;
}

// Opens asynchronous http reuqest
function asyncRequest(url, method)
{
    if(!method)
    {
        method = "GET";
    }

	var paramSeperator = "?";
	if (url.indexOf("?") != -1)
	{
		paramSeperator = "&";
	}
	url += paramSeperator + "rand="+ Math.random().toString();	
	
    var request = new createXMLHttpRequest();
    request.open(method, url, false);
    request.send(null);
} 

function getQueryString(key)
{
    pairs = window.location.search.substring(1).split("&");
    for (i=0; i < pairs.length; i++)
    {
        pair = pairs[i].split("=");
        if (pair[0] == key) {
        return pair[1];
        }
    }
}

// Cookie helper functions: create, read and clear
function createCookie(name,value,days)
{
    if (days)
    {
	    var date = new Date();
	    date.setTime(date.getTime()+(days*24*60*60*1000));
	    var expires = "; expires="+date.toGMTString();
    }
    else
    {
        var expires = "";
    }
    
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
    var nameEQ = 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(nameEQ) == 0) 
	    {
	        return c.substring(nameEQ.length,c.length);
	    }
    }
    
    return null;
}

function eraseCookie(name)
{
    createCookie(name,"",-1);
}