var container;
var errorDiv;
var survey;
var showContent = true;
var hasTaken;
var matchUsers;
var surveyURL;
var approved;
var osContainer;
var surveyImgUrl;
var PAGE=0;
var allFriends = []; 
var SURVEY_QUESTIONS = null;
var SURVEY = null;
var OWNER_ANSWER;
var showOwnerAnswer = false;
var totalLikeMe = null;
var msgCount = null;
var LIKEME_USER_COUNT = 20;
var HAS_PROFILE_INFO;
var firstAnswer = true;
var totalTakenCount = 0;
var IS_SHARED = true;
var myResults;
var InvitationSubject = "";
var InvitationContent = "";
var friendsToInvite = [];
var ADMIN_USER = 330343129;
//var ADMIN_USER = 4694439;
var ADS_DATA = {};
var score;
var totalPoints;
var flag = true;
var IS_CORRECT = 1;
var first_time = 0;
var TAKEN_SURVEYS = 1;
var CREATED_SURVEYS = 2;
var allowNotExactMatch = true;
var AD_SURVEYS = [
					  {url: MAKER_URL,
					   imgUrl: "logo.gif",
					   title: "Make a Survey"
					   }
					 ];

var init = function(){

	req_getLastTest();
	req_getAdsData();
	req_getRightBar();
	
	req_channel_statistics("canvas");
	
//	inviteMessage = opensocial.newMessage("Let's play [app]. I want to compare our results.");
}

var req_getRightBar = function(){
	Request.sendGET(SERVICE_URL+"/surveys_rb", resp_getRightBar);
	req_getRecentlyTaken();
	setInterval(req_getRecentlyTaken, 20000);
}

var req_getAdsData = function(){
	Request.sendGET(SERVICE_URL+"/ad", resp_getAdsData);
}

var req_getLastTest = function(){
	Request.sendGET(SERVICE_URL+"/lastTest/"+userId,resp_getLastTest);
}

var resp_getLastTest = function(response){
	var data = response.data;
	surveyId = data.id;
	req_getSurvey();
	//takeThisTest(surveyId);
}

var timesRefreshed = 0;

var req_getRecentlyTaken = function(){
	if (timesRefreshed < 6){
		Request.sendGET(SERVICE_URL+"/getRecentlyTaken", resp_getRecentlyTaken);
		timesRefreshed++;
	}
}

var nextURL = null;
var nextURLs = [];

var resp_getRightBar = function(response){
	var data = response.data;
	$("popular_rb").innerHTML = getRightBarSurveysHTML(data.popular);
	$("recent_rb").innerHTML = getRightBarSurveysHTML(data.recent);
	$("today_rb").innerHTML = getRightBarSurveysHTML(data.today);
	gadgets.window.adjustHeight();
}

var resp_getAdsData = function(response){
	var data = response.data;
	ADS_DATA = data.ads;
	if (ADS_DATA == null) ADS_DATA = [];
	AD_SURVEYS = AD_SURVEYS.concat(data.surveys);
}

var resp_getRecentlyTaken = function(response){
	var str = "";
	var data = response.data.recently.users;
	var obj;
	for(var i=0;i<data.length && i<10;i++){
		obj = data[i];
		str +="<table><tr>"+
					"<td width='30px'><img width=25px height=25px src='"+obj.user.thumbnail+"' /></td>"+
					"<td><a href='javascript:takeThisTest("+obj.id+")' >"+obj.title+"</a></td>"+
					"<tr><td colspan=2><div title='"+obj.user.name+"' style='width:200px;overflow:hidden><a style='font-weight:normal' href='"+obj.user.profile+"'>"+obj.user.name+"</a></div></td></tr>"+
			  "</tr></table>";
		nextURLs[nextURLs.length] = obj.url;
	}
	$("just_taken_rb").innerHTML = str;
}


var getRightBarSurveysHTML = function(surveys){
	var str = "";
	var srv;
	for(var i=0;i<surveys.length;i++){
		srv = surveys[i];
		str +="<table><tr>"+
					"<td><img width=25px height=25px src='"+SURVEY_IMG_URL+srv.imgUrl+"' /></td>"+
					"<td><a href='#' onclick='javascript:takeThisTest("+srv.surveyId+")' >"+srv.title+"</a></td>"+
			  "</tr></table>";
		nextURLs[nextURLs.length] = srv.url; 	  
	}
	return str;
}

var takeThisTest = function(testId){
	surveyId = testId;
	req_getSurvey();
	takeSurvey(SURVEY_QUESTIONS, SURVEY, HAS_PROFILE_INFO);
}

var req_getSurvey = function(){
	if (ownerId && ownerId != userId){
		Request.sendGET(SERVICE_URL+"/survey/"+userId+"/"+surveyId+"/"+ownerId, resp_getSurvey);
	} else {
		Request.sendGET(SERVICE_URL+"/survey/"+userId+"/"+surveyId, resp_getSurvey);
	}
}

var logError = function(){
	container.innerHTML = "<center><h1>Error occured while loading data. Try again in a few minutes.</h1></center>";
}

var resp_getSurvey = function(response){
	if (response.errorCode){
		logError();
		return;
	}
	if (response.error){
		hideTabs("User authorization failed. Check if you are logged in and refresh the page.");
		return;
	}
	var json = response.data;
	hasTaken = json.hasTaken;
	HAS_PROFILE_INFO = json.hasProfileInfo;
	SURVEY = json.data.survey;
	SURVEY_QUESTIONS = json.data.questions;
	try{
		OWNER_ANSWER = json.ownerAnswer.answerStr;
		showOwnerAnswer = OWNER_ANSWER && json.ownerAnswer.shared;
	}catch(e){}
	surveyURL = SURVEY.url;
	
	if(SURVEY.imgUrl != ""){
		surveyImgUrl = SURVEY_IMG_URL+SURVEY.imgUrl;
		}
	else{
		surveyImgUrl = SURVEY_IMG_URL+"noimage.jpg";
	}	
	approved = SURVEY.status != 0;
	IS_SHARED = json.data.shared;
	if (showContent || json.showContent){
		if (json.hasTaken){
			$("take_survey").style.display = "none";
			selectTab("results");
			//req_getMsgCount();
			var questions = json.data.questions;
			totalTakenCount = questions[0].totalAnswers;
			req_likeMeFirst();
			showResults(questions);
		}else{
			selectTab("take");
			$("srvResults").style.display = "none";
//			$("srvCompare").style.display = "none";
			takeSurvey(SURVEY_QUESTIONS, SURVEY, HAS_PROFILE_INFO);
		}
	}else{
		selectTab("take_survey");
		$("srvResults").style.display = "none";
		$("srvCompare").style.display = "none";
		checkAge();
	}
	
	// $("adDiv1").innerHTML = getAd(1);
	//$("adDiv2").innerHTML = getAd(2);
}

var req_getMsgCount = function(){
	Request.sendGET(SERVICE_URL+"/userMsgCount/"+userId+"/"+surveyId, resp_getMsgCount);
}

var resp_getMsgCount = function(response){
	msgCount = response.data;
	if (totalLikeMe != null){
		showPostUnderLikeMe();
	}
}

var showPostUnderLikeMe = function(){
	var str = "<h1 class='postLikeMe'>"+totalLikeMe+" people are like you. You've got "+msgCount+" emoticons and gifts. <a href='javascript:postResults()'>Post to Your Bulletin</a> to get more!</h1>";
	str += "<h1 class='postLikeMe'><a href='javascript:postMyResults()'>Post Your Results</a></h1>";
	$("postUnderLikeMe").innerHTML = str;
}
var postNewSurvey = function(){
	var content = "We just got a new survey - <a href='"+surveyURL+"'>"+surveyTitle+"</a>. Enjoy and find more people aroud!";
	var title = "New survey added "+surveyTitle;
	postTo_(title, content, user, "BULLETINS");
}

var postMyResults = function(forwardToResultsPage){
	var content = "<a href='"+surveyURL+"'>"+surveyTitle+"</a>"+
				  "<br/><a href='"+surveyURL+"'><img src='"+surveyImgUrl+"' />"+surveyTitle+"</a><br/><br/>"+
				  "<br/><a href='"+surveyURL+"'>Take this survey</a>"+
				   myResults+
				  "<br/><br/><a href='"+surveyURL+"'>CLICK HERE TO TAKE THIS SURVEY</a>"+
				  "<br/><br/><a href='"+MAKER_URL+"'>More tests</a> | <a href='"+MAKER_URL+"'>Make survey</a>";
	postTo_(surveyTitle, content, user, "BULLETINS", forwardToResultsPage ? req_getResults : null);
}

var postResults = function(){
	var subject = surveyTitle;
	var content = "Come on, join me and play <a href='"+surveyURL+"'>"+surveyTitle+"</a>. "+
				  "I have got "+totalLikeMe+" people like me, "+msgCount+" emoticons and gifs from them."+
				  "<a style='float:left' href='"+surveyURL+"'><img src='"+surveyImgUrl+"' /></a>";
	postTo_(subject, content, user, "BULLETINS");
}

var checkAge = function(){
	container.innerHTML = "<div align=center>"+
							"<h1>Make sure you are older than 18.</h1>"+
							"<input type=button value='Yes, I am' onclick='allow()' />"+
							"<input style='margin-left:10px;' type=button value='No, I am not' onclick='preventUnder18()' />"+
						  "</div>";
}

var preventUnder18 = function(){
	var tabDivs = $("tabContainer").getElementsByTagName("td");	
	var name;
	for (var i=0;i<tabDivs.length;i++){
		name = tabDivs[i].getAttribute("name"); 
		if (name != "users" && name != "public" && name != "create"){
			tabDivs[i].style.display = "none";
		}
	}
	getPublicTrivias();
}

var allow = function(){
	showContent = true;
	req_getSurvey();
}

var likeMePage;

/////////////////////////////////////////// RESULTS ///////////////////////////////////////////
var inviteViaBulletin = function(showResultLink){
	selectTab("invite");
   	var str = "<center><h1 style='font-size:19px'>Invite Your Friends to have more fun!!!<br/>Post on your bulletin!!!</h1>"+
                          '<img src='+IMG_URL+'invite.png onclick="postInvite()"/></center>';
    if (showResultLink){
	    str += "<h1><a href='javascript:req_getResults()'>View results</a></h1>";
	}
    container.innerHTML = str;
    gadgets.window.adjustHeight();
}


var req_getResults = function(){
	selectTab("results");
	if (!hasTaken) {
		requireTakeSurvey();
		return;
	}
	if (!showContent){
		checkAge();
	}else{
		req_likeMeFirst();
		if (SURVEY_QUESTIONS == null){
			Request.sendGET(SERVICE_URL+"/results/"+userId+"/"+surveyId, resp_getResults);
			//req_getMsgCount();
		}else{
			showResults(SURVEY_QUESTIONS);
		}
	}
}
var smartPeople = function(){
	showError("");
	selectTab("smartPeople");
	showLoading();
	 var str =	"<div class=title>Best Today</div><div class=content id = 'besttoday'></div>"+
				"<div class=title>Absolute Best</div><div class=content id = 'absolutebest'></div>"+
				"<div class=title>Most Active</div><div class=content id='mostactive'></div>"+
				"<div class=title>Most Creative</div><div class=content id='mostcreative'></div>";
		$("container").innerHTML = str;		
	Request.sendGET(SERVICE_URL+"/besttoday/"+LIKEME_USER_COUNT+"/1", resp_besttoday);
	Request.sendGET(SERVICE_URL+"/absolutebest/"+LIKEME_USER_COUNT+"/1", resp_absolutebest);
	Request.sendGET(SERVICE_URL+"/mostactive/"+LIKEME_USER_COUNT+"/1", resp_mostactive);
	Request.sendGET(SERVICE_URL+"/mostcreative/"+LIKEME_USER_COUNT+"/1", resp_mostcreative);
}

var resp_besttoday = function(response){
	var data = response.data;
	var totalbesttoday = data.users.length;
	besttoday = new Paging("absolutebest", totalbesttoday, SERVICE_URL+"/besttoday/"+LIKEME_USER_COUNT, data, "besttoday");
}

var resp_absolutebest = function(response){
	var data = response.data;
	var totalabsolutebest = data.users.length;
	smartPaging = new Paging("absolutebest", totalabsolutebest, SERVICE_URL+"/absolutebest/"+LIKEME_USER_COUNT, data, "absolutebest");
}

var resp_mostactive = function(response){
	var data = response.data;
	var totalactive = data.users.length;
	mostactive = new Paging("mostactive", totalactive, SERVICE_URL+"/mostactive/"+LIKEME_USER_COUNT, data, "mostactive");
}

var resp_mostcreative = function(response){
	var data = response.data;
	var totalcreative = data.users.length;
	mostcreative = new Paging("mostcreative", totalcreative, SERVICE_URL+"/mostcreative/"+LIKEME_USER_COUNT, data, "mostcreative");
}
var firstscore = 0;
var secondscore = 0;
var likeMeFirstResponse = null;
var req_likeMeFirst = function(){	

	var str = "<div id='score'><div  id='scoreDiv' width = '30%'></div><div id='scoreRes' style='margin-top:4px'></div></div>"+
		  "<div id=likeMeDiv></div>"+
		  "<div id=postUnderLikeMe></div>"+
		  "<div id='adDiv3' style='margin:30px 0px;' ></div>"+
		 // "<div id=adDiv3 style='margin:30px 0px;'>"+getAd(3)+"</div>"+
		  "<div id=resultsDiv><div class=loading>Loading...</div></div>";
	container.innerHTML = str;
	Request.sendGET(SERVICE_URL+"/testscore/"+userId+"/"+surveyId+"/"+LIKEME_USER_COUNT+"/1"+"/"+firstscore+"/"+secondscore, resp_likeMeFirst);
   
	applyMiddleAd("adDivMiddle", "adDiv3");
}

var likeMePaging;
var testPaging;
var resp_likeMeFirst = function(response){
	likeMeFirstResponse = response;
	var data = response.data;
	totalLikeMe = data.total;
	allowNotExactMatch = data.allowNotExactMatch;
	var str =  "";
	if(flag){
		if(score-5 >= 0){
			firstscore = score-5;
		}else{
			firstscore = 0;
		}
		if(score+5 <= totalPoints){
			secondscore = score+5;
		}else{
			secondscore = totalPoints;
		}
	}
	flag = false;
	
	totaltest = data.total;
	var scoreDiv = document.getElementById("scoreDiv");
	var strStart = "<select id = 'firstscore'>";
	for(var j = 0; j <= totalPoints - 1 ; j++){
		if(firstscore != j)
			strStart+="<option>"+j+"</option>";
		else{
			strStart+="<option selected>"+j+"</option>";
		}
	}
	
	strStart+= "</select>";
	
	var strEnd = "<select id = 'secondscore'>";
	for(var j = 1; j <= totalPoints ; j++){
		if(secondscore != j){
			strEnd+="<option>"+j+"</option>";
		}
		else{
			strEnd+="<option selected>"+j+"</option>";
		}
	}
	strEnd+= "</select>";
	scoreDiv.innerHTML = "<b style='font-size:15px'>Show people who got\t</b>"+strStart+"<b style='font-size:15px'> to </b>"+strEnd+"<b style='font-size:15px'>\tpoints\t</b><img src='"+SERVER_URL+"img/find.png'   style='margin-bottom:-5px ; cursor:pointer ' id='doneScore' onclick = 'done_score()'>";
	testPaging = new Paging("testPaging", totaltest, SERVICE_URL+"/testscore/"+userId+"/"+surveyId+"/"+LIKEME_USER_COUNT, data, "scoreRes");

	gadgets.window.adjustHeight();
}

var done_score = function(){
	var errorDiv = $("error");
	firstscore = document.getElementById("firstscore").value;
	secondscore = document.getElementById("secondscore").value;
	if(firstscore<=secondscore){
		errorDiv.style.display = "none";
		Request.sendGET(SERVICE_URL+"/testscore/"+userId+"/"+surveyId+"/"+LIKEME_USER_COUNT+"/1"+"/"+firstscore+"/"+secondscore, resp_likeMeFirst);
	}else{
		errorDiv.style.display = "";
		errorDiv.innerHTML = "Enter valid numbers, please.";
	}
}

var updateLikeMeHeader = function(){
	try{
		if (totalTakenCount > 0){
			var percent = Math.round(100*totalLikeMe/totalTakenCount);
			if (percent == 0 && totalLikeMe > 0) percent = 1;
			var str = "<table width=100% cellspacing=0><tr><td class=title>"+percent+"% people are like you ("+totalLikeMe+" out of "+totalTakenCount+")</td>";
			str += "<td class=title align=right><a href='#' class=link onclick='req_likeMe(this, "+GENDER_MALE+")'>Male</a>  ";
			str += "<a href='#' class='link' onclick='req_likeMe(this, "+GENDER_FEMALE+")'>Female</a>  ";
			str += "<a href='#' class='selectedLink' onclick='req_likeMe(this)'>All</a></td></tr></table>";
			$("likeMeHeader").innerHTML = str;
		}
	}catch(ex){}
}
var likeMeGender;
var req_likeMe = function(node, gender){
	var links = node.parentNode.childNodes;
	for (var i=0;i<links.length;i++){
		links[i].className = "link";
	}
	node.className = "selectedLink";
	likeMeGender = gender;
    Request.sendGET(SERVICE_URL+"/peopleLikeMe/"+userId+"/"+surveyId+"/"+likeMeGender+"/"+allowNotExactMatch+"/"+LIKEME_USER_COUNT+"/1", resp_likeMe);
}

var resp_likeMe = function(response){
	likeMeFirstResponse = response;
	var data = response.data;
	allowNotExactMatch = data.allowNotExactMatch;
	var url = SERVICE_URL+"/peopleLikeMe/"+userId+"/"+surveyId+"/"+likeMeGender+"/"+allowNotExactMatch+"/"+LIKEME_USER_COUNT;
	likeMePaging = new Paging("likeMePaging", data.total, url, data, "likeMe");
}

var resp_getResults = function(response){

	if (response.errorCode){
		logError();
		SURVEY_QUESTIONS = null;
		return;
		
	}
	var data = response.data;
	surveyId = data.survey.id
	
	showResults(data.questions);
	//$("adDiv1").innerHTML = getAd(1);
	//$("adDiv2").innerHTML = getAd(2);
}

var showResults = function(questions, flirt){
    
	var adIds= new Array();
	$("surveyHeader").innerHTML =
		"<table><tr><td><img src='"+surveyImgUrl+"'></td>"+
		"<td><h1>"+SURVEY.title+"</h1><div class=lightGreyText>"+SURVEY.description+"</div></td>"+
		"</tr></table>";
	var colspan = 3;
	myResults = "";
	score = 0;
	totalPoints = 0;
	var str = "<form name=match><div style='border:1px solid #D8DEEE; margin-top:5px'><table cellspacing=0 cellpadding=0 width=100% id='show_result_table' ><tbody>"+
				"<tr>"+
					"<td class=resultHead>Answer</td>"+
					"<td class=resultHead>You</td>";
					if (showOwnerAnswer && !flirt){
						str+=
						"<td class=resultHead>"+ownerName+"</td>";
						colspan = 4;
					}
					str+=
					"<td class=resultHead>Correct</td>"+
				"</tr>";
	var answers, percent, width;
	SURVEY_QUESTIONS = questions;
	totalTakenCount = questions[0].totalAnswers;
	//updateLikeMeHeader();
	
	if ($("adDiv3")) applyMiddleAd('adDivMiddle', 'adDiv3'); 	//$("adDiv3").innerHTML = getAd(3);
	for (var i=0;i<questions.length;i++){
		if (questions[i].text == "Age"|| questions[i].text == "Gender"){
			continue;
		}
		
		totalPoints += questions[i].cost;
	
		if (i!=0 && i % 4 == 0 && questions.length-i>2){
			var k = 3+i/4;
			str += "<tr><td style='padding:5px;' colspan="+(colspan+1)+"  id='ad"+k+"' ></td></tr>"; 
			adIds.push("ad"+k);
		}
		if(questions[i].id != "age" && questions[i].id != "gender"){
			myResults += "</br><br/>";
			if (questions[i].imgUrl){
				myResults += "<img src='"+SURVEY_IMG_URL+questions[i].imgUrl+"' />";
			}
			if (questions[i].text){
				myResults += "<b>"+questions[i].text+"</b>";
			}
		}
		var tmp = 'questions[i].id != "age" && questions[i].id != "gender"';
		str +="<tr><td colspan="+colspan+" class=question><table cellspacing=0 cellpadding=0 width=100%><tr>" + (questions[i].imgUrl ? "<td class='question_img_td'><img class=question_Img src='"+SURVEY_IMG_URL+questions[i].imgUrl+"' /></td>" : "");
		str += (questions[i].text ? "<td style='padding-left: 5px; font-weight: bold;'>"+questions[i].text+(eval(tmp)? "\t(<span style='color:red'>"+questions[i].cost+"</span><span style='font-weight:normal'> points</span>)" : "")+"</td>" : "" )+"</tr></table></td></tr>";
		answers = questions[i].answers;
		for (var j=0;j<answers.length;j++){
			percent = 100 * answers[j].count / totalTakenCount;
			percent = roundToDecimals(percent, 2);
			if (answers[j].count == null){
				answers[j].count = 0;
			}
			if(answers[j].isMine){
				if(questions[i].id != "age" && questions[i].id != "gender"){
					if (answers[j].imgUrl){
						myResults += "<img src='"+SURVEY_IMG_URL+answers[j].imgUrl+"' />";
					}
					if (answers[j].text){
						myResults += "&nbsp;&nbsp;"+answers[j].text;
					}
				}
			}
			if (showOwnerAnswer && !flirt){
				answers[j].isOwners = false;
				if (questions[i].text == "Age" && answers[j].id == ownerAge ||
					questions[i].text == "Gender" && answers[j].id == ownerGender ||
					OWNER_ANSWER.charAt(i) == answers[j].letter 
					){
					answers[j].isOwners = true;
				}
			}
			if(answers[j].isMine && answers[j].is_correct){
				score += questions[i].cost;
			}
			str +="<tr class='"+((answers[j].isMine && answers[j].is_correct) ? "bgImg'" : "result'")+" name='result'>"+
						"<td width=40% style='padding-left: 10px;'>"+
							"<table cellspacing=0 cellpadding=0 width=100% height=31px>"+
								"<tr>"+(answers[j].imgUrl ? "<td width=50 >"+
									"<img onmouseover=\"imageMouseOver('"+i+"_"+j+"', '"+answers[j].imgUrl+"')\" id='answerImg_"+i+"_"+j+"' class=answer_Img src='"+SURVEY_IMG_URL+answers[j].imgUrl+"' />"+
									"<img onmouseover=\"imageMouseOver('"+i+"_"+j+"', '"+answers[j].imgUrl+"')\" id='Img_"+i+"_"+j+"' src='"+IMG_URL+"plus_icon.png' />"+ 
								  "</td>" : "" );
						str += (answers[j].text ? "<td>"+answers[j].text+"</td>" : "" )+"</tr></table></td>";
						if (flirt){
						str+=
						"<td align=center width=5%><input type=checkbox name=q_"+questions[i].id+" value="+answers[j].id+" letter="+answers[j].letter+" /></td>";
						}else{
							str+=
							"<td align=center width=5%>";
							if(answers[j].isMine && answers[j].is_correct){
								str+="<img src='"+IMG_URL+"ok.png' /></td>";
							}else if(answers[j].isMine && !(answers[j].is_correct)){
								str+="<img src='"+IMG_URL+"wrong.png' /></td>";
							}else{
								str+="</td>";
							}
						}
						str+=
						"<td width=35%>";
						if(answers[j].is_correct == IS_CORRECT){
							str+="<img src='"+IMG_URL+"ok.png' />";
						}else{
							str+="";
						}
//							"<div class=bgParent style='width:100%'>"+
//								"<div class=bg style='background-image:url("+IMG_URL+"progress.jpg);width:"+percent+"%' ></div>"+
//								"<div class=count>"+percent+"% ("+answers[j].count+")</div>"+
//							"</div>"+
						str+=
						"</td>"+
				  "</tr>";
		}
	}
	str+="</tbody></table></div></form>";
	if (flirt){
		str += "<input id=matchButton class=button type=button value=Match onclick='req_match()' />";
	}else{
		/*str += "<div align=center style='margin-top: 40px'><a href='javascript:goToNextSurvey()'>"+
		   "<img src="+IMG_URL+"next.jpg /></a>"+
		   "<span onclick='changeAnswer()' style='padding-left: 100px;'><img src="+IMG_URL+"retake.jpg /></span>"+
		   "</div>";*/
	}
	str += "<div id='matchDiv' />";
	
	$("resultsDiv").innerHTML = str;

	var result_table = $("show_result_table");
	var scoreDiv = document.createElement("div");
	scoreDiv.className = "score_result";	
	var str = "<b style='padding-bottom:10px'>Your score is <span style='color:red'>"+score+"</span> points out of <span style='color:red'>"+totalPoints+"</span> ( "+roundToDecimals(score*100/totalPoints)+"% )</b>"+
				" <img src='"+IMG_URL+"post_bulletin.png?v=6' onclick = 'topostBulletin()' style='margin-bottom:-7px ; cursor:pointer'> "+
				" </img><img src='"+IMG_URL+"next_trivia.png' onclick = 'nextTrivia()' style='margin-bottom:-7px ; cursor:pointer'></img>";

	scoreDiv.innerHTML = str;
	var parentDiv = result_table.parentNode.parentNode;
	parentDiv.insertBefore(scoreDiv, parentDiv.firstChild);	
	
	for(var i=0; i<adIds.length; i++){
		applyMiddleAd("adDivMiddle",adIds[i]);
	}

	gadgets.window.adjustHeight();
}

var topostBulletin = function(){
	Request.sendGET(SERVICE_URL+"/post_results/"+userId+"/"+surveyId, resp_postMyTestsResults);
}

var nextTrivia = function(){
	
	Request.sendGET(SERVICE_URL+"/nextresult/"+userId,resp_nextTrivia);
}

var resp_nextTrivia = function(response){
	var data = response.data;
	surveyId = data.id;
	takeThisTest(surveyId);
}

var replaceAll = function(oldStr,findStr,repStr) {
	var srchNdx = 0;
	var newStr = "";

	while (oldStr.indexOf(findStr,srchNdx) != -1) {
		newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
		newStr += repStr;
		srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
	}

	newStr += oldStr.substring(srchNdx,oldStr.length);

	return newStr;
}

var changeAnswer = function(){
	selectTab("take");
	$("take_survey").style.display = "";
	$("srvResults").style.display = "none";
	firstAnswer = false;
	takeSurvey(SURVEY_QUESTIONS, SURVEY, HAS_PROFILE_INFO);
}

var imageMouseOver = function(id,imgUrl) {
	var imgDiv = document.createElement("DIV");
	var div = $("answerImg_"+id);
	var left_ = findPosX(div);
	var top_ = findPosY(div);
	imgDiv.id = "imgDiv_"+id;
	imgDiv.style.position = "absolute";
	imgDiv.style.left = left_ -8  + "px";
	imgDiv.style.top = top_ + "px";
	imgDiv.innerHTML = "<img src='"+SURVEY_IMG_URL+imgUrl+"' class='imgOver' onmouseout=\"imageMouseOut('"+id+"')\"><img src='"+IMG_URL+"minus_icon.png'>"
	document.body.appendChild(imgDiv);
}

var imageMouseOut = function(id) {
	document.body.removeChild($("imgDiv_"+id));
}

////////////////////////////////////////// TAKE SURVEY ////////////////////////////////////////
var takeSurvey = function(questions, srv, hasProfileInfo){
	if (selectedTab != "take") return;
	if (false) questions = questions.concat(additionalQuestions);//removed gender and age 09.10.08
	var str = "<table width=100%>"+
				"<tr>"+
					"<td class=surveyImg>"+
						(srv.imgUrl ? "<img src='"+surveyImgUrl+"' />" : "&nbsp;" ) +
					"</td>"+
					"<td class=desc>"+
						"<h1>"+srv.title+"</h1>"+
						"<br><br>"+
						"<div class=lightGreyText>"+srv.description+"</div>"+
					"</td>"+
				"</tr>"+
			  "</table>";
	var answers, checked;
	str += "<form name=questions><table border=0 cellpadding=0 cellspacing=0 width=100%><tbody>";
	for (var i=0;i<questions.length;i++){
		if(questions[i].text=="Gender" || questions[i].text=="Age"){
			continue;
		}
		str += "<tr><td class=question><table border=0 ><tr>";
		str += (questions[i].imgUrl ? "<td><img class=question_Img src='"+SURVEY_IMG_URL+questions[i].imgUrl+"' /></td>" : "" );
		str += (questions[i].text ? "<td><b>"+questions[i].text + "\t(</b><b style='color:red' id='qst"+i+"_cost'>"+questions[i].cost+"</b> points<b>)</b></td>" : "" ) + "</tr></table></td></tr>";
		answers = questions[i].answers;
		for(var j=0;j<answers.length;j++){
			checked = "";
			if (answers[j].isMine == true || (answers[j].isMine == undefined && j==0))
				checked = "checked";
			str += "<tr><td class=answers><table><tr><td><input type=radio "+ checked +" value='"+answers[j].id+"' name='"+questions[i].id+"' qIndex="+i+" aIndex="+j+" is_correct="+answers[j].is_correct+" /></td>";
			str += (answers[j].imgUrl ? "<td><img onmouseover=\"imageMouseOver('"+i+"_"+j+"', '"+answers[j].imgUrl+"')\" id='answerImg_"+i+"_"+j+"' class=answer_Img src='"+SURVEY_IMG_URL+answers[j].imgUrl+"' style='cursor: pointer' />"+
											"<img onmouseover=\"imageMouseOver('"+i+"_"+j+"', '"+answers[j].imgUrl+"')\" id='Img_"+i+"_"+j+"' src='"+IMG_URL+"plus_icon.png' />"+ 
								  		"</td>" : "" );	
			str += (answers[j].text ? "<td>" +answers[j].text+ "</td>" : "" ) + "</tr></table></td></tr>"; 
		}
	}
	str +=
	/* "<tr><td class=question colspan=2>Share my answers with my profile visitors.</td></tr>"+
		   "<tr><td class=answers><input type=radio checked value=1 name='shared' />Yes</td></tr>"+
		   "<tr><td class=answers><input type=radio value=0 name='shared' />No</td></tr>"+*/
		 "</tbody></table></form>"+
		 "<input id=doneButton class=button type=button value=Done onclick=saveResult() />"; 
	fillContainer(str);
	adjustHeight();
}

var saveResult = function(){
	$("doneButton").disabled = true;
	var	inputs = document.questions.elements;
	var additional = "";
	var resultStr = "";
	myResults = "";
	var score = 0;
	var i = 0;
	var qstNo = -1;
	for (i=0;i<inputs.length;i++){
			if (inputs[i].checked){
				qstNo++;
				switch (inputs[i].name){
					case "age":
					case "gender":additional += "&"+inputs[i].name+"="+inputs[i].value; break;
					case "shared": IS_SHARED = (inputs[i].value == 1);additional += "&"+inputs[i].name+"="+inputs[i].value; break;
					default: resultStr += inputs[i].value+",";
					if(parseInt(inputs[i].getAttribute("is_correct")) == IS_CORRECT){
						var cost = $("qst"+qstNo+"_cost");
						score += parseInt(cost.firstChild.nodeValue,10);
					}
					var qst = SURVEY_QUESTIONS[parseInt(inputs[i].getAttribute("qIndex"))];
					var ans = qst.answers[parseInt(inputs[i].getAttribute("aIndex"))];
				    myResults += "<br/><br/>";
				    if (qst.imgUrl) myResults += "<td><img src='"+SURVEY_IMG_URL+qst.imgUrl+"' />";
				    if (qst.text) myResults += "<b>"+qst.text+"</b>";
				    if (ans.imgUrl) myResults += "&nbsp;&nbsp;<img src='"+SURVEY_IMG_URL+ans.imgUrl+"' />";
				    if (ans.text) myResults += "&nbsp;&nbsp;"+ans.text;
				    break;
				}
			}
	}
	resultStr = resultStr.substring(0, resultStr.length-1);	
	var data="query=addResults&surveyId="+surveyId;
	data += "&resultStr="+resultStr+"&score="+score+"&"+getUserPostData()+additional;
	Request.sendPOST(SERVICE_URL, data, resp_saveResult);
}

var resp_saveResult = function(response){
	if (response.errorCode){
		logError();
		return;
	}
	if (response.text == "ok"){
		hasTaken = true;
		HAS_PROFILE_INFO = true;		
		$("take_survey").style.display = "none";
		$("srvResults").style.display = "";
//		$("srvCompare").style.display = "";
		SURVEY_QUESTIONS = null;
		inviteViaBulletin(true);
	}else {
		container.innerHTML = "Error occured while saving data.";
	}
}
///////////////////////////////////// COMPARE ////////////////////////////////////////
var friend;
var friends;
var friendsId;
var friendsPaging;
var friendsCount;
var friendCurPage;
var next_friend = function(){
		var nextPage = friendCurPage + 1;
		if ($("friend_"+nextPage)){
			$("friend_"+nextPage).style.display = "";
			$("friend_"+friendCurPage).style.display = "none";
		}else{
			$("friend_"+friendCurPage).style.display = "none";
			sendCont.style.display = "none";
			new FriendPaging(nextPage);
		}
		friendCurPage++;
		$("friend").setAttribute("curPage", friendCurPage);
}

var prev_friend = function(){
	$("friend_"+friendCurPage).style.display = "none";
	$("friend_"+(friendCurPage-1)).style.display = "";
	friendCurPage--;
	$("friend").setAttribute("curPage", friendCurPage);
}

var compareFirst = function(){
	var str = "";
	str =  "<div id=compare_  style='display:none'><div onclick='backToFriends()' class='back_to_friends' >Back to friends list</div>"+
				"<div id=compareResult style='margin-top:15px'></div></div>"+
				"<div id=allFr><div id=title class=title>Friends</div>"+
			   		"<div id=usrcontentMsg class=usrcontentMsg>"+
			  			"<div id=friend></div>"+
			  	"</div></div>"+
			  	"<h1 class='postLikeMe'><a href='javascript:postMyResults()'>Post Your Results</a></h1>";
	container.innerHTML = str;
	friendCurPage = 1;
	$("friend").setAttribute("curPage", friendCurPage);
	friendsPaging = new FriendPaging(friendCurPage);
}

var backToFriends = function(){
	$("allFr").style.display = "";
	$("compare_").style.display = "none";
}

var showCompareResults = function(friendAnswers, friendId){
	$("compare_").style.display = "";
	$("allFr").style.display = "none";
	friend = getFriendById(friendId);
	var friendName = friend.getField(opensocial.Person.Field.NAME);
	var friendThumbnail = friend.getField(opensocial.Person.Field.THUMBNAIL_URL);
	var friendProfile = friend.getField(opensocial.Person.Field.PROFILE_URL);
	var userAnswerText;
	var friendAnswerText;
	if (friendAnswers){
		var questions = SURVEY_QUESTIONS;
		var str="<table width=100%>";
		var agree, agreeCount=0;
		var answers;
		for (var i=0;i<questions.length-2;i++){
			answers = questions[i].answers;
			for (var j=0;j<answers.length;j++){
				if (answers[j].isMine) userAnswerText = answers[j].text;
				if (friendAnswers.charAt(i) == answers[j].letter) friendAnswerText = answers[j].text;
			}
			agree = userAnswerText == friendAnswerText;
			if (agree) agreeCount++;
			str += "<tr><td colspan=3 class=question>"+questions[i].text+"</td></tr>"+
				   "<tr class="+(agree ? "agree" : "")+">"+
						"<td width=50%><table><tr>"+
							"<td class=img>"+
								"<img class=smallImg src='"+friendThumbnail+"' />" +
							"</td>"+
							"<td valign=top>"+
								"<a href='"+friendProfile+"' >"+friendName+"</a><br/>"+friendAnswerText+
							"</td>"+	
						"</tr></table></td>"+
						"<td width=50%><table><tr>"+
							"<td class=img>"+
								"<img class=smallImg src='"+userThumbnail+"' />" +
							"</td>"+
							"<td valign=top>"+
								"<a href='"+userProfile+"' >You</a><br/>"+userAnswerText+
							"</td>"+	
						"</tr></table></td>"+
					"</tr>";
		}
		str+="</table>";
		var percent = roundToDecimals(100*agreeCount/questions.length, 2);
		str +="<h1>Result "+percent+"%</h1>";
		str += "<div style='margin:10px 0px' id='ad3' >"+
		//str += "<div style='margin:10px 0px'>"+getAd(3)+
		       "<h1>Send a message to "+friendName+"</h1>"+getPostToHTML("", "");
	}else{
		str = "<h1>"+friendName+" has not taken this survey. Invite "+friendName+" to play "+surveyTitle+".</h1>";
		var subject = "Lets see how much we are compatible!";
		var text ="Hey!"+"<br/>"+
	              "Wonna see how much we have in common?"+
				  "Play <a href='"+surveyURL+"'>"+surveyTitle+"</a> and click compare.<br/>"+
				  "You can also send a nice gift to me if we are compatible! "+
				  "<a href='"+surveyURL+"'><img src='"+surveyImgUrl+"' /></a>"+
				  "Or create your own survey with <a href='"+MAKER_URL+"'>Survey Maker</a> and invite me to take it.";
		str += getPostToHTML(subject, text);
	}
    $("compareResult").innerHTML = str;
    applyMiddleAd("adDivMiddle", "ad3");
    
    gadgets.window.adjustHeight();
}
var valTime = null;
var getPostToHTML = function(subject, text){
	var supported = osContainer.getMySpaceEnvironment().getSupportedPostToTargets();
	var str= "<div id=postTo>"+
		   "<table>"+
		   "<tr><td>Post To:</td><td><select style='width:146px'>";
    for (var i = 0; i < supported.length; i++){
            str += "<option value='"+supported[i]+"'>" + supported[i] + "</option>";
    }
    valTime = (new Date()).getTime();
    str += "</select></td></tr>"+
    	   "<tr><td>Subject:</td><td><input value='"+subject+"' /></td></tr>"+
    	   "<tr><td>Text:</td><td><textarea rows=4 cols=55>"+text+"</textarea></td></tr>"+
    	   "<tr><td></td><td><img id='captchaimage' src='"+SERVER_URL+"ImageCaptchaServlet?valTime="+valTime+"'></td></tr>"+
    	   "<tr><td>Valid. code:</td><td><input type='text' value='' id = 'validate'/></td></tr>"+
    	   "<tr><td colspan='2'><input type=button value='Post' onclick='checkCaptcha()' /></td></tr>"+
    	   "<tr><td colspan='2' id='errorTD' style='color:red'></td></tr>"+
           "</table>"+
    	   "</div>";	
   return str;   
}

var checkCaptcha = function() {
	var valText = $("validate").value;
	var data = "valText="+valText+"&valTime="+valTime;
	Request.sendPOST(SERVER_URL+"ImageCaptchaServlet", data, getResponse);
}

var getResponse = function(response) {
	if(response.text == "true"){
		postTo();
	} else {
        $("errorTD").innerHTML = "Validation code is incorrect.";
    }
    valTime = (new Date()).getTime();
    $("captchaimage").src = SERVER_URL+"ImageCaptchaServlet?valTime="+valTime;
}

var postTo = function(){
	var postToDiv = $("postTo");
	var subject = postToDiv.getElementsByTagName("input")[0].value;
	var content = postToDiv.getElementsByTagName("textarea")[0].value;
	var postType = postToDiv.getElementsByTagName("select")[0].value;
	var os_token = MyOpenSpace.MySpaceContainer.OSToken;
	var message = opensocial.newMessage(content);
	message.setField(opensocial.Message.Field.TITLE, subject);
	message.setField(opensocial.Message.Field.TYPE, postType);
	var recipientPerson = friend;
	osContainer.postTo(os_token, message, recipientPerson);		
}

var postAtStart = function(){
	var subject;
	var content;
	subject= surveyTitle;
	content= "<a href='"+surveyURL+"'>Come play with me now!</a> Find your perfect match!"+
			 "You can also create your own survey with <a href='"+MAKER_URL+"'>Survey Maker</a> and invite me to take it.";
	postTo_(subject, content, user, "BULLETINS");
}
var postToMassege = function(friendId) {
	var friend = getFriendById(friendId);
	var subject = surveyTitle;
	var content = "Let's play <a =href='"+surveyURL+"'>"+surveyTitle+"</a>. I want to compare our results.";
	postTo_(subject, content, friend, "SEND_MESSAGE");
}

var friendIndex = 0;
//var inviteMessage = opensocial.newMessage("Let's play [app]. I want to compare our results.");

var postInvite = function(forwardToResultsPage){
	var content = "Hey!<br/>"+
	          "Wonna see how much we have in common?"+
			  "Play <a href='"+surveyURL+"'>"+surveyTitle+"</a> and click compare.<br/>"+
			  "You can also send a nice gift to me if we are compatible! "+
			  "<a href='"+surveyURL+"'><img src='"+surveyImgUrl+"' /></a>";
	postTo_(surveyTitle, content, user, "BULLETINS", forwardToResultsPage ? req_getResults : null);
}

var getFriendById = function(id){
	for (var i=0;i<allFriends.length;i++){
		if (allFriends[i].getId() == id) return allFriends[i];		
	}
}

var postAfterMatch = function(matchCount){
	var subject= surveyTitle;
	var content= "I just found "+matchCount+" matches. <a href='"+surveyURL+"'>Come join me and more than 100,000 other match makers!</a> Find your perfect match now!"+
		 		 "You can also create your own survey with <a href='"+MAKER_URL+"'>Survey Maker</a> and invite me to take it.";
	postTo_(subject, content, user, "BULLETINS");
}

var additionalQuestions = [
	{
	text: "Your age",
	id: "age",
	answers: [
				{id:0, text: "0-14"},
				{id:1, text: "15-17"},
				{id:2, text: "18-20"},
				{id:3, text: "21-26"},
				{id:4, text: "27-35"},
				{id:5, text: "36-46"},
				{id:6, text: "46+"}
			 ]
	},
	{
	text: "Your gender",
	id: "gender",
	answers: [
				{id:0, text: "Male"},
				{id:1, text: "Female"}
			 ]
	}
];

var requireTakeSurvey = function(){
	container.innerHTML = "<center><h1>You should <a href='javascript:req_getSurvey()'>Take the trivia</a> first.</center>";
}
///////////////////////////////////////// Match & Flirt ///////////////////////////////////////////////
var matchReqData;
var flirt = function(){
	selectTab("flirt");
	if (!hasTaken) {
		requireTakeSurvey();
		return;
	}
	if (!showContent){
		checkAge();
	}else{
		container.innerHTML = "<div id=resultsDiv><div class=loading>Loading...</div></div>";
		if (SURVEY_QUESTIONS == null){
			Request.sendGET(SERVICE_URL+"/results/"+userId+"/"+surveyId, resp_getResultsForFlirt);
		}else{
			showResults(SURVEY_QUESTIONS, true);
		}
	}
}

var resp_getResultsForFlirt = function(response){
	if (response.errorCode){
		logError();
		return;
	}
	questions = response.data.questions;
	if (selectedTab == "flirt") showResults(questions, true);
}

var req_match = function(){
	var data = "query=match&surveyId="+surveyId+"&userId="+userId;
	var	form = document.match;
	var inputs;	
	var count = 0; 
	var age="", gender="", matchStr="", answer="";// "^...[abci]..$"
	var questions = SURVEY_QUESTIONS;
	for (var i=0;i<questions.length;i++){
		inputs = form["q_"+questions[i].id];
		answer = "";
		for (var k=0;k<inputs.length;k++){
			if (inputs[k].checked){
				if (inputs[k].name == "q_age"){
					age += inputs[k].value+",";
				}else if(inputs[k].name == "q_gender"){
					gender += inputs[k].value+",";
				}else{
					answer += inputs[k].getAttribute("letter");
				}
			}
		}
		if (i<questions.length-2){
			if (answer == ""){
				matchStr += ".";
			}else{
				matchStr += "["+answer+"]";
				count++;
			}
		}
	}
	if (count == 0 && age == "" && gender == ""){
		showError("You should select one answer at least."); 
	}else{
		age = age.substring(0, age.length-1);
		gender = gender.substring(0, gender.length-1);
		matchPage = 1;
		data += "&matchAge="+age+"&matchGender="+gender+"&matchStr="+matchStr;
		matchReqData = data;
		data += "&page="+matchPage+"&userCount="+USER_COUNT;
		Request.sendPOST(SERVICE_URL, data, resp_match);
		$("matchButton").disabled = true;
		showError("");
	}
}
var matchPaging;
var resp_match = function(response){
	try{$("matchButton").disabled = false;}catch(e){}
	if (response.errorCode){
		logError();
		return;
	}
	var data = response.data;
	var str = ""; 
	var matchDiv = $("matchDiv");
	if (data.users.length == 0){
		str = "<div class='textGreen'>Nobody answered like you (yet).</div>";
		matchDiv.innerHTML = str;
	}else{
		var total = data.available ? data.users.length : data.users.length;
		str = "<div style='margin-bottom:20px;' id='ad3' ></div>"+
		//str = "<div style='margin-bottom:20px;'>"+getAd(3)+"</div>"+	
			  "<h1 class='postLikeMe'><a href='javascript:postAfterMatch("+total+")'>Post match result to your bulletin!!!</a></h1>"+
			  "<div class=title>Match Result</div>"+
			  "<div class=usrcontentMsg>"+
			  	"<div id=matchUser><div class=loading>Loading...</div></div>"+
			  "</div>";
	    matchDiv.innerHTML = str;
	  	matchPaging = new Paging("matchPaging", total, SERVICE_URL, data, "matchUser", matchReqData );
	}
	applyMiddleAd("adDivMiddle", "ad3");
	gadgets.window.adjustHeight();
}


//////////////////////////////////////////////////////////////////

////////////////////////////////////// INBOX /////////////////////
var smileCount, smilePaging;
var kissCount, kissPaging;
var hugCount, hugPaging;
var winkCount, winkPaging;
var beerCount, beerPaging;
var flowerCount, flowerPaging;
var icecreamCount, icecreamPaging;

var req_getUserMsgs = function(){
	selectTab("inbox");
	if (!hasTaken) {
		requireTakeSurvey();
		return;
	}
	showLoading();
	Request.sendGET(SERVICE_URL+"/userMsgs/"+userId+"/"+surveyId+"/"+USER_COUNT, resp_getUserMsgs);
}


var resp_getUserMsgs = function(response){
	var json = response.data;
	cupCount =json.cupCount;
	bookCount = json.bookCount;
	medalCount = json.medalCount;
/*	winkCount = json.winkCount;
	beerCount = json.beerCount;
	flowerCount = json.flowerCount;
	icecreamCount = json.icecreamCount;*/
	var str = "<div style='height:55px' class=title><img width='40px' height='55px' src='"+IMG_URL+"cup.gif'><span style='position:relative;top:-23px'>People, who has sent you CUP ("+cupCount+")</span></div>"+
			  "<div class=usrcontentMsg>"+
			  	"<div id=cup><div class=loading>Loading...</div></div>"+
			  "</div>"+ 
			  '<div style="margin-bottom:10px;" id="ad3" >'+
			  		//getAd(3)+
			  '</div>'+	
	         "<div style='height:55px' class=title><img width='48px' height='55px' src='"+IMG_URL+"book.gif'><span style='position:relative;top:-23px'>People, who has sent you BOOK ("+bookCount+")</span></div>"+
			  "<div class=usrcontentMsg>"+
			  	"<div id=book><div class=loading>Loading...</div></div>"+
			  "</div>"+
			  '<div style="margin-bottom:10px;" id="ad4" >'+
			  		//getAd(4)+
			  '</div>'+			  
			  "<div style='height:55px' class=title><img width='32px' height='55px' src='"+IMG_URL+"medal.gif'><span style='position:relative;top:-23px'>People, who has sent you MEDAL ("+medalCount+")</span></div>"+
			  "<div class=usrcontentMsg>"+
				  	"<div id=medal><div class=loading>Loading...</div></div>"+
			  "</div>"+
			  '<div style="margin-bottom:10px;" id="ad5" >'+
			  		//getAd(5)+
			  '</div>';
/*			  "<div class=title>People, who has sent you WINK ("+winkCount+")</div>"+
			  "<div class=usrcontentMsg>"+
				  	"<div id=wink><div class=loading>Loading...</div></div>"+
			  "</div>"+
			  '<div style="margin-bottom:10px;">'+
			  		getAd(6)+
			  '</div>'+		  
			  "<div class=title>People, who has sent you BEER ("+beerCount+")</div>"+
			  "<div class=usrcontentMsg>"+
				  	"<div id=beer><div class=loading>Loading...</div></div>"+
			  "</div>"+
			   '<div style="margin-bottom:10px;">'+
			  		getAd(7)+
			  '</div>'+	
			  "<div class=title>People, who has sent you FLOWER ("+flowerCount+")</div>"+
			  "<div class=usrcontentMsg>"+
				  	"<div id=flower><div class=loading>Loading...</div></div>"+
			  "</div>"+
			   '<div style="margin-bottom:10px;">'+
			  		getAd(8)+
			  '</div>'+	
			  "<div class=title>People, who has sent you ICE_CREAM ("+icecreamCount+")</div>"+
			  "<div class=usrcontentMsg>"+
				  	"<div id=icecream><div class=loading>Loading...</div></div>"+
			  "</div>";*/
	container.innerHTML = str;
	var data = {users: json.cups, available: ((cupCount - USER_COUNT) > 0)};
	smilePaging = new Paging("cupPaging", cupCount, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_CUP+"/"+USER_COUNT, data, "cup");
	data = {users: json.books, available: ((bookCount - USER_COUNT) > 0)};
	kissPaging = new Paging("bookPaging", bookCount, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_BOOK+"/"+USER_COUNT, data, "book");
	data = {users: json.medals, available: ((medalCount - USER_COUNT) > 0)};
	hugPaging = new Paging("medalPaging", medalCount, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_MEDAL+"/"+USER_COUNT, data, "medal");
/*	data = {users: json.winks, available: ((winkCount - USER_COUNT) > 0)};
	winkPaging = new Paging("winkPaging", winkCount, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_WINK+"/"+USER_COUNT, data, "wink");
	data = {users: json.beers, available: ((beerCount - USER_COUNT) > 0)};
	beerPaging = new Paging("beerPaging", beerCount, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_BEER+"/"+USER_COUNT, data, "beer");
	data = {users: json.flowers, available: ((flowerCount - USER_COUNT) > 0)};
	flowerPaging = new Paging("flowerPaging", flowerCount, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_FLOWER+"/"+USER_COUNT, data, "flower");
	data = {users: json.icecreams, available: ((icecreamCount - USER_COUNT) > 0)};
	icecreamPaging = new Paging("icecreamPaging", icecreamCount, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_ICECREAM+"/"+USER_COUNT, data, "icecream");*/
	
	
	setTimeout('applyMiddleAd("adDivMiddle", "ad3"),2000');
	setTimeout('applyMiddleAd("adDivMiddle", "ad4"),3000');
	setTimeout('applyMiddleAd("adDivMiddle", "ad5"),4000');
	
	gadgets.window.adjustHeight();
}

var FriendPaging = function(friendPage) {
	var self = this;
	var containerId = "friend";
	this.compare = function(){
		selectTab("compare");
		if (!hasTaken) {
			requireTakeSurvey();
			return;
		}
		if (!showContent){
			checkAge();
		}else{
			var req=opensocial.newDataRequest();
			MyOpenSpace.DefaultPageSize = 20;
			var params = {}; 
   			params[opensocial.DataRequest.PeopleRequestFields.FIRST] = (friendPage-1)*MyOpenSpace.DefaultPageSize;
		   	req.add(req.newFetchPeopleRequest("VIEWER_FRIENDS", params), "friends");
		    req.send(this.showComapre);
		}
	} 

	this.showComapre = function(data){
		if (selectedTab != "compare") return;
		friendsData = data;
		friends = data.get("friends").getData().asArray();
		friendsCount = data.get('friends').getData().getTotalSize();
		friendsId="";
		for (var i=0;i<friends.length;i++){
			if(friends[i].getId() != "6221"){
				allFriends[allFriends.length] = friends[i];
				friendsId += friends[i].getId()+",";
			}
		}
		friendsId = friendsId.substring(0, friendsId.length-1);
		
		var resp_getFriends = function (response){
			if (response.errorCode){
				logError();
				return;
			}
		
			var takenFriends = response.data;
			var json = [];
			var obj;
			var answer;
			for(var j=0; j<friends.length; j++) {
			    obj = {};
			    obj.id = friends[j].getField(opensocial.Person.Field.ID);
			    if(obj.id != "6221"){
				    obj.name = friends[j].getField(opensocial.Person.Field.NAME);
				    obj.thumbnail = friends[j].getField(opensocial.Person.Field.THUMBNAIL_URL);
				    answer = takenFriends[obj.id];
				    if (answer != null && answer != 'undefined'){ 
				    	obj.hasTaken = true;
				    	obj.answer = answer;
				    }else{
				    	obj.hasTaken = false;
				    }
				    json[json.length] = obj;
				}
			}
			var data = {users: json, available: ((friendsCount-allFriends.length)>0)};
			var str = getFriendsHTML(data);
			$("friend").innerHTML +=  "<div id=friend_"+friendPage+">"+str+"</div>";
		}
		Request.sendGET(SERVICE_URL+"/getFriends/"+userId+"/"+friendsId+"/"+surveyId, resp_getFriends);
	}
	
	var contains = function(ar, el){
		var res = false;
		for (var i=0;i<ar.length && !res;i++){
			if (ar[i] == el) res = true;
		}
		return res;
	}
	
	var getFriendsHTML = function(data){
		var str = "<table class=matchUser>";
		var users = data.users;
		for (var i=0; i<users.length; i++){
		    
			if (i % 5 == 0) str+= "<tr>";
			str += "<td name=userCell width=20% class='userBox'>"+
						"<table  valign=top width=100%><tr>";
		    var name = users[i].name;
		    var hasTaken =  users[i].hasTaken;
	        if(name.length>15){
	        	name = name.substring(0,15)+"\n"+name.substring(15);
	        }
	        str += "<td class=smallFont_>"+name+"</td>";
	        str +=  "<td align=right><input hasTaken="+hasTaken+" type=checkbox checked=true name='checkBox' id='"+users[i].id+"' /></td></tr></table>";
            str += "<table><tr>"+    
			   		 "<td><img class=smallImg src='"+users[i].thumbnail+"' /></td>"+
					 "<td>"+
					    "<table><tr>"+
					       "<td id='getNot"+users[i].id+"' onclick='getNotifications("+users[i].id+",this, \""+containerId+"\")'><img name='popup' padding='center' src='"+IMG_URL+"selectBox.png' /></td>"+
					      "</tr><tr>"+
					         "<td id='getGift"+users[i].id+"'><img name='popup' src='"+IMG_URL+"cupBox.png' onclick='getGifts("+users[i].id+",this, \""+containerId+"\")' /></td>"+
					      "</tr>"+					      				      
					    "</table>"+
					 "</td>"+  
			        "</tr></table>";
			        if(hasTaken) {
		        	  str += "<table><tr>"+ 
		        				"<td onclick='showCompareResults(\""+users[i].answer+"\", "+users[i].id+")' style='color: #003399; text-decoration: underline;cursor: pointer;'' />Compare"+
		        				"</td>"+
		        			"</tr></table>";
			        } else {
			        	str += "<table><tr>"+ 
			        				"<td onclick='postToMassege("+users[i].id+")' style='color: gray; text-decoration: underline;cursor: pointer;'>Invite Friend"+
			        				"</td>"+
			        			"</tr></table>";
			        }
			      str +=  "</td>";
			if (i % 5 == 4) str += "</tr>";
		}
		var prevPage = friendPage - 1;
		if (data.available || prevPage>0){
			str += "<tr><td colspan=5 align=right>";
						if (prevPage>0)
						str+=
						"<a href='javascript:prev_friend()' style='margin-right: 10px;'>Previous</a>";
						if (data.available)
						str+=
						"<a href='javascript:next_friend()' style='margin-right: 10px;'>Next</a>"+
					"</td></tr>";
		}
		str += "</table>";
		return str;
	}
	
		var table = document.createElement("table");
		sendCont = document.createElement("tbody");
		var row = document.createElement("tr");
		sendCont.appendChild(row);
		var cell1 = document.createElement("td");
		row.appendChild(cell1);
		checkBox = document.createElement("input");
		checkBox.type = "checkbox";
		checkBox.checked = "true";
		checkBox.onclick = function(){
			selectAll(this.checked, "friend");
		}
		cell1.appendChild(checkBox);
		cell1.appendChild(document.createTextNode("Select all"));
		var cell2 = document.createElement("td");
		row.appendChild(cell2);
		
		var imgInvite = document.createElement("img");
		imgInvite.className = "sendButtonInvite";
		imgInvite.src = IMG_URL+"inviteAll.png";
		imgInvite.onclick = inviteAll;
		var imgSendKiss = document.createElement("img");
		imgSendKiss.className = "sendButton";
		imgSendKiss.src = IMG_URL+"applauses.gif";//"sendKiss.png";
		imgSendKiss.onclick = function(){sendMsg(NOT_TYPE_KISS, this, containerId);}
		var imgSendHug = document.createElement("img");
		imgSendHug.className = "sendButton";
		imgSendHug.src = IMG_URL+"sendHug.png";
		imgSendHug.onclick = function(){sendMsg(NOT_TYPE_HUG, this, containerId);}
		var imgSendWink = document.createElement("img");
		imgSendWink.className = "sendButton";
		imgSendWink.src = IMG_URL+"sendWink.png";
		imgSendWink.onclick = function(){sendMsg(NOT_TYPE_WINK, this, containerId);}
		var imgSendSmile = document.createElement("img");
		imgSendSmile.className = "sendButton";
		imgSendSmile.src = IMG_URL+"sendSmile.png";
		imgSendSmile.onclick = function(){sendMsg(NOT_TYPE_SMILE, this, containerId);}
		var imgSendBeer = document.createElement("img");
		imgSendBeer.className = "sendButton";
		imgSendBeer.src = IMG_URL+"sendBeer.png";
		imgSendBeer.onclick = function(){sendMsg(NOT_TYPE_BEER, this, containerId);}
		var imgSendFlower = document.createElement("img");
		imgSendFlower.className = "sendButton";
		imgSendFlower.src = IMG_URL+"sendFlower.png";
		imgSendFlower.onclick = function(){sendMsg(NOT_TYPE_FLOWER, this, containerId);}
		var imgSendIcecream = document.createElement("img");
		imgSendIcecream.className = "sendButton";
		imgSendIcecream.src = IMG_URL+"sendIcecream.png";
		imgSendIcecream.onclick = function(){sendMsg(NOT_TYPE_ICECREAM, this, containerId);}
		
		cell2.appendChild(imgInvite);
		cell2.appendChild(imgSendKiss);
		cell2.appendChild(imgSendHug);
		cell2.appendChild(imgSendWink);
		cell2.appendChild(imgSendSmile);
		cell2.appendChild(imgSendBeer);
		cell2.appendChild(imgSendFlower);
		cell2.appendChild(imgSendIcecream);
		
		var row = document.createElement("tr");
		sendCont.appendChild(row);
		infoCell = document.createElement("td");
		infoCell.colSpan=2;
		infoCell.id = containerId+"_info";
		infoCell.className = "msgSent";
		row.appendChild(infoCell);
		
		table.appendChild(sendCont);
		$("friend").parentNode.appendChild(table);
		this.compare();
}


var getInviteLink = function(){
	var msgHTML = "Hey!"+"<br/>"+
	              "Wonna see how much we have in common?"+
				  "Play <a href='"+surveyURL+"'>"+surveyTitle+"</a> and click compare.<br/>"+
				  "You can also send a nice gift to me if we are compatible! "+
				  "<a href='"+surveyURL+"'><img src='"+surveyImgUrl+"' /></a>";
	var hr = GetThis("Lets see how much we are compatible!", msgHTML, surveyURL, 2);
	return hr;
}

var inviteViaBulletin = function(forwardToResultsPage){
	selectTab("invite");
   	var str = "<center><h1 style='font-size:19px'>Invite Your Friends to have more fun!!!<br/></h1>"+
   			 "<img style='cursor:pointer;' src='"+IMG_URL+"post_to_bulletin_big.png' onclick='postInvite()'></center>";
  	str += "<div style='margin: 30px 0px;'><h1 style='font-size:19px'>Send invitations to your friends.</h1><div id=friend><div></div>";
    container.innerHTML = str;
    Invite.show();
}

var fillBody = function(){
	var popUpDiv = document.createElement("div");
	popUpDiv.id = "popUpCont"; 
	document.body.appendChild(popUpDiv); 
	allContent = $("allContent");
	preloadimages("sendCup.png", "sendBook.png", "sendMedal.png",
                  "cup.gif", "book.gif", "medal.gif");
   
	fill();
    try{
    	getUser();
    }catch(ex){
    	//console.log(ex);
    }

}

var fill = function(){
	allContent.innerHTML = 
	'<div id = "surveyHeader"></div>'+
	'<table><tr>'+
	'<td><table cellspacing=0 cellpadding=0>'+
		'<tr class="tabs" id="tabContainer">'+
			'<td name=public><a href="javascript:getPublicTrivias()">Cool Trivia</a></td>'+
			'<td name=take id="take_survey"><a href="javascript:req_getSurvey()">Take Trivia</a></td>'+
			'<td name=userSurveys_1 id ="userSurveys_1"><a href="javascript:req_userSurveys(1, 1)">Taken Trivias</a></td>'+
		'<td name=userSurveys_2 id="userSurveys_2" ><a class=lastTab href="javascript:req_userSurveys(1, 2)">My Trivias </a></td>'+
			'<td name=results id="srvResults"><a href="javascript:req_getResults()">Results</a></td>'+
//			'<td name=compare id="srvCompare"><a href="javascript:compareFirst()">Compare</a></td>'+
//			'<td name=flirt id="srvFlirt"><a href="javascript:flirt()">Search</a></td>'+
			'<td name=inbox id="srvInbox"><a href="javascript:req_getUserMsgs()">Funbox</a></td>'+
			'<td name=invite id="srvInvite"><a href="javascript:inviteViaBulletin()">Invite Friends</a></td>'+
//			'<td name=users><a href="javascript:getUsers()">Cool People</a></td>'+
//			'<td name=settings id=settings><a href="javascript:settings()">Settings</a></td>'+
			'<td name=test id="test"><a href = "javascript:createTest()">Create Trivia</a></td>'+			
			'<td name=smartPeople id="smartPeople"><a class=lastTab href = "javascript:smartPeople()" >Smart People</a></td>'+		
//			'<td name=create><a class=lastTab target="_blank" href="'+MAKER_URL+'">Create Survey</a></td>'+
		'</tr>'+
	'</table></td>'+
	'<td id=enableMail style="padding-left:20px;"></td>'+
	'</tr></table>'+
	'<div style="margin-top:15px;" id="adDiv1"></div>'+
	'<table class=container><tr>'+
		'<td width=75% valign=top>'+
			'<div id=error style="display: none"></div>'+
			'<div id=container><div class=loading>Loading...</div></div>'+
		'</td>'+
		'<td id=rb width=25% valign=top style="padding:0px 10px;">'+
			"<div class=title_rb>Just Taken</div>"+
			"<div class=content_rb id='just_taken_rb'><div class=loading>Loading...</div></div>"+	
			"<div class=title_rb>Most Recent</div>"+
			"<div class=content_rb id='recent_rb'><div class=loading>Loading...</div></div>"+	
			"<div class=title_rb>Most Popular</div>"+
			"<div class=content_rb id='popular_rb'><div class=loading>Loading...</div></div>"+	
			"<div class=title_rb>Active Today</div>"+
			"<div class=content_rb id='today_rb'><div class=loading>Loading...</div></div>"+
		'</td>'+
	'</tr></table>'+
	'<div style="margin-top:20px;" id="adDiv2"></div>';
	
	container = $("container");
	errorDiv = $("error");
	
	
	applyAds('adDivTop', 'adDiv1');
	applyAds('adDivBottom', 'adDiv2');
	sr_gof();

	gadgets.window.adjustHeight();
	setInterval(refreshIframe, 45000);
}

var hideTabs = function(msg) {
	getPublicTrivias();
	req_getRightBar();
	var bodyMask = document.createElement("div");
	 bodyMask.className = "body-mask";
	 bodyMask.id = "body-mask";
	 bodyMask.onclick = function(ev){
	  if (window.event) ev = window.event;
	  ev.cancelBubble = true;
	  return false;
	 }
	 document.body.appendChild(bodyMask);
	 
	 var wizardBox = document.createElement("div");
	 wizardBox.className = "wizardBox-dlg";
	 wizardBox.id = "wizardBox-dlg";
	 wizardBox.innerHTML = 
	 "<center><img src='"+IMG_URL+"arrow_jump.gif'></center>"+
	 "<div style='border: 3px solid red; padding:13px'>"+
	 "Add / Install this App to start using "+surveyTitle+"</div>";
	 document.body.appendChild(wizardBox);
	 wizardBox.style.left = "190px";
}

function embedGoogleAnalitics(){
 try{
  var head = document.getElementsByTagName("head");
  var script = document.createElement("script");
  script.setAttribute('src', 'http://www.google-analytics.com/urchin.js');
  script.setAttribute('type', 'text/javascript');
  head[0].appendChild(script);
  
  var script = document.createElement("script");
  script.setAttribute('type', 'text/javascript');
  script.text = '_uacct = "UA-241707-8";urchinTracker();';
  head[0].appendChild(script);
 }catch(ex){}
}

var rnd = Math.floor(Math.random()*19);
var goToNextSurvey = function(){
	var nextURL = nextURLs[rnd] ? nextURLs[rnd] : nextURLs[0];
	window.open(nextURL);
}

var settings = function(){
	selectTab("settings");
	if (!hasTaken) {
		requireTakeSurvey();
		return;
	}
	var str = "<table>"+
				"<tr><td>Share my results with my profile visitors.</h1></td></tr>"+
				"<tr><td><input id=share type=radio value=1 name=share "+(IS_SHARED ? "checked" : "") +" />Yes</td</tr>"+
				"<tr><td><input type=radio value=0 name=share "+(IS_SHARED ? "" : "checked") +" />No</td</tr>"+
				"<tr><td><input id='saveSettings' type=button value='Done' onclick='saveSettings()' /></td</tr>"+
			"</table>";
	container.innerHTML = str;
}

var saveSettings = function(){
	var share = $("share").checked ? 1 : 0;
	$("saveSettings").disabled = true;
	Request.sendPOST(SERVICE_URL, "query=settings&shared="+share+"&userId="+userId+"&surveyId="+surveyId, resp_settings);
}

var resp_settings = function(response){
	if(response.text == "ok"){
		IS_SHARED = $("share").checked;
	}
	$("saveSettings").disabled = false;
}

var req_userSurveys = function(page, type){
	selectTab("userSurveys_"+type);
	var typeText = "My";
	if (type == TAKEN_SURVEYS){
		typeText = "Taken";
	}
	container.innerHTML =
	  "<div class=title>"+typeText+" Tests</div>"+
	 '<div class=usrcontent id="userSurveys"><div style="height:200px;"><div class=loading>Loading...</div></div></div>'+	
	 '<div id="ad3" ></div>'+
	// '<div>'+getAd(3)+'</div>'+
	 "<div class=title style='display:none'>Active Today</div>"+
	 "<div class=content id='today' style='display:none'><div id=todaySrv1><div class=loading>Loading...</div><div></div>";
	Request.sendGET(SERVICE_URL+"/userSurveys/"+userId+"/"+type+"/"+APP_COUNT+"/"+page, resp_userSurveys);
	todayPage = 1;
	Request.sendGET(SERVICE_URL+"/todaySurveys/"+todayPage+"/"+APP_COUNT, resp_getTodaySurveys);
	
	applyMiddleAd("adDivMiddle", "ad3");
}

var resp_userSurveys = function(response){
	var userSurveys = response.data.tests;
	var currentPage = response.data.page;
	var type = response.data.type;
	var str = "";
	var srv;
	if (!userSurveys || userSurveys.length == 0){
		if (type == CREATED_SURVEYS){
			str = "<h1>You haven't created any Trivia. <a href='javascript:createTest()'>Create a Trivia</a></h1>";
		}else if (type == TAKEN_SURVEYS){
			str = "<h1>You haven't taken any survey. <a href='javascript:getPublicTrivias()'>Click here</a> to pass a Trivia.</h1>";
		}
	}else{
		str+="<table cellspacing=12>";
		for (var i=0;i<userSurveys.length;i++){
			srv = userSurveys[i].test;
			total = userSurveys[i].totalPoints;
			current_score = userSurveys[i].score;
					if(srv.imgUrl != ""){
						surveyImgUrl = SURVEY_IMG_URL+srv.imgUrl;
						}
					else{
					surveyImgUrl = SURVEY_IMG_URL+"noimage.jpg";
					}
			switch(srv.status){
				case 0: srv.statusMsg = "Approval pending"; srv.statusColor="blue"; break;
				case 1: srv.statusMsg = "Approved"; srv.statusColor="#3B5998"; break;
				case 2: srv.statusMsg = "Not approved"; srv.statusColor="red"; break;
			}
			if ( i % 3 == 0) str += "<tr>";
			str += "<td><table><tr>"+
					"<td><a href='javascript:loadSurvey("+srv.id+")'><img width=80px height=80px src='"+surveyImgUrl+"' /></a></td>"+	
					"<td>"+
						"<a style='color:black' href='javascript:loadSurvey("+srv.id+")'>"+srv.title+"</a>"+
						"<div style='margin:3px 0px;'><a href='javascript:showMakerInviteTab("+srv.id+",\""+srv.title+"\", \""+srv.imgUrl+"\")'>Invite friends</a></div>"+
						"<div style='margin:3px 0px;'><a href='javascript:loadSurvey("+srv.id+")'>View results</a></div>"+
						(type==1 ? "<div style='margin:3px 0px;'><a href='javascript:postMyTestsResults("+srv.id+", "+userId+")'>Share results</a></div>" : "")+
						(type==1 ? "<div id='takenTestScore' style='margin:3px 0px; color:#3B5998'>Score "+current_score+" ("+roundToDecimals(current_score*100/total)+" %)</div>" : "")+
						//"<div style='margin:3px 0px;'><a href='javascript:req_getResultsForBulletin("+srv.id+",\""+srv.title+"\", \""+srv.imgUrl+"\")'>Share results</a></div>"+
					"</td>"+
				  "</tr></table></td>";
		  	if ( i % 3 == 2) str += "</tr>";
		}
		var pageCount = Math.ceil(response.data.totalCount / APP_COUNT);
		if (pageCount>1){
			str += "<tr><td colspan=3 align=right>";
			for (var p = currentPage-2; p<currentPage+2;p++){
				if (p > 0 && p <= pageCount){
					var color = p == currentPage ? "color: black" : "";
					str += "<a style='margin: 0px 7px;"+color+"' href='javascript:req_userSurveys("+p+","+type+")'>"+p+"</a>";
				}
			}
			if (currentPage < pageCount){
				str += "<a style='margin: 0px 7px;' href='javascript:req_userSurveys("+(currentPage+1)+","+type+")'>Next</a>";
			}
			str += "</td><tr>";
		}
		str += "</table>";
	}
	showError("");
	$("userSurveys").innerHTML = str;
	gadgets.window.adjustHeight();
}

var loadSurvey = function(id){
	if (id != undefined){
		surveyId = id;
	}
	if (userId != null){
		Request.sendGET(SERVICE_URL+"/survey/"+userId+"/"+surveyId, resp_loadSurvey);
		$("take_survey").style.display = "none";
		$("srvResults").style.display = "";
		selectTab("results");
		showLoading();
	}else{
		$("errorMsgDiv").innerHTML = "To load the survey you should add the app. Click on the link above.";
	}
}

var resp_loadSurvey = function(response){
	if (response.errorCode){
		logError();
		return;
	}
	if (response.error){
		hideTabs("User authorization failed. Check if you are logged in and refresh the page.");
		return;
	}
	var json = response.data;
	SURVEY = json.data.survey;
	surveyImgUrl = SURVEY_IMG_URL+SURVEY.imgUrl;
	resp_getSurvey(response);
}


var postMyTestsResults = function(srvId, userId){
	Request.sendGET(SERVICE_URL+"/post_results/"+userId+"/"+srvId, resp_postMyTestsResults);
}

var resp_postMyTestsResults = function(response){
	var resp = response.data;
	
	var title = "My results at "+resp.testName;
	var content = "<div>Hey, I have took this test called <a href='javascript:takeThisTest("+resp.testId+")'><font style='font-size:15px; text-color:blue'>"+resp.testName+"</font></a> and I am So proud of my results, check out my results! I've got "+resp.score+"points out of "+resp.totalPoints+"!!!</div><div><a target='_blank' href='http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=116330'><img src='"+IMG_URL+"play.png'></a></div>";
	postTo_(title, content, user, "BULLETINS");
}

var showMakerInviteTab = function(id, title, img){
	if (id != undefined){
		surveyId = id;
		surveyTitle = title;
		surveyURL = MAKER_URL+"&appParams=%7B%22surveyId%22%3A"+surveyId+"%7D";
		surveyImgUrl = SURVEY_IMG_URL+img;
	}
	selectTab("invite");
   	var str =
   			"<center><h1 style='font-size:19px'>Invite Your Friends to have more fun!!!<br/></h1>"+
   			"<img  style='cursor:pointer;' src='"+IMG_URL+"post_to_bulletin_big.png' onclick='postMakerInvite()'></center>"+
  			"<div style='margin: 30px 0px;'><h1 style='font-size:19px'>Click on a friend image to send an invitation.</h1><div id=friend><div></div>";
    container.innerHTML = str;
    Invite.show(id, title, img);
}

var req_getResultsForBulletin = function(id, title, img){
	if (id != undefined){
		surveyId = id;
	}
	surveyTitle = title;
	surveyURL = MAKER_URL+"&appParams=%7B%22surveyId%22%3A"+surveyId+"%7D";
	surveyImgUrl = SURVEY_IMG_URL+img;
	Request.sendGET(SERVICE_URL+"/userResult/"+userId+"/"+surveyId, resp_getResultsForBulletin);
}

var resp_getResultsForBulletin = function(response){
	if (response.errorCode || response.text == ""){
		return;
	}
	myResults = "";
	if(isQuize){
		var data = response.data;
	   	myResults+="<br><br><b>My Result Is</b>";
		myResults+="<br><br>";
		myResults+=data.imgUrl ? "<img src='"+SURVEY_IMG_URL+data.imgUrl+"' />":"";
	 	myResults+="<br><br>"
		myResults+="<b>"+data.text+"</b><br>";
	}else{
		var quest = response.data.questions;
		for (var i=0;i<quest.length;i++){
			myResults += "<br><br>";
			if (quest[i].q_imgUrl != null && quest[i].q_imgUrl != ""){
				myResults += "<img src='"+SURVEY_IMG_URL+quest[i].q_imgUrl+"' />";
			}
			if (quest[i].q_text != null && quest[i].q_text != ""){
				myResults += "<b>"+quest[i].q_text+"</b>";
			}
			if (quest[i].a_imgUrl != null && quest[i].a_imgUrl != ""){
				myResults += "<img src='"+SURVEY_IMG_URL+quest[i].a_imgUrl+"' />";
			}
			if (quest[i].a_text != null && quest[i].a_text != ""){
				myResults += "&nbsp;&nbsp;"+quest[i].a_text;
			}
		}
	}
	postMyResults();
}
