/*
 * 
 * Write test variation data to DB for revenue tracking later
 * 
 * Requires: jQuery, jqURL
 * Code is meant to integrate with Omniture's Test&Target
 * 
 */

TestAndTarget = {
	
	logged : false,

	mboxQueue : new Array(),

	mboxCount : 0,

	isAjax : false,
	
	userSessionInfo : null,

	getIsAjax : function(){return this.isAjax;},
	setIsAjax : function(is_ajax){this.isAjax = is_ajax;},
	
	getUserSessionInfo : function(){return this.userSessionInfo;},
	setUserSessionInfo : function(userSessionInfo)
	{
		var tempAr = new Array();
		
		for (i in userSessionInfo) 
		{
			if(userSessionInfo[i])
			{
				tempAr.push("'"+i+"="+userSessionInfo[i]+"'");
			}
		}
		
		this.userSessionInfo = tempAr.join(',');
	},
	
	getAjaxServer : function()
	{
		if(typeof ajax_server == 'undefined')
		{
			var ajax_host = (("https:" == document.location.protocol) ? "https://" : "http://");
			ajax_server = ajax_host + 'ajax.allwebleads.com';
		}

		return ajax_server;
	},
	
	checkIsIE : function()
	{
		if (navigator.appVersion.indexOf("MSIE") != -1)
		{
			return true;
		}
		
		return false;
	},
	
	mboxCreate : function(args)
	{	
		if( TargusAdAdvisor.getIsLoaded() == true /*|| this.checkIsIE()*/)
		{
			this.setIsAjax(false);
			
			if(typeof console != 'undefined')
			{
				console.log('early mbox, targus is loaded already');
			}
			
			//apend cookie data to mbox create			
			var tArgs = mboxShiftArray(args);			
            
            var reg = new RegExp("'", 'g');  
            // get user session params
            var params = this.getUserSessionInfo().replace(reg,'').split(',');
            // get Targus params
			if(TargusAdAdvisor.getCookie())
			{				
				var targusCookieParams = TargusAdAdvisor.getCookieParams().replace(reg,'').split(',');                
                var params = $.merge(targusCookieParams,params);
			}

            for(i in params)
            {
                tArgs.push(params[i]);
            }
			
			//create mbox			
			var X = mboxFactoryDefault.create(args[0], tArgs);
			
		 	if (X)
		 	{
		 		X.load();
		 	}
		 	
		 	return X;
		}
		else
		{		
			this.setIsAjax(true);
			
			var mbox = args[0];
			var tArgs = mboxShiftArray(args);
			
			this.mboxCount += 1;
			
			this.mboxQueue.push([mbox,tArgs,this.mboxCount]);
		}
	},
	
	mboxUpdate : function(args)
	{
		this.setIsAjax(true);
		mboxFactoryDefault.update(args[0], mboxShiftArray(args));
	},
	
	log : function(t)
	{		
		if(this.logged == true) return;

		var ajax_server = this.getAjaxServer();
		
		var connection_url = ajax_server + '/1.0/TestAndTarget/php/test-and-target.php';
		
		var sUrl = $.jqURL.url();
		
		var test_and_target_array = new Array();
		
		var validData = true;
		
		/*** SET ARRAY of TEST AND TARGET VARIABLES ***/
		
		if(typeof sSessionId != 'undefined')
		{
			test_and_target_array['session_id'] = sSessionId;
		} else { validData = false; }
		
		if(typeof sUserSessionId != 'undefined')
		{
			test_and_target_array['user_session_id'] = sUserSessionId;
		} else { validData = false; }
		
		if(typeof t.sCampaignName != 'undefined')
		{
			test_and_target_array['campaign_name'] = t.sCampaignName;
		} else { validData = false; }
		
		if(typeof t.sCampaignId != 'undefined')
		{
			test_and_target_array['campaign_id'] = t.sCampaignId;
		} else { validData = false; }

		if(typeof t.sRecipeName != 'undefined')
		{
			test_and_target_array['recipe_name'] = t.sRecipeName;
		} else { validData = false; }
		
		if(typeof sUrl != 'undefined')
		{
			test_and_target_array['url'] = sUrl;
		} else { validData = false; }
		
		if(typeof t.sVisitorId != 'undefined')
		{
			test_and_target_array['vistor_id'] = t.sVisitorId;
		} else { validData = false; }
		
		if(typeof t.sTestAndTargetUserSessionId != 'undefined')
		{
			test_and_target_array['test_and_target_user_session'] = t.sTestAndTargetUserSessionId;
		}else { validData = false; }
		
		if(typeof t.sIsFirstSession != 'undefined')
		{
			test_and_target_array['is_first_session'] = t.sIsFirstSession;
		} else { validData = false; }
		
		test_and_target_array['action'] = 'log';
		
		if(validData == true)
		{
			//this.logged = true;

			$.jsonp({			
				url: connection_url + '?' + this.buildUrlString(test_and_target_array),
				dataType: 'jsonp',
				//data: test_and_target_array,
				callbackParameter: "jsoncallback",
				error : function(req,status,e){			
					
					switch(status)
					{
						case 'timeout':
							if(typeof console != 'undefined')
							{
								//console.log('mbox timeout');
							}
							break;
						default:
							break;		
					}
					
					if(typeof console != 'undefined')
					{					
						//console.log('error: ' + status);
					}
				},
				success : function(data,status,req){
					if(typeof console != 'undefined')
					{
						console.log(data);
					}
				},
				timeout: 3000
			});	
			
		}
		
		return true;
		
	},
	
	buildUrlString : function(arr)
	{
		var str = '';
		for ( key in arr ) {
			if(str != '')
			{
				str += '&';
			}
			str += key + '=' + arr[key];
		}
		return str;
	}
	
};

