//Implement JSON.stringify serialization -
// needed fro the fact some browsers do not support JSON
// object and its functions
var JSON = JSON || {};
JSON.stringify = JSON.stringify || function (obj) {
	var t = typeof (obj);
	if (t != "object" || obj === null) {
		// simple data type
		if (t == "string") obj = '"'+obj+'"';
		return String(obj);
	}
	else {
		// recurse array or object
		var n, v, json = [], arr = (obj && obj.constructor == Array);
		for (n in obj) {
			v = obj[n]; t = typeof(v);
			if (t == "string") v = '"'+v+'"';
			else if (t == "object" && v !== null) v = JSON.stringify(v);
			json.push((arr ? "" : '"' + n + '":') + String(v));
		}
		return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
	}
};
//implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
	if (str === "") str = '""';
	eval("var p=" + str + ";");
	return p;
};

/* 
 * Log an initial page load where the content search id needs to be created before
 * other logging can take place.
 * @argument type The log type
 * @argument data The log data object
 */
function vp_logContentLoad(type, data) {
	// Log content search if search id is not set and results or bpp page
	if ((g_searchId == 0) && ((g_page == "results") || (g_page == "bpp"))) {
		if (!vp_logContentSearch()) return false;
	}

	// Log site visit
	vp_logSiteVisit();
	
	// Log site activities
	vp_logActivities(type, data);
}

/* 
 * Log a site visit.
 */ 
function vp_logSiteVisit() {
	
    var protocol = "http://";
    if (g_omniPage == "checkout" || g_omniPage == "confirmation"){
    	protocol = "https://";
    }
	//var URL = g_context + '/svc/log/visit';
    var URL = protocol + location.host + '/coupons' + '/svc/log/visit';

	$.ajax({
		url: URL,
		dataType: "json",
		cache: false,
		success: function(data) {
			var chkStatus = data.status;
			
			if (chkStatus != "ok") {
				return false;
			}
		}
	});
}

/* 
 * Log a content search.
 */ 
function vp_logContentSearch() {
	g_ajaxErrors = false;
	var URL = g_context + '/svc/log/contentSearch';
	$.ajax({
		url: URL,
		dataType: "json",
		async: false,
		cache: false,
		success: function(data) {
			var chkStatus = data.status;
			var content = data.content;
			
			if (chkStatus == "ok") {
				if (content) {
					g_searchId = content;
			    } else {
					g_searchId = 0;
				}
			}
			else {
				return false;
			}
		}
	});
	
	if (g_ajaxErrors) {
		g_ajaxErrors = false; // Reset for subsequent calls
		return false;
	}
	return true;
}

/*
 * Log content print.
 */
function vp_logContentPrint(printTypeId, pageName, zoneMapId, slugId) {
    var contentZoneId = vp_getContentZoneId(pageName);
    var logData = {zmId:zoneMapId, czId:contentZoneId, ptId:printTypeId};
    vp_logActivity(g_LOG_CONTENT_PRINT, logData);
    
	// Omniture log print click
    if (printTypeId == "N") {
    	vp_omniLogClick("event17", "Print Now", "c;" + slugId);
    }
    else if (printTypeId == "P") {
    	vp_omniLogClick("event19", "Print Company Info");
    }
    else if (printTypeId == "E") {
    	// Envelope print click
    	vp_omniLogClick("event17,event29", "Print Envelope", "c;" + slugId);
    }
}

/*
 * Log print list add.
 */
function vp_logPrintListAdd(pageName, zoneMapId, slugId) {
    var contentZoneId = vp_getContentZoneId(pageName);
    var logData = {czId:contentZoneId, zmId:zoneMapId};
    vp_logActivity(g_LOG_PRINTLIST_ADD, logData);

	// Omniture log print list add click
	vp_omniLogClick("scAdd", "Add to Print List", "c;" + slugId);
}

/* 
 * Log user activity
 * @argument type The log type
 * @argument data The log data object
 */
function vp_logActivity(type, data) {
	// Log with search id if available
	var searchId = '0';
    if (g_searchId != 0) {
    	searchId = g_searchId;
    }
    
    
    var protocol = "http://";
    if (g_omniPage == "checkout" || g_omniPage == "confirmation"){
    	protocol = "https://";
    }
    //var URL = g_context + '/svc/log/activity';
    var URL = protocol + location.host + '/coupons' + '/svc/log/activity';
    
    //alert("appName=" + navigator.appName);
    //alert("appCodeName=" + navigator.appCodeName);

    if ($.browser.msie || $.browser.mozilla){
    	$.ajax({
    		url: URL,
    		dataType: "json",
    		data: "logType=" + type + "&searchId=" + searchId + "&logData=" + JSON.stringify(data),
    		async: true,
    		cache: false,
    		type: "POST",
    		success: function(data) {
    			var chkStatus = data.status;
    			
    			if (chkStatus != "ok") {
    				return false;
    			}
    		}
    	});
    } else {
    	$.ajax({
    		url: URL,
    		dataType: "json",
    		data: "logType=" + type + "&searchId=" + searchId + "&logData=" + JSON.stringify(data),
    		async: false, // To work with Safari browser.
    		cache: false,
    		type: "POST",
    		success: function(data) {
    			var chkStatus = data.status;
    			
    			if (chkStatus != "ok") {
    				return false;
    			}
    		}
    	});

    }
}

/* 
 * Log user activity
 * @argument type The log type
 * @argument data The log data object
 */
function vp_logActivities(type, data) {
	// Log with search id if available
	var searchId = '0';
    if (g_searchId != 0) {
    	searchId = g_searchId;
    }
    
    //alert(g_omniPage);
    
    var protocol = "http://";
    if (g_omniPage == "checkout" || g_omniPage == "confirmation"){
    	protocol = "https://";
    }

    //alert("protocol=" + protocol);
    //alert("location.host=" + location.host);
    //alert("g_context=" + g_context);
    
    var URL = protocol + location.host + '/coupons' + '/svc/log/activities';
    
    //alert(URL);
    
	$.ajax({
		url: URL,
		dataType: "json",
		data: "logType=" + type + "&searchId=" + searchId + "&logData=" + JSON.stringify(data),
		cache: false,
		type: "POST",
		success: function(data) {
			var chkStatus = data.status;
			
			if (chkStatus != "ok") {
				return false;
			}
		}
	});
}

/* 
 * Log link clicks
 * @argument featureType The log feature type
 * @argument zoneMapId The zone map id from the slug containing the link
 * @argument contentZoneId The content zone id of the link
 * @argument couponSlugId The id of the slug containing the link (optional)
 */
function vp_logLinkClick(featureType, zoneMapId, pageName, couponSlugId){
	/*
	alert("featureType=" + featureType
    		+ " zoneMapId=" + zoneMapId
    		+ " pageName=" + pageName
    		+ " couponSlugId=" + couponSlugId);
	*/
	
	// Activity Log website
    var contentZoneId = vp_getContentZoneId(pageName);

    var linkClickLog = {zmId:zoneMapId, czId:contentZoneId, ftId:featureType};
    
    vp_logActivity(g_LOG_LINK_CLICK, linkClickLog);
}

/* 
 * Omniture clear variables
 * @argument type The type of Omniture call - page or click
 */ 
function vp_omniClear(type) {
	s.events="";
    
	//s.pageName="";
    s.channel="";
    s.server="";
    s.pageType="";
    s.referrer="";
    s.campaign="";
    s.products="";
    s.purchaseID="";
    s.transactionID="";
    s.hier1="";
    s.zip="";
    
    s.prop2="";
    s.prop6="";
    s.prop7="";
    s.prop8="";
    s.prop10="";
    s.prop11="";
    s.prop14="";
    //s.prop15="";
    //s.prop16="";
    s.prop18="";
    //s.prop19="";
    s.prop20="";
    s.prop21="";
    //s.prop22="";
    s.prop25="";
    s.prop26="";
    s.prop27="";
    s.prop28="";
    s.prop29="";
    s.prop30="";
    s.prop31="";
    s.prop32="";
    s.prop33="";
    s.prop34="";
    s.prop35="";
    s.prop36="";
    //s.prop37="";
    s.prop38="";
    s.prop39="";
    s.prop40="";
    s.prop41="";
    s.prop42="";
    s.prop43="";
    s.prop44="";
    s.prop45="";
    s.prop46="";
    s.prop47="";
    s.prop48="";
    s.prop49="";
    s.prop50="";
    s.prop51="";
    s.prop52="";
    s.prop53="";
    s.prop54="";
    s.prop55="";
    
    s.eVar2="";
    s.eVar3="";
    s.eVar4="";
    //s.eVar5="";
    s.eVar6="";
    s.eVar7="";
    s.eVar8="";
    //s.eVar11="";
    s.eVar13="";
    s.eVar14="";
    s.eVar15="";
    //s.eVar19="";
    s.eVar23="";
    s.eVar24="";
    s.eVar25="";
    s.eVar26="";
    s.eVar27="";
    s.eVar28="";
    s.eVar29="";
    s.eVar31="";
    s.eVar32="";
    s.eVar33="";
    s.eVar34="";
    s.eVar35="";
    s.eVar36="";
    //s.eVar37="";
    s.eVar38="";
    s.eVar39="";
    s.eVar40="";
    s.eVar41="";
    s.eVar42="";
    s.eVar43="";
    s.eVar44="";
    s.eVar45="";
    //s.eVar46="";
    s.eVar47="";
    s.eVar48="";
    s.eVar49="";
    s.eVar50="";
    s.eVar51="";
    s.eVar52="";
    s.eVar53="";
    s.eVar54="";
    //s.eVar55="";
    s.eVar56="";
    s.eVar57="";
    s.eVar58="";
    s.eVar59="";
    s.eVar60="";
    s.eVar61="";
}

/* 
 * Log a standard Omniture link click
 * @argument event The click event
 * @argument name The name of the link or null
 * @argument products The complete products string variable contents
 * @argument zone The content zone id of the link, the page name or null
 * @argument feature The feature type of the link or null
 * @argument vars Object containing props and eVars to modify (optional)
 */
function vp_omniLogClick(event, name, products, zone, feature, vars) {
	// Note: zone and feature are not used anymore
    vp_omniClear("click");
    s.events = (event) ? event : "";

    if (products) {
        s.products = products;
    }
    
    // Not used globally anymore - set only where needed
    //	I.E. Billboard click areas
    //if (zone) {
    //    s.eVar23 = vp_getContentZoneId(zone);
    //}
    
    // Add/modify the s object with passed in values
    if (vars) {
        $.extend(s, vars);
    }
    
    name = (name) ? name : "";
    s.tl(this, "o", name);
}

/* 
 * Log an Omniture page view
 * @argument name The name of the page or null
 * @argument vars Object containing props and eVars to modify (optional)
 */
function vp_omniLogPage(name, vars) {
    vp_omniClear("page");
    
    if (name) {
        s.pageName = name;
    }
    
    // Add/modify the s object with passed in name:value pairs
    if (vars) {
        $.extend(s, vars);
    }

    s.t();
}

function vp_getContentZoneId(pageName) {
	var strPageName = pageName.toString();
    var contentZoneId;
    if (pageName == "results") {contentZoneId = 57;}
    else if (strPageName.lastIndexOf("ls", 0) == 0) {contentZoneId = 57;}
    else if (strPageName.lastIndexOf("lc", 0) == 0) {contentZoneId = 57;}
    else if (strPageName.lastIndexOf("ld", 0) == 0) {contentZoneId = 57;}
    else if (strPageName.lastIndexOf("os", 0) == 0) {contentZoneId = 57;}
    else if (strPageName.lastIndexOf("gr", 0) == 0) {contentZoneId = 57;}
    else if (strPageName.lastIndexOf("kw", 0) == 0) {contentZoneId = 57;}
    else if (strPageName.lastIndexOf("vd", 0) == 0) {contentZoneId = 63;}
    else if (pageName == "bpp" || pageName == "bppPagePrint") {contentZoneId = 60;}
    else if (pageName == "printList") {contentZoneId = 61;}
    else if (pageName == "deals") {contentZoneId = 63;}
    else if (pageName == "dealCheckout") {contentZoneId = 63;}
    else if (pageName == "dealVoucher") {contentZoneId = 65;}
    else if (pageName == "dealConfirmation") {contentZoneId = 66;}
    else if (pageName == "dealPurchaseSteps") {contentZoneId = 71;}
    else if (pageName == "profile" || pageName == "signup" || pageName == "signin") {contentZoneId = 67;}
    else if (pageName == "keywordResults" || pageName == "results" || pageName == "couponResults" || pageName == "dealResults" || pageName == "groceryResults" || pageName == "onlineResults") {contentZoneId = 57;}
    //else if (pageName == "printConf") {contentZoneId = 34;}
    else {contentZoneId = pageName;}

    return contentZoneId;
}

/** Log video states for Martha Stewart (288)
 *  This function is called by the Martha Flash program to log
 *  how the user play the instant win game.
 *  
 * @param status - The video status.  Either 'play' or 'stop'
 * @param value - The video number.  For example, 1 = video #1
 * and 2 = video #2.
 * @return nothing.
 */
function vp_videoPlay(status, value) {
	// TODO - Make function more generic for other contests/videos
	// Convert the video status to all lower case.
	if (status != null){
		// Convert activity name to lower case.
		status = status.toLowerCase();
		
		// Convert the video number to match with the activity types
		// defined in the VPLogConstants.java
		var activity = 0;
		if (value == 1) {
			activity = 4; // Video 1.
		} else if (value == 2){
			activity = 5; // Video 2.
		}

		if (activity != 0){
			// Log video activity.
			if (status == 'play'){
				vp_logContestActivity(activity, 1); // Play video
			} else if (status == 'stop'){
				vp_logContestActivity(activity, 0); // Stop video
			}
		}
	}
}

/** Log contest actions
 *  This function is called by the Martha Flash program to log
 *  how the user play the instant win game.
 *
 *  @param activity - The user's activity such as webcam, print symbol, etc.
 *  The contest activities are defined in the VPLogConstants.java
 *  These constants are defined here for convenience but should refer
 *  the VPLogConstants.java for the latest values.
 *  
 *   // Contest Activity Types
 *   public static final int CONTEST_ACTIVITY_WEBCAM   				= 1;
 *   public static final int CONTEST_ACTIVITY_PRINT_SYMBOL			= 2;
 *   public static final int CONTEST_ACTIVITY_INSTANT_GAME			= 3;
 *   public static final int CONTEST_ACTIVITY_VIDEO_1				= 4;
 *   public static final int CONTEST_ACTIVITY_VIDEO_2				= 5;
 *   
 *   
 *  @param value - The value input parameter is either 1 or 0.  1 = true/yes/start 
 *  and 0 = false/no/stop.
 *  @return nothing
 *  
 */
function vp_logContestActivity(activity, value) {
	// TODO - Make function more generic for other contests/videos
	if (activity > 0) {
		// Log user's activities for playing the contest.
		
		var URL = g_context + '/svc/log/contestActivity';
		$.ajax({
			url: URL,
			dataType: "json",
			data: "contestId=288&activityType=" + activity + "&activityValue=" + value,
			cache: false,
			success: function(data) {
				var chkStatus = data.status;
				var content = data.content;
				
				if (chkStatus != "ok") {
					return false;
				}
			}
		});
	}
}

/* 
 * Log a Gaming action
 */ 
function vp_logGamingAction(action) {
	
    var protocol = "http://";
    if (g_omniPage == "checkout" || g_omniPage == "confirmation"){
    	protocol = "https://";
    }
	//var URL = g_context + '/svc/log/visit';
    var URL = protocol + location.host + '/coupons' + '/svc/log/gaming/action';
    
	$.ajax({
		url: URL,
		dataType: "json",
		data: "action=" + action,
		cache: false,
		type: "GET",
		success: function(data) {
			var chkStatus = data.status;
			
			if (chkStatus != "ok") {
				return false;
			}
		}
	});
}


