// jquery
// hearst session script

var ra_raws = {
	variables : {
		member_id : null,
		cal_age : "?",
		cal_diff : "+/-",
		real_age : "??",
		news : null,
		goals : null,
		isActive : null,
		personalpod_data : null,
		child_id : "0",
		debugAlerts: 0
	},
	
	rpc : {
		getPersonalPodData : function(child_id){			
			var newproc = function(json){
				ra_raws.variables.personalpod_data = json.result;
				if (ra_raws.variables.personalpod_data.real_age != null){
					ra_raws.variables.real_age = parseFloat(ra_raws.variables.personalpod_data.real_age).toFixed(1);
					ra_raws.variables.cal_age = parseFloat(ra_raws.variables.personalpod_data.current_age).toFixed(1);
					// get cal_diff string
					var cal_diff = parseFloat(ra_raws.variables.real_age - ra_raws.variables.cal_age).toFixed(1);
					if (cal_diff > 0){
						cal_diff = "+"+cal_diff;
					}
					ra_raws.variables.isActive = true;
					ra_raws.variables.cal_diff = cal_diff;
				} else {
					ra_raws.variables.cal_age = ra_raws.variables.personalpod_data.current_age;
					ra_raws.variables.isActive = false;
				}
				ra_raws.variables.goals = ra_raws.variables.personalpod_data.goals;
				if (debugAlerts != 0){
					ra_raws.rpc.getRecommendationsOverview(child_id);
				}
			}
			var errproc = function(json){
			}
			ra_raws.call('{"jsonrpc": "2.0", "method": "getPersonalPodData", "params": ["'+child_id+'"], "id": 1}',newproc,errproc);
		},
		getUrlParam : function(name){
			var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
			if (!results) { return 0; }
			return results[1] || 0;
		},
		getRecommendationsOverview : function(child_id){
			var url = "http://raap.realage.com/data/json?callback=?";
			var data = {"method": "getRecommendationsOverview", "params": JSON.stringify({ "child_id" : child_id, "assessment_id" : 108267 }), "id": 1 };
			if (debugAlerts != 0) {
				$.ajax({
					url: url,
					dataType: 'json',
					timeout: 90,
					data: data,
					error: function(a, b, c) {
						alert("Text Status: " + b + "\nError Thrown: " + c);
					},
					success: function(j) {
						j = $.parseJSON(j);
						$.each(j.result, function(i,item) {
							j.result[i] = item;
						});
						ra_raws.variables.news = j.result;
					}
				});
			}
			if (ra_raws.variables.news == null) {
				ra_raws.variables.news = [{"cost_benefit": "cost","page": "112648","overview_teaser": "Failed Retrieval","rec_id": "112658"},{"cost_benefit": "benefit","page": "112648","overview_teaser": "Failed Retrieval","rec_id": "112682"},{"cost_benefit": "cost","page": "112648","overview_teaser": "Failed Retrieval","rec_id": "112686"}];
			}
		},
		getNews : function(interest_ids,callback,errorCallback){
			// NOTE: interest_ids can be an array
			var newproc,errproc;
			if (!!!callback){
				newproc = function(json){
					ra_raws.variables.news = json.result;
				}
			} else {
				newproc = callback;
			}
			if (!!!errorCallback){
				errproc = function(json){
				}
			} else {
				errproc = errorCallback;
			}
			if (interest_ids == null){
				ra_raws.callNews(interest_ids,'{"jsonrpc": "2.0", "method": "getNews", "params": [], "id": 1}',newproc,errprocc);
			} else {
				ra_raws.callNews(interest_ids,newproc,errproc);
			}
		}
	},
	call : function(data,proc,err){
		var success = function(json){
				if (json.hasOwnProperty("error")) {
					console.error("JSON RPI ERROR["+json.error.code+"] "+json.error.message);
					err(json);
				} else if (json.hasOwnProperty("result")) {
					proc(json);
				} else {
					console.error("UNKNOWN RESULT");
				}
		}
		var testobj = {
			"url": "/raws2/",
			"dataType": "json",
			"type": "POST",
			"data": data,
			"contentType": "application/json",
			"success": success
		}
		jQuery.ajax(testobj);	
	},
	callNews : function(ids,proc,err){
		var success = function(json){
				if (json.hasOwnProperty("error")) {
					console.error("JSON RPI ERROR["+json.error.code+"] "+json.error.message);
					err(json);
				} else if (json.hasOwnProperty("result")) {
					proc(json);
				} else {
					console.error("UNKNOWN RESULT");
				}
		}
		var testobj = {
			"url": "http://services.hearstmags.com/api/js/RealAge/news_" + ids,
			"dataType": "json",
			"type": "POST",
			"contentType": "application/json",
			"success": success
		}
		jQuery.ajax(testobj);	
	}
}


var ra_personalpod = {
	set_active : function(){
		var displayemail = "";
		if (mag_user.email.length > 23){
		 displayemail = mag_user.email.substr(0,23)+"...";
		} else {
		 displayemail = mag_user.email +"!";
		}
		$("#rr_personal_pod_hdr").css({"height":"133px"});
		$("[pod_field='first_name']").html("Hi, "+displayemail);
		$(".rr_personal_plan_header_l").hide();
		$(".rr_personal_plan_header_2").hide();
		$(".rr_personal_plan_whatsmyrealage").show();
		$("[pod_field='my_plan'] > .rr_pp_std_cont_active").show();
		$("[pod_field='my_plan'] > .rr_pp_std_cont_inactive").hide();
		$("[pod_field='my_plan']").show();
		$("[pod_field='my_recipebox']").show();
		$("#rr_personal_pod").show();
	},
	set_inactive : function(){
		var displayemail = "";
		if (mag_user.email.length > 23){
		 displayemail = mag_user.email.substr(0,23)+"...";
		} else {
		 displayemail = mag_user.email +"!";
		}		
		$("#rr_personal_pod_hdr").css({"height":"133px"});
		$("[pod_field='first_name']").html("Hi, "+displayemail);
		$(".rr_personal_plan_header_l").show();
		$(".rr_personal_plan_header_2").hide();
		$(".rr_personal_plan_whatsmyrealage").show();
		$("[pod_field='my_plan'] > .rr_pp_std_cont_inactive").show();
		$("[pod_field='my_plan'] > .rr_pp_std_cont_active").hide();
		$("[pod_field='my_plan']").show();
		$("[pod_field='my_recipebox']").show();
		$("#rr_personal_pod").show();
	},
	set_notsignedin : function(){
		$("[pod_field='first_name']").html("<a class=\"pp_link_arrow\" href=\"http://www.realage.com/reg/regvar/st1.aspx?mod=LONGFORM\">Take the RealAge Test</a>");
		$(".rr_personal_plan_header_l").hide();
		$(".rr_personal_plan_header_2").show();
		$(".rr_personal_plan_whatsmyrealage").hide();
		$("[pod_field='my_plan']").hide();
		$("[pod_field='my_goals']").hide();
		$("[pod_field='my_recipebox']").hide();
		$("#rr_personal_pod_hdr").css({"height":"38px"});
		$("#rr_personal_pod").show();
	},
	listener : {
		email : null,
		isActive : null,
		personalPodData : null,
		hasGoals : false
	},
	init : function(){
		debugAlerts = ra_raws.rpc.getUrlParam("debugGR");
		child_id = readCookie("raap_child_id");
		ra_raws.rpc.getPersonalPodData(child_id);
		//We aren't putting recs in the pod for now, so no point in trying to get them here. -- KL 2010-12-01
		//ra_raws.rpc.getRecommendationsOverview(child_id);
		ra_personalpod.set_inactive();
		ra_personalpod.listener.isActive = setInterval(function(){
			if(ra_raws.variables.isActive != null){
				$("[pod_field='cal_age']").html(ra_raws.variables.cal_age);
				if (ra_raws.variables.isActive == false){
					ra_personalpod.set_inactive();
				} else {
					ra_personalpod.set_active();
				}
				window.clearInterval(ra_personalpod.listener.isActive);
			}
		},500);
		ra_personalpod.listener.personalPodData = setInterval(function(){
			if(!!ra_raws.variables.personalpod_data){
				window.clearInterval(ra_personalpod.listener.personalPodData);
				$("[pod_field='cal_age']").html(ra_raws.variables.cal_age);
				$("[pod_field='cal_diff']").html(ra_raws.variables.cal_diff);
				$("[pod_field='cal_realage']").html(ra_raws.variables.real_age);
				$(".rr_personal_plan_whatsmyrealage").show();
				var newsArray = {};
				newsArray[1] = "Walk Your Way Fit";
				newsArray[2] = "Get Younger Skin in 9 Days";
				newsArray[3] = "Lose a Few Pounds";
				newsArray[4] = "Lose a Lot -- Even 100+ Pounds";
				newsArray[5] = "Lose 10 to 50 Pounds";
				newsArray[6] = "Feel Younger in 14 Days";
				newsArray[7] = "Stop Smoking -- For Real";
				newsArray[8] = "Flatten Your Belly with Dr. Oz's Trainer";
				newsArray[9] = "Grow Younger in 60 Days";
				var myhtml = "";
				for (var i in ra_raws.variables.goals) {
					myhtml += "<li><a href=\"http://www.realage.com/my-goals/"+ra_raws.variables.goals[i].goal_name+"\">"+newsArray[ra_raws.variables.goals[i].goal_id]+"</a></li>";
				}
				$("[pod_field='goal_list']").html(myhtml);
				myhtml = "";
				var goalslength = (ra_raws.variables.news.length > 3) ? 2 : ra_raws.variables.news.length;
				for (var i = 0; i < goalslength; i++) {
					myhtml += "<li><a href=\"http://www.realage.com/realage-recs?recpage_id="+ra_raws.variables.news[i].page+"\">"+ra_raws.variables.news[i].overview_teaser+"</a></li>";
				}
				$("[pod_field='my_plan_ul']").html(myhtml);
				if (ra_raws.variables.goals.length > 0){
					$("[pod_field='my_goals'] > .rr_pp_std_cont_active").show();
					$("[pod_field='my_goals'] > .rr_pp_std_cont_inactive").hide()
					$("[pod_field='my_goals']").show();
				} else {
					$("[pod_field='my_goals'] > .rr_pp_std_cont_inactive").show();
					$("[pod_field='my_goals'] > .rr_pp_std_cont_active").hide()
					$("[pod_field='my_goals']").show();
				}
			}
		},500);
	}
}

ra_newsfromtheweb = {
	list : new Array(),
	drawNews : function(){
		$h.console.log("RAWS: calling getNews("+ra_newsfromtheweb.list+")");
		//ra_raws.rpc.getNews(ra_newsfromtheweb.list.join("_"),ra_newsfromtheweb.newsCallback);
		var ids = ra_newsfromtheweb.list.join("_");
		var url = "/api/js/RealAge/news_" + ids;   		
		$.ajax({
			url:  url,
			dataType: 'json',
			type: "GET",
			success: function(j) {
				$.each(j, function(i,item) {
					j[i] = item;
				});
				ra_raws.variables.news = j;
				var myhtml = "";
				for (i in j){
					myhtml += "<li><a href=\""+j[i].url+"\" target=\"_blank\">"+j[i].title+"</a></li>";
				}
				$("[news_field='ul']").html(myhtml);
			}
		});
	},
	newsCallback : function(json){
		$h.console.log("RAWS: getNews() returned: "+json.result);
		var myhtml = "";
		for (i in json.result){
			myhtml += "<li><a href=\""+json.result[i].url+"\" target=\"_blank\">"+json.result[i].title+"</a></li>";
		}
		$("[news_field='ul']").html(myhtml);
	}
}

