// These values must match the UserActionType
var ShareType = {ShareVehicle: 12, ShareDealer: 15}

function ShareClickLogger()
{
    this.nodesWithAttribute = [];
    this.openTimerId = -1;
    this.openMoreTimerId = -1;
    this.openFound = false;
    this.openMoreFound = false;
    this.debug = false;
    this._dlrId = -1;
    this._vehId = -1;
    this._userActionTypeId = -1;
    
    //Starts a timer that will run tryToAddLogging() over an over
    //until a certain open div is found, then openFound will be set
    //and a bunch of other stuff will happen
    this.startOpenPoller = function()
    {
        if(this.openFound || this.openTimerId != -1) return;
        this.openTimerId = setInterval("ShareClickLoggerVar.tryToAddLogging()", 500);
    }
    
    //Starts a timer that will run tryToAddMoreLogging() over an over
    //until a certain open div is found, then openMoreFound will be set
    //and a bunch of other stuff will happen
    this.startOpenMorePoller = function()
    {
        if(this.openMoreFound || (this.openFound && this.openMoreTimerId != -1)) return;
        this.openMoreTimerId = setInterval("ShareClickLoggerVar.tryToAddLogging('more')", 500);
    }

    //Adds onclick event handlers to elements    
    this.tryToAddLogging = function(level)
    {
        //Find the div we are looking for
        var openDiv;
        if(level == null || level == "")
        {
            if(this.openFound) return;
            openDiv = document.getElementById("at_hover");
        }
        else
        {
            if(this.openMoreFound) return;
            openDiv = document.getElementById("at16ps");
        }
        
        //If the div was found then it's ready for processing
        if(openDiv != null)
        {
            //Stop our timer and don't check again
            if(level == null || level == "")
            { 
                clearTimeout(this.openTimerId);
                this.openTimerId = -1;
                this.openFound = true;
            }
            else
            {   
                clearTimeout(this.openMoreTimerId);
                this.openMoreTimerId = -1;
                this.openMoreFound = true;
            }
            
            //Get all child nodes under the one we got above that have an onclick event/attribute of addthis_sendto
            this.nodesWithAttribute = []; //Clear here since this will be added to
            this.getNodesWithAttribute(openDiv, "onclick", "addthis_sendto", this.nodesWithAttribute);
            
            //Add handlers to our elements, if we are loading the "More" dialog, do it in 3 parts because it is really slow
            this.addHandlersToElements(this.nodesWithAttribute, 0, 9999)
                
            //Delay-add the rest of the elements.  Uncomment these if things load too slowly, and adjust the top index of the first load
            //var lastDelay = 0;
            //var rangeIndex;
            //var rangeEndIndex;
            //var rangeInc = 35;
            //var timeInc = 600;
            //for(rangeIndex = 24; rangeIndex < 210; rangeIndex += rangeInc)
            //{
            //    lastDelay += timeInc;
            //    rangeEndIndex = rangeIndex + rangeInc - 1;
                
            //    setTimeout("ShareClickLoggerVar.addHandlersToElements(ShareClickLoggerVar.nodesWithAttribute, " + rangeIndex + ", " + rangeEndIndex + ")", lastDelay);

            //}
            //setTimeout("ShareClickLoggerVar.addHandlersToElements(ShareClickLoggerVar.nodesWithAttribute, " + (rangeEndIndex+1) + ", 9999)", (lastDelay + timeInc));
        } else {
            this.debugPrint((new Date()).toString());
        }
    }
    
    this.addHandlersToElements = function(elements1, startIndex, endIndex)
    {
        //Loop through all the nodes we found and add to their onclick events
        for(var i = startIndex; i < elements1.length && i <= endIndex; i++)
        {
            var thisNode = elements1[i];
            
            //Pull who we are sharing with from the current onclick
            var currentOnClick = this.getAttributeValueIfExists(thisNode, "onclick");
            var patt = new RegExp("addthis_sendto\\('(.*)'\\)");
            var result;
            var shareWith = "";
            try {
                result  = patt.exec(currentOnClick);
                shareWith = result[1];
            } catch(e2) { this.debugPrint("ERROR"); }
            
            //Add to onclick so that we can log who the user is sharing with
            //or add onclick handlers to more links
            if(shareWith == "more")
            {
                //Add a handler so if the user clicks "more", start the timer that will call this 
                //function to add handlers to the "more" buttons that pop up
                elements1[i].onclick = 
                    (function(old, new1, arg1) {
                        return function() 
                        {
                            old.call(this, arguments);
                            new1.call(this, arg1);
                        }
                    })(elements1[i].onclick, Function.createDelegate(this, this.startOpenMorePoller), null);
            } else {
                //Set onclick to call the old onclick, then log the click
                elements1[i].onclick = 
                    (function(old, new1, arg1) {
                        return function() 
                        {
                            new1.call(this, arg1);
                            old.call(this, arguments);
                        }
                    })(elements1[i].onclick, Function.createDelegate(this, this.onShareItemClicked), shareWith);
            }
            this.debugPrint("adding " + shareWith + " " + this.openFound + " " + this.openMoreFound + "<BR>");
        }
    }


    //Logs the click for conversion tracking purposes
    this.onShareItemClicked = function(shareWith)
    {
		if (ShareClickLoggerVar._userActionTypeId == -1) 
		{
			ShareClickLoggerVar._userActionTypeId = (ShareClickLoggerVar._vehId > 0) ? ShareType.ShareVehicle : ShareType.ShareDealer;
		}
		
		if (ShareClickLoggerVar._userActionTypeId == ShareType.ShareVehicle)
		{
        LogUserActionByVehicle(
            ShareClickLoggerVar._userActionTypeId,
            ShareClickLoggerVar._dlrId,
            ShareClickLoggerVar._vehId);
		}
		else if (ShareClickLoggerVar._userActionTypeId == ShareType.ShareDealer)
		{
			LogUserActionByDealer(
				ShareClickLoggerVar._userActionTypeId,
				ShareClickLoggerVar._dlrId
			);
		}
    }
    
    //Stores ids of nods / child nodes that have an attribute that partially/wholly contains a value
    this.getNodesWithAttribute = function(root, attributeName, attributeValueContains, storageArray)
    {
        if(root == null) return;
        
        //Does this node contain the attribute?
        var attributeValue = this.getAttributeValueIfExists(root, attributeName);
        if(attributeValue != "")
        {
           //It does contain the value, add it to the lists
           if(attributeValue.indexOf(attributeValueContains) != -1)
           {
                storageArray[storageArray.length] = root;
           }
        }
        
        //Check child nodes of this element
        var i;
        for(i = 0; i < root.childNodes.length; i++)
        {
            this.getNodesWithAttribute(root.childNodes[i], attributeName, attributeValueContains, storageArray);
        }
        
        return storageArray;
    }

    //Returns the value of an attribute if it exists, "" if it doesn't, or "error" if something breaks
    this.getAttributeValueIfExists = function(node, attrName)
    {
        var attr = "";

        try
        {
            if(node.attributes[attrName] != null)
                attr = node.attributes[attrName].value;
        } catch(e) { 
            attr = "error"; 
        }
            
        return attr;
    }
    
    this.debugPrint = function(txt1)
    {
        if(this.debug)
        {
            var div1 = document.getElementById("divProperties");
            div1.innerHTML += txt1;
        }
    }
}


//Wrapper so we can call this without worrying about object instantiation
function fnShareClickLoggerStartOpenPoller(action)
{
	if(ShareClickLoggerVar != null)
	{
	    if (action == "hover")
	    {
		    ShareClickLoggerVar.startOpenPoller();
		}
		else
		{
		    ShareClickLoggerVar.startOpenMorePoller();
		}
	}
}
