
if(!window._com_eatMetrics)
    window._com_eatMetrics = {};

_com_eatMetrics.visit = function(/*..*/)
// Parameters will be added onto the request to server
{
    // The 'this' object is special -- it must be set to the accountData object
    var accountData = this;
    
    var url = "http://eatmetrics.com/visit.php";
    
    var payload = 'timestamp='+(new Date()).getTime();
    
    payload += '&account_id=' + escape(accountData.account_id);
    payload += '&visit_url=' + escape(document.location.href);
    payload += '&refer=' + escape(document.referrer);
    
    for(var i = 0; i < arguments.length; i++) {
        
        if(typeof (arguments[i]) == "object") {
            
            for(key in arguments[i])
                payload += '&' + escape(key) + '=' + escape(arguments[i][key]);
        }
        else
            payload += '&' + window.escape(arguments[i]);
    }
    
    var s = document.createElement('script');
    
    s.src = url + "?" + payload;
    
    document.body.appendChild(s);
};

// Returns the form's Restaurant ID node.  Use node.value to get the actual RID
_com_eatMetrics.getFormRIDNode = function(frm)
{
    var ret = null;
    
    for(var j = 0; j < frm.length; j++)
        if(frm[j].name == "RestaurantID")
            ret = frm[j];
    
    return ret;
}

// If setItTo is not false, the value will be set to the value of
// setItTo before returning that value.  If setItTo is null, than the value
// is simply returned.
_com_eatMetrics.getFormRID = function(frm, setItTo)
{
    var n = _com_eatMetrics.getFormRIDNode(frm);
    
    if(!n)
        return 0;
    
    if(setItTo)
        n.value = setItTo;
    
    return n.value;
}

// Returns the form's Restaurant ID node.  Use node.value to get the actual RID
_com_eatMetrics.getFormLinkNode = function(frm)
{
    var ret = null;
    
    if(!frm)
    	return null;
    
    for(var ptr = frm.nextSibling; ptr; ptr = ptr.nextSibling)
        if(ptr.id == "OT_logoLink") {
            
            var as = ptr.getElementsByTagName('a');
            
            if(as.length)
                ret = as[0];
        }
    
    return ret;
}

// If setItTo is not false, the innerText will be set to the value of
// setItTo before returning that text.  If setItTo is null, than the innerText
// is simply returned.
_com_eatMetrics.getFormLinkText = function(frm, setItTo)
{
    var n = _com_eatMetrics.getFormLinkNode(frm);
    
    if(!n)
        return 'Default';
    
    if(setItTo) {
    	
        n.innerText = setItTo;
        n.innerHTML = setItTo;
    }
    
    return n.innerText || n.innerHTML;
}

_com_eatMetrics.getParentByNodeName = function(node, parentNodeName)
{
    parentNodeName = parentNodeName.toLowerCase();
    
    while(node = node.parentNode)
        if(node.nodeName.toLowerCase() == parentNodeName)
            return node;
    
    return null;
}

_com_eatMetrics.dropDownSelection = function()
{
    var frm = this.nextSibling;
    var accountData = this.options[this.selectedIndex].accountData;
    /*
    var linkReg1 = /rid=[0-9]+/;
    var linkReg2 = /restref=[0-9]+/;
    
    var n = _com_eatMetrics.getFormLinkNode(frm);
    
    var href = n.href.toString();
    
    href = href.replace(linkReg1, 'rid=' + accountData.ot_id);
    href = href.replace(linkReg2, 'restref=' + accountData.ot_id);
    
    n.href = href;
    */
    _com_eatMetrics.getFormLinkText(frm, accountData.name);
    _com_eatMetrics.getFormRID(frm, accountData.ot_id);
}

_com_eatMetrics.loadUp = function(accountData)
{
    // Capture form submit with this function, canceling it.
    var catchSubmit = function(e)
    {
        if(catchSubmit.done)
            return true;
        
        var accountData = this.accountData;
        
        _com_eatMetrics.catchSubmit = arguments.callee;
        _com_eatMetrics.submitMe = this;
        
        _com_eatMetrics.visit.call(accountData, "goal1", {onFinish:1});
        
        return false;
    }
    
    // Capture link click with this function, canceling it.
    var catchClick = function(e)
    {
        if(catchClick.done)
            return true;
        
        var accountData = this.accountData;
        
        _com_eatMetrics.catchClick = arguments.callee;
        _com_eatMetrics.clickMe = this;
        
        _com_eatMetrics.visit.call(accountData, "goal1", {onFinish:2});
        
        return false;
    }
    
    var once = true;
    
    // Perform setup (may be called multiple times)
    var setupOnSubmit = function(accountData, count)
    {
        count = count || 0;
        
        if(count > 2)
            return;
        
        /* Find all forms that match the criteria, modify them as needed */
        
        var forms = document.forms || document.getElementsByTagName('form');
        
        for(var i = 0; i < forms.length; i++) {
            
            var frm = forms[i];
            
            // Skip non-matching forms.
            if(frm.id != 'ism' && frm.name != 'ism' &&
                frm.action != 'http://www.opentable.com/ism/interim.aspx')
                    continue;
            
            var formRID = _com_eatMetrics.getFormRID(frm);
            var defLocName = _com_eatMetrics.getFormLinkText(frm);
            
            // We can't really do much without this information!
            // Either OT changed their form layout or this is not an OT form.
            // Give up...
            if(!formRID)
                continue;
            
            var formMatch = false;
            
            if(formRID == accountData.ot_id)
                formMatch = true;
            
            // Create (or find) a dropdown for picking location
            // When dropdown selection made -- set frm.accountData
            if(!formMatch) {
                
                var sel = frm.previousSibling;
                
                // If selector was not present, add it now
                if(!sel || sel.nodeName.toLowerCase() != "select" || !sel.isFormDropdown) {
                    
                    sel = frm.parentNode.insertBefore(document.createElement('select'), frm);
                    
                    sel.isFormDropdown = true;
                    
                    // Create default option, What the form originally posted to
                    var o = sel.appendChild(document.createElement('option'));
                    
                    o.accountData = {name:defLocName, ot_id:formRID};
                    o.value = formRID;
                    o.appendChild(document.createTextNode(defLocName));
                    
                    sel.onchange = _com_eatMetrics.dropDownSelection;
                    
                    if(navigator.userAgent.indexOf("MSIE")!= -1) {
                    	
                    	sel.style.position = 'absolute';
                    	sel.style.top = -sel.offsetHeight + 'px';
                    	sel.style.zIndex = 100;
                    }
                }
                
                var alreadyInDropDown = false;
                
                /* Check if the dropdown already has our ot_id in it */
                for(var j = 0; j < sel.childNodes.length; j++)
                    if(sel.childNodes[j].value == accountData.ot_id)
                        alreadyInDropDown = true;
                
                if(!alreadyInDropDown) {
                    
                    // Create default option, What the form originally posted to
                    var o = sel.appendChild(document.createElement('option'));
                    
                    o.accountData = accountData;
                    o.value = accountData.ot_id;
                    o.appendChild(document.createTextNode(accountData.name));
                }
            }
            else {
                
                // Set default accountData
                frm.accountData = accountData;
            }
            
            frm.onsubmit = catchSubmit;
            
            // Note: There does not seem to be a way to cancel the form submit
            // event if you register the event the proper way, so we use the
            // onsubmit attribute.
        }
        
        /* Find all links that match criteria, capture click events. */
        
        var as = document.getElementsByTagName('a');
        
        // Regex to check for the proper ot_id inside the link.
        var rrid = new RegExp("([?]|[&])rid="+accountData.ot_id+"([&]|$)");
        var rref = new RegExp("([?]|[&])restref="+accountData.ot_id+"([&]|$)");
        
        // Regex to check the destination of the link.
        var rot = new RegExp("^[fhtps:\\/]*[^.]*[.]opentable.com");
        
        for(var i = 0; i < as.length; i++) {
            
            var a = as[i];
            
            if((rref.exec(a.href) || rrid.exec(a.href)) && rot.exec(a.href)) {
                
                a.accountData = accountData;
                a.onclick = catchClick;
            }
        }
        
        var ad = accountData;
        
        setTimeout(function()
        {
            setupOnSubmit(ad, count + 1);
        }, 1);
    };
    
    setupOnSubmit(accountData);
    
    var ad = accountData;
    
    // Fallback methods of capturing load events.
    if(window.attachEvent)
        window.attachEvent("onload", function()
        {
            setupOnSubmit(ad);
        });
    else if(window.addEventListener)
        window.addEventListener("load", function()
        {
            setupOnSubmit(ad);
        }, true);
    else {
        
        window.onload = function()
        {
            setupOnSubmit(ad);
        };
    }
    
    once = false;
    
    // Record this user's visit
    _com_eatMetrics.visit.call(accountData);
};

_com_eatMetrics.loadMultiple = function(accounts)
{
    for(var i = 0; i < accounts.length; i++)
        _com_eatMetrics.loadUp(accounts[i]);
};
