/* main utility functions for tagging.
 * tag configuruation is done in tag_config.js
 *
 * for DART tagging to work, this js file either:
 * - needs to be within tags <body></body> or
 * - have tags <iframe id="dart_iframe"></iframe> on page
 */

var atRoot = false;
var firedDartHome = false;
var firedDartFP = false;
var prefix, extenstion, domain, path, initialURL, port;
var startupFlashDeepLink = "";

//determine whether a URL has yet been tracked
function isAlreadyTracked(u) {
    var f = (u.indexOf("at=t") >= 0) ? true : false;
    
    return f;
}

/*
 activateDartTag()
 send out tags for Core Metrics & Dart
 */
function activateDartTag(src, type, cat, ord) {
	document.images['dart'].src = "http://fls.doubleclick.net/ad/activityi;src=" + src + ";type=" + type + ";cat=" + cat;
    
	return true;
}

//logic for dart tagging in flash
function dartTagControl(deeplinkKey) {
    //only tag on certain pages - home, featured iras
    if ( (deeplinkKey == "/featured/starttodayira/") && firedDartFP ) {
        return;
    } else if ( deeplinkKey == "/featured/starttodayira/" ) {
        firedDartFP = true;
    }
	
    if ( (deeplinkKey == "/featured/high-yield-ira-cd/" || deeplinkKey == "/fp/high-yield-ira-cd/") && firedDartFP ) {
        return;
    } else if (deeplinkKey == "/featured/high-yield-ira-cd/" || deeplinkKey == "/fp/high-yield-ira-cd/") {
        firedDartFP = true;
    }
	
    if ( deeplinkKey == default_tag_section && firedDartHome ) {
        return;
    } else if ( deeplinkKey == default_tag_section ) {
        firedDartHome = true;
    }
    
    if ( deeplinkKey == default_tag_section || deeplinkKey == "/featured/high-yield-ira-cd/" || deeplinkKey == "/fp/high-yield-ira-cd/" || deeplinkKey == "/featured/starttodayira/" ) {
        activateDartTag(dart_src, dart_type, dart_hash[deeplinkKey]["cat"], dart_ord);
    }
}

/*
 tagControl() - for HTML
 set tracking tag, depending on tag processing
 */
// sectionnames
// coretags
// darttags
// ... are all defined in tag_config.js

function tagControl() {
    // if we've already tagged this URL, let's get out of here.
    var url = window.location.href;
    
	if (isAlreadyTracked(url)) { return; }
    
    var response = processTagControl(url);
    var v = response.value;
	var s = window.top.location.search.indexOf('adlink');
    var e = (window.top.location.search.indexOf('&', s) > 0) ? window.top.location.search.indexOf('&', s) : window.top.location.search.length;
	var al = (s > 0) ? window.top.location.search.substring(s + 7, e) : null;
	
    switch ( response.msg ) {
        case "setTag_home":
          	
			cmCreatePageviewTag(cmPageIDs[v["cmPId"]], 'overview', null, cmCategoryIDs[v["cmCat"]], false, false, null, false, false, al, null, null);
			
            break;
        case "setTag_section":

            cmCreatePageviewTag(cmPageIDs[v["cmPId"]], 'overview', null, cmCategoryIDs[v["cmCat"]], false, false, null, false, false, al, null, null);
			
            break;
        default:
            //createTag( "malformed_section_name", DO_DART_TAG);
            break;
    }
}

//based on deeplink string, create tags
function processTagControl(url) {
    var response = {
        msg: "",
        value: {
            "cmPId": "",
            "cmCat": ""
        }
    }; //"setTag_home", "setTag_section", "error"
    
    var dlMatch = url.match("[#]([^?#]+)"); //eg, null, ["#/section/subsection", "/section/subsection"]
    
	// we're in HTML w/ javascript. have a different URL to parse for "deeplink"
    if ( getCookie("ver") == "html" ) {
        dlMatch = url.match("http://[^/]+(.*[/]).*$");
    };
    
    // we know user is at the home page if:
    //   there's no hash mark (i.e., no deeplinking)
    //   or if the hash mark is impossibly close to the end of the URL.
    // examples:
    //  "http://64.106.216.174/nfmp/"
    //  "http://64.106.216.174/nfmp/#"
    //  "http://64.106.216.174/nfmp/#/"
    //
    // dlMatch[0] - for Flash deeplink, dlMatch[1] for HTML deeplink
    if ( dlMatch == null || dlMatch[0].length <= 2 || dlMatch[1] == "/" ) {
        response.msg = "setTag_home";
        response.value["cmPId"] = default_tag_section;
        response.value["cmCat"] = default_tag_section;
		
        return response;
    }
    
    // so now  we know there's a deeplink. of some sort.
    // let's use it to find the section name (it goes after the hash sign)
    //
    var section = dlMatch[1]; // eg, "/section/subsection"
    
    if ( cmPageIDs[section] != null ) {
        response.msg = "setTag_section";
        response.value["cmPId"] = section;
        response.value["cmCat"] = section;
		
        return response;
    }
    
   	response.msg = "error";
	
    return response;
}

//control deeplink-url re-writing
function deeplinkControl() {
    // let's not rewrite url for HTML version
    if ( getCookie("ver") == "html" ) {
        return;
    };
    
    var response = newProcessURL(window.location.href); //dl_processURL(window.location.href);
    
    switch ( response.msg ) {
        case "loadSWFObject":
         	startupFlashDeepLink = response.value;
            loadSWFObject();
			
			break;
        case "setLocation":
            this.location.href = response.value;
            break;
        default:
           break;
    }
}

function newProcessURL(u) { 
    initialURL = u;
    prefix = "http://";
    extension = ".com";
    port = (u.lastIndexOf(":") > 4) ? u.substring(u.lastIndexOf(":"), u.lastIndexOf(":") + 3) : "";
    domain = u.substring(u.indexOf(prefix) + prefix.length, u.indexOf(extension) + extension.length);
    
    var stop = -1;
	
    if ( u.indexOf("Default.aspx?") > -1 ) {
		stop = u.indexOf("Default.aspx?");
	} else if ( u.indexOf("?") > -1 ) {
		stop = u.indexOf("?");
	} else if ( u.indexOf("#") > -1 ) {
		stop = u.indexOf("#");
	} else {
		stop = u.lastIndexOf("/") + 1;
	}
			
    path = (stop > -1) ? u.substring(u.indexOf(domain) + domain.length + port.length, stop) : "";
    
    return {
        msg: "loadSWFObject",
        value: path
    };
}

//process a URL and determine which kind of URL re-write is needed
function dl_processURL(url) {
    // default reponse object
    var response = {
        msg: "",
        value: ""
    }; //"setLocation", "loadSWFObject"
    
    //reg exp's to parse URL parts
    var urlPath = url.match("^[^?#]+")[0]; //eg, "http://site.com/sec/sub/Default.aspx"
    var urlQuery = url.match("[?]([^?#]+)"); //eg, "?q=f&cn=2&tr=434"
    var urlDeepLink = url.match("[#]([^?#]+)"); //eg, "#/section/subsection"
    
	//clean up data
    urlPath = urlPath.replace("http://", "").replace("/Default.aspx", ""); // clean it
    urlQuery = (urlQuery != undefined) ? urlQuery[1] : "";
    str_urlDeepLink = (urlDeepLink != undefined) ? urlDeepLink[1] : "";
    
    // if we've already tagged this view, just give them the SWF
    if ( isAlreadyTracked(url) ) {
        response.msg = "loadSWFObject";
        return response;
    }
    
    var re_coreMetricTags = "cm_mmc|cm_sp|cm_re";
    var arr_filteredQuery = [];
	
    arr_urlQuery = (urlQuery != "") ? urlQuery.split("&") : []; // ["cmc=234","one=two"]
    
    if ( !urlQuery.match(re_coreMetricTags) ) {
        arr_filteredQuery = arr_urlQuery;
    } else {
        for ( var i = 0; i < arr_urlQuery.length; i++ ) {
            if ( !arr_urlQuery[i].match("cm_mmc|cm_sp|cm_re") ) {
                // add back everything but core metric
                arr_filteredQuery.push(arr_urlQuery[i]);
            } else {
                //send marketing codes off to coremetrics
                var cmID = arr_urlQuery[i].split("=")[0];
                var cmValue = arr_urlQuery[i].split("=")[1];
				
                tagIt(cmID, cmValue);
                
            }
        }
    }
	
    //Lets make our calls before we set at=t
    arr_filteredQuery.unshift("at=t"); // mark as already tagged
    
	// let's reconstruct our new URL
    arr_urlPath = urlPath.split("/"); // eg, ['site.com', 'section', 'subsection']
    
	var newUrl = "http://" + arr_urlPath.shift() + "/Default.aspx"; // add server
    
	newUrl += "?" + arr_filteredQuery.join("&"); // add query params
    newUrl += "#/" + arr_urlPath.join("/"); // add deep link
    newUrl += (arr_urlPath.length != 0) ? "/" : ""; // add on trailing slash
    
    response.msg = "setLocation";
    response.value = newUrl;
    
	return response;
}

function _cmCreateConversionEventTag(id, actionType) {
    //alert("CONVERSION EVENT");
    
	cmCreateConversionEventTag('IRA-PRN', actionType, cmCategoryIDs[flash2cmIdMap[id]], null, null, null, null, null);
}

function _cmCreateManualPageviewTag(id, path) {
    //alert("MANUAL PAGE VIEW");
    
    var _path = path;
    
    if (_path == "window.top.location") {
        _path = window.top.location;
    }
    
    cmCreateManualPageviewTag(cmPageIDs[id], cmCategoryIDs[id], _path, window.top.location);
}

function _cmCreatePageviewTag(id) {
    //alert("PAGE VIEW");
    
    var s = window.top.location.search.indexOf('adlink');
    var e = (window.top.location.search.indexOf('&', s) > 0) ? window.top.location.search.indexOf('&', s) : window.top.location.search.length;
    var al = (s > 0) ? window.top.location.search.substring(s + 7, e) : null;
    
    var cmError = false;
    
    cmCreatePageviewTag(cmPageIDs[id], 'overview', null, cmCategoryIDs[id], false, false, null, false, false, al, null, null);
    
    dartTagControl(id);
}

function _cmCreateProductViewTag(id) {
    //alert("PRODUCT VIEW");
    
    cmCreateProductviewTag('RetirementPlan', 'RetirementPlan', cmCategoryIDs[flash2cmIdMap[id]], null, false, false, null, false, null, null, false);
}

function _cmCreateShopAction5Tag() {
    //alert("SHOP ACTION 5");
    
    cmCreateShopAction5Tag('RetirementPlan', 'RetirementPlan', 'BAISI:Promotions:RetCalc', null, null, true);
}

var customerID;
var orderID;
var uniquenessEnforcer1;
var uniquenessEnforcer2;
var uniquenessEnforcerOffset1;
var uniquenessEnforcerOffset2;

function _cmCreateShopAction9Tag(id) {
    //alert("SHOP ACTION 9");
	
    var date = new Date();
    var timeStamp = date.getTime().toString();
    
	uniquenessEnforcer1 = Math.round(Math.random() * 1000000).toString();
	uniquenessEnforcer2 = Math.round(Math.random() * 1000000).toString();
	
	var uniquenessEnforcerArray = [uniquenessEnforcer1, uniquenessEnforcer2];
	
	uniquenessEnforcerOffset1 = 7 - uniquenessEnforcer1.length;
	uniquenessEnforcerOffset2 = 7 - uniquenessEnforcer2.length;
	
	for ( var i = 0; i < uniquenessEnforcerArray.length; i++ ) {
		for ( var j = 0; j < this["uniquenessEnforcerOffset" + String(i + 1)]; j++ ) {
			this[uniquenessEnforcer = '0' + String(i + 1)] + this["uniquenessEnforcer" + String(i + 1)];
		}
	}
	
	customerID = ( customerID == undefined ) ? timeStamp + uniquenessEnforcer1 : customerID;
	//orderID = timeStamp + uniquenessEnforcer2;
	
    cmCreateShopAction9Tag('RetirementPlan', 'RetirementPlan', customerID, null, cmCategoryIDs[flash2cmIdMap[id]], null, null, null, null, true, null);
}