﻿// The global asis variable contains all the methods and variables pertinent to asis functionality.
// Think of it like a namespace
var asis = {
    webServiceUri:"nowhere",
    defaultTimeout:20000, // milliseconds
    imageContainer: {
        id:"asisImageContainer"
    }
};
asis.isExecuting = false;
// Embeds an image onto the page with the appropriate uri
asis.makeAsisCall = function(asisData, onComplete) {    
    if(!asisData || !asisData.fullUri) {
        return;
    }
    var asisImg = new Image(),
        cacheKillVar = "cache_kill=";
    // Need to update the cache_kill on the client side because click events can happen multiple times
    asisImg.src = asisData.fullUri.replace(cacheKillVar, cacheKillVar + new Date().getTime());
	onComplete();
};
// All of the calls get queued so they are definitely processed in order. There was a problem where the 
// header impression was getting sent after the other ones in the page. This prevents this.
asis.queue = [];
// Add a call to the queue
asis.enqueue = function(asisData) {
    asis.queue.push(asisData);
};
// Makes all the asis calls in the queue in order. 
asis.executeQueue = function() {
    if(asis.queue.length > 0) {
        var response = asis.makeAsisCall(asis.queue[0], asis.next);
    }
};
// Executes the next asis call in the queue and removes the previous one
asis.next = function(onComplete) {
    asis.queue.shift();
    asis.executeQueue(onComplete);
};
asis.getAsisProperties = function(element) {
    var el = jQuery(element);
    return {
        fullUri : el.attr("asis_full_uri"),
        async: el.is(".asisImpression") // Clicks need to be done synchronously to prevent image and web service requests from being cancelled
    }
};
asis.logImageSent = function(imageElement, onComplete) {
};
asis.addZip = function(asisData, zip) {    
    var parts = asisData.fullUri.split("?"),
        qs, length = 0, found = false;
    length = parts.length;
    qs = length > 1 ? parts[1].split("&") : [];
    length = qs.length;
    for (var i = 0; i < length; i++) {
        var t = qs[i];
        if(t.indexOf("address=")===0) {
            qs[i] = "address=" + zip;
            found = true;
        }
    }
    if(!found) {
        qs.push("address="+zip);
    }
    asisData.fullUri = parts[0] + "?" + qs.join("&");
    return asisData;
};
asis.getLandingPageZip = function() {
    return jQuery("[name*=txtZipCode]").val();
};
// Initializes the asis functionality. Must be called for anything to work. This allows you to set up any asis properties
// or control when the queuing gets executed.
asis.init = function() {
    jQuery(".asisImpression").each(function() {
        var data = asis.getAsisProperties(this);        
        asis.enqueue(data);
    });
    asis.executeQueue(); // Run all the impressions in order
    var clicks = jQuery(".asisClick");
    clicks.data("prevent", true);
    function asisClick(e) {        
        var data = asis.getAsisProperties(this),
            prevent = false,
            self = jQuery(this);
        if (self.is(".asisNeedsZip")) {
            var zip = asis.getLandingPageZip();
            data = asis.addZip(data, zip);
        }
        asis.enqueue(data);
        asis.executeQueue();
        return true;
    };
    clicks.each(function() {
		var src = jQuery(this);		
		if(src.is("input") && !src.is("[name*='btnGetCashOffer']")) {
			src.wrap("<span></span>").click(function(e) {
				jQuery(this).unbind("click");
				asisClick.call(src);
				setTimeout(function() {
					src.click();
				}, 750);
				return false;
			});
		} else {
			src.click(function() {
				asisClick.call(src);
			});
		}
    });
};
