var container;
var errorDiv;
var survey;
var showContent = true;
var hasTaken;
var matchUsers;
var surveyURL;
var osContainer;
var surveyImgUrl;
var PAGE=0;
var allFriends = []; 
var SURVEY_QUESTIONS = null;
var QUIZE_RESULTS = null;
var SURVEY = null;
var OWNER_ANSWER;
var showOwnerAnswer = false;
var totalLikeMe = null;
var LIKEME_USER_COUNT = 21;
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 ADS_DATA = {};
var allowNotExactMatch = true;
var AD_SURVEYS = [
					  {url: MAKER_URL,
					   imgUrl: "logo.gif",
					   title: "Make a Survey"
					   }
					 ];
					 
var isSuperApp = false;
var inviteMessage = null;
var surveyType;
var surveyId;

SERVICE_URL = SERVICE_URL+"/"+SURVEY_TYPE_SURVEY; 

var init = function(){	
	saveUser();
	req_getAdsData();
}

var saveUser = function (){
	
	var data="query=addUser&"+getUserPostData();
	data+="&surveyId="+surveyId+"&surveyType="+SURVEY_TYPE_SURVEY;
	Request.sendPOST(SERVICE_URL, data, doNothing);
	
}

var req_getAdsData = function(){
	Request.sendGET(SERVICE_URL+"/ad", resp_getAdsData);
}

var timesRefreshed = 0;
var resp_getAdsData = function(response){
	var data = response.data;
	ADS_DATA = data.ads;
	for (var i=0; i<data.surveys.length;i++){
		if (data.surveys[i].id != surveyId){
			AD_SURVEYS[AD_SURVEYS.length] = data.surveys[i];
			surveyId = data.surveys[i].id;
		}
	}
//	$("adDiv2").innerHTML = getAd(2);
	req_getSurvey();
}

var req_getSurvey = function(){
	surveyId = getRandomElement(AD_SURVEYS).id
	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;
	surveyURL = MAKER_URL+"&appParams=%7B%22surveyId%22%3A"+surveyId+"%7D";
	surveyImgUrl = SURVEY_IMG_URL+SURVEY.imgUrl;
	surveyTitle = SURVEY.title;
	IS_APPROVED = SURVEY.status != 0;
	surveyType = json.data.survey.survey_type;
	isQuize = surveyType == SURVEY_TYPE_QUIZZ;
	APP_NAME = isQuize ? "Quiz" : "Survey";
	APP_NAMES = isQuize ? "Quizzes" : "Surveys";
	SERVICE_URL = SERVER_URL+"SurveyService/"+surveyType;
	if (json.hasTaken){
		if(surveyType==1){
			changeAnswer();
			var questions = json.data.questions;
			totalTakenCount = questions[0].totalAnswers;
		}else if(surveyType==2){
			var targets=json.data;
		    totalTakenCount=json.data.totalCount;
			QUIZE_RESULTS=targets;
			changeAnswer();
		}
	}else{
		takeSurvey(SURVEY_QUESTIONS, SURVEY, HAS_PROFILE_INFO);
	}
}

var showPostUnderLikeMe = function(){
	var str = "<h1 class='postLikeMe'>"+totalLikeMe+" people are like you. <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 postMyResults = function(){
	var content = "<a target='_blank' href='"+surveyURL+"'>"+surveyTitle+"</a>"+
				  "<br/><a target='_blank' href='"+surveyURL+"'><img src='"+surveyImgUrl+"' />"+surveyTitle+"</a><br/><br/>"+
				  "<br/><a target='_blank' href='"+surveyURL+"'>Take this "+APP_NAME+"</a>"+
				   myResults+
				  "<br/><br/><a target='_blank' href='"+surveyURL+"'>CLICK HERE TO TAKE THIS SURVEY</a>"+
				  "<br/><br/><a target='_blank' href='"+MAKER_URL+"'>More "+APP_NAME+"</a> | <a target='_blank' href='"+MAKER_URL+"'>Make a "+APP_NAME+"</a>";
	postTo_(surveyTitle, content, user, "BULLETINS", 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."+
				  "<a style='float:left' href='"+surveyURL+"'><img src='"+surveyImgUrl+"' /></a>";
	postTo_(subject, content, user, "BULLETINS");
}

var likeMePage;
/////////////////////////////////////////// RESULTS ///////////////////////////////////////////
var req_getResults = function(){
	$("topNextBtn").style.display = "";
	selectTab("take");
	req_likeMeFirst();
	Request.sendGET(SERVICE_URL+"/results/"+userId+"/"+surveyId, resp_getResults);
}

var likeMeFirstResponse = null;
var req_likeMeFirst = function(){
	var str = "";
	if(QUIZE_RESULTS!=null){
	str+="<div id=QuizeResultsDiv></div><div id=likeMeDiv></div>"+
		  "<div id=postUnderLikeMe></div>"+
		  "<div id=middleAd style='margin-bottom:8px;width:728px;height:90px;overflow: hidden;'></div>"+
	//	  "<div id=adDiv3 style='margin-bottom:8px'>"+getAd(3)+"</div>"+
		  "<div id=resultsDiv><div class=loading>Loading...</div></div>";
	}else {
	str+="<div id=likeMeDiv></div>"+
		  "<div id=postUnderLikeMe></div>"+
		  "<div id=middleAd style='margin-bottom:8px;width:728px;height:90px;overflow: hidden;'></div>"+
		 // "<div id=adDiv3 style='margin-bottom:8px'>"+getAd(3)+"</div>"+
		  "<div id=resultsDiv><div class=loading>Loading...</div></div>";
    }
	container.innerHTML = str;
    Request.sendGET(SERVICE_URL+"/peopleLikeMe/"+userId+"/"+surveyId+"/nogender/true/"+LIKEME_USER_COUNT+"/1", resp_likeMeFirst);
    
    try{
    	applyMiddleAd('adDivMiddle', 'middleAd');
	}catch(ex){
		$('middleAd').innerHTML =  '<iframe src="http://ads.socialmedia.com/myspace/monetize.php?width=645&height=60&pubid=dbca0dcd5a282e3c790056cc68783379&bgcolor=FFFFFF&bordercolor=FFFFFF" border="0" width="645" height="60" name="socialmedia_ad" scrolling="no" frameborder="0"></iframe>';
	} 
	
}

var likeMePaging;
var resp_likeMeFirst = function(response){
	likeMeFirstResponse = response;
	var data = response.data;
	totalLikeMe = data.total;
	allowNotExactMatch = data.allowNotExactMatch;
	var str =  "";
	if (totalLikeMe > 0){
		str += "<div id='likeMeHeader'></div>"+
			   "<div class=usrcontentMsg>"+
			  	"<div id=likeMe><div class=loading>Loading...</div></div>"+
			   "</div>";
		$("likeMeDiv").innerHTML = str;
		likeMePaging = new Paging("likeMePaging", totalLikeMe, SERVICE_URL+"/peopleLikeMe/"+userId+"/"+surveyId+"/nogender/"+allowNotExactMatch+"/"+LIKEME_USER_COUNT, data, "likeMe");
	}else{
		$("likeMeDiv").innerHTML = str;
	}
	showPostUnderLikeMe();
	gadgets.window.adjustHeight();
}

var updateLikeMeHeader = function(){
	try{
		if (totalTakenCount > 0 && totalLikeMe>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 id='gendercell'><a name='"+GENDER_MALE+"' class=link href='javascript:req_likeMe("+GENDER_MALE+")'>Male</a>  ";
			str += "<a name='"+GENDER_FEMALE+"' class=link href='javascript:req_likeMe("+GENDER_FEMALE+")'>Female</a>  ";
			str += "<a name='all' class=selectedLink href='javascript:req_likeMe(\"all\")'>All</a></td></tr></table>";
			$("likeMeHeader").innerHTML = str;
		}
	}catch(ex){}
}
var likeMeGender;
var req_likeMe = function(gender){
	var links = $("gendercell").getElementsByTagName("a");
	for (var i=0;i<links.length;i++){
		if (links[i].name == gender){
			links[i].className = "selectedLink";
		}else{
			links[i].className = "link";
		}
	}
	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;
		QUIZE_RESULTS=null;
		return;
	}
	var data = response.data;
	if(data.survey.survey_type==1){
		myResults="";
		showResults(data.questions);
	}else if(data.survey.survey_type==2){
		showResults(data.questions);
		showQuizeResults(data);
	} 
}


var showQuizeResults=function(results, flirt){
	myResults = "";
	var yourResultStr="<table width=100% style='text-align:center'><tr><td><h1 style='font-size: 19px;'>Your Result is</h1></td></tr>";
	for(var i=0;i<results.targets.length;i++){
		if(results.targets[i].isMine){
		    if(results.targets[i].imgUrl){
				yourResultStr += "<tr><td><img src='"+SURVEY_IMG_URL+results.targets[i].imgUrl+"' /></td></tr>";
			}
		    yourResultStr += "<tr><td style='padding-top:15px; color: #3B5998; font-size: 15px; font-weight: bolder;'>"+
						results.targets[i].text+"</td></tr>"+
			"</table>"+
			"<div style='margin: 5px 0px;'>"+getAd(10)+"</div>";   
		 	myResults+="<br/><br/><b>My Result Is</b>";
			myResults+="<br/><br>";
			myResults+=results.targets[i].imgUrl ? "<img src='"+SURVEY_IMG_URL+results.targets[i].imgUrl+"' />":"";
		 	myResults+="<br/></br>"
			myResults+="<b>"+results.targets[i].text+"</b><br/>";
 		}
	}	
	var colspan = 3;
	
	var str = yourResultStr+"<form name=match><div style='border:1px solid #D8DEEE'><table cellspacing=0 cellpadding=0 width=100% ><tbody>";
				str+="<tr>"+
					"<td class=resultHead>Results</td>"+
					"<td class=resultHead>You</td>";
					if (showOwnerAnswer && !flirt){
						str+=
						"<td class=resultHead>"+ownerName+"</td>";
						colspan = 4;
					}
					str+=
					"<td class=resultHead>All</td>"+
				"</tr>";
	if (results.targets){				
		QUIZE_RESULTS=results;
		SURVEY_QUESTIONS = results.questions;
		var percent;
		totalTakenCount = results.totalCount;
		if ($("adDiv3")) $("adDiv3").innerHTML = getAd(3);	
		for(var i=0;i<results.targets.length;i++){
			percent = 100 * results.targets[i].count / totalTakenCount;	
			percent = roundToDecimals(percent, 2);
		   	if (results.targets[i].count == null){
				results.targets[i].count = 0;
			}
		  	str +="<tr class=result>"+
					"<td width=40% style='padding-left: 10px;'>"+
						"<table cellspacing=0 cellpadding=0 width=100% height=31px>"+
							"<tr>"+(results.targets[i].imgUrl ? "<td width=50 >"+
								"<img onmouseover=\"imageMouseOver('"+i+"', '"+results.targets[i].imgUrl+"')\" id='answerImg_"+i+"' class=answer_Img src='"+SURVEY_IMG_URL+results.targets[i].imgUrl+"' />"+
								"<img onmouseover=\"imageMouseOver('"+i+"' , '"+results.targets[i].imgUrl+"')\" id='Img_"+i+"' src='"+IMG_URL+"plus_icon.png' />"+ 
							  "</td>" : "" );
					str += (results.targets[i].shortDesc ? "<td>"+results.targets[i].shortDesc +"</td>" : "<td>"+results.targets[i].text +"</td>" )+"</tr></table></td>";
					str+=
					"<td align=center width=5%>"+(results.targets[i].isMine ? "<img src='"+IMG_URL+"ok.png' />" : "" )+"</td>";
					str+=
					"<td width=35%>"+
						"<div class=bgParent style='width:100%'>"+
							"<div class=bg style='background-image:url("+IMG_URL+"progress.jpg);width:"+percent+"%' ></div>"+
							"<div class=count>"+percent+"% ("+results.targets[i].count+")</div>"+
						"</div>"+
					"</td>"+
			  "</tr>";			
		}
	}
	str+="<tbody></table></div></form>";
	if (flirt){
		str += "<input id=matchButton class=button type=button value=Match onclick='req_match()' />";
	}
	str += "<div id='matchDiv' />";				
				
				
$("QuizeResultsDiv").innerHTML = str;
	
gadgets.window.adjustHeight();				
}

var showResults = function(questions, flirt){
	var colspan = 3;
	myResults = "";
	var str = "<form name=match><div style='border:1px solid #D8DEEE'><table cellspacing=0 cellpadding=0 width=100% ><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>All</td>"+
				"</tr>";
	var answers, percent, width;
	SURVEY_QUESTIONS = questions;
	totalTakenCount = questions[0].totalAnswers;
	
	updateLikeMeHeader();
	if ($("adDiv3")) $("adDiv3").innerHTML = getAd(3);
	for (var i=0;i<questions.length;i++){
		if (i!=0 && i % 4 == 0 && questions.length-i>2){
			str += "<tr><td style='padding:5px;' colspan="+(colspan+1)+" >"+getAd(3+i/4)+"</td></tr>"; 
		}
		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>";
			}
		}
		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+"</td>" : "" )+"</tr></table></td></tr>";
		if(!questions[i].answers) continue;
		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;
				}
			}
			str +="<tr class=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%>"+(answers[j].isMine ? "<img src='"+IMG_URL+"ok.png' />" : "" )+"</td>";
						if (showOwnerAnswer) str+=
						"<td align=center width=5%>"+(answers[j].isOwners ? "<img src='"+IMG_URL+"ok.png' />" : "" )+"</td>";
						}
						str+=
						"<td width=35%>"+
							"<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>"+
						"</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.png /></a>"+
		   "<span onclick='changeAnswer()' style='padding-left: 100px;'><img src="+IMG_URL+"retake.png /></span>"+
		   "</div>";
	}
	str += "<div id='matchDiv' />";
	
	$("resultsDiv").innerHTML = str;
	
	gadgets.window.adjustHeight();
}

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");
	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){
	selectTab("take");
	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 (i!=0 && i % 4 == 0 && questions.length-i>2){
			str += "<tr><td style='padding:5px;' colspan=3 >"+getAd(3+i/4)+"</td></tr>"; 
		}
		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 + "</b></td>" : "" ) + "</tr></table></td></tr>";
		if(!questions[i].answers) continue;
		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+" /></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+= "</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 = "";
	for (var i=0;i<inputs.length;i++){
			if (inputs[i].checked){
				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+","; 
					
					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+"&surveyType="+surveyType;
	data += "&resultStr="+resultStr+"&"+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;		
		SURVEY_QUESTIONS = null;
		selectTab("take");
		req_getResults();
	}else {
		container.innerHTML = "Error occured while saving data.";
	}
}


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 postInvite = function(){
	var content = "Hey!<br/>"+
	          "Wonna see how much we have in common?"+
			  "Play <a target='_blank' 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", null);
}

var getFriendById = function(id){
	for (var i=0;i<allFriends.length;i++){
		if (allFriends[i].getId() == id) return allFriends[i];		
	}
}

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 survey</a> first.</center>";
}

var showInviteTab = function(){
	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()'>"+
  	"<div style='margin: 30px 0px;'><h1 style='font-size:19px'>Send invitations to your friends.</h1><div id=friend><div></div>";
    container.innerHTML = str;
    $("topNextBtn").style.display = "none";
    Invite.show();
}

var fillBody = function(){
	var popUpDiv = document.createElement("div");
	popUpDiv.id = "popUpCont"; 
	document.body.appendChild(popUpDiv); 
	allContent = $("allContent");
	preloadimages("sendKiss.png", "sendHug.png", "sendFlower.png", "sendWink.png",
                  "sendSmile.png", "sendBeer.png", "sendIcecream.png",
                  "beer.png", "flower.png", "icecream.png", "kiss.png",
                  "hug.png", "wink.png", "smile.png");
    fill();
	getUser();
}
var fill = function(){
	allContent.innerHTML = 
	'<table><tr>'+
	'<td><table cellspacing=0 cellpadding=0>'+
		'<tr class="tabs" id="tabContainer">'+
			'<td name=take id="take_survey"><a href="javascript:req_getSurvey()">Survey</a></td>'+
			'<td name=invite id="srvInvite" style="border:1px solid #898989;"><a href="javascript:showInviteTab()">Invite Friends</a></td>'+
		'</tr>'+
	'</table></td>'+
	'<td id=enableMail style="padding-left:20px;"></td>'+
	'</tr></table>'+
	'<div style="margin-top:5px;width:728px;height:90px;overflow: hidden;" id="topAd"></div>'+
	//'<div style="margin-top:5px;" id="adDiv1">'+getAd(1)+'</div>'+
	"<div id='topNextBtn' align=center style='margin-top: 40px'><a href='javascript:goToNextSurvey()'>"+
			   "<img src="+IMG_URL+"next.png /></a></div>"+
	
	'<table class=container><tr>'+
		'<td width=100% valign=top>'+
			'<div id=error style="display: none"></div>'+
			'<div id=container><div class=loading>Loading...</div></div>'+
			'<div style="margin-top:5px;width:728px;height:90px;overflow: hidden;" id="bottomAd"></div>'+
		//	'<div style="margin-top:5px;" id="adDiv2"></div>'+
		'</td>'+
	'</tr></table>';
	
	container = $("container");
	var topNext = "<div align=center style='margin-top: 40px'><a href='javascript:goToNextSurvey()'>"+
			     "<img src="+IMG_URL+"next.png /></a></div>";
	         	$("container").innerHTML += topNext;
	errorDiv = $("error");
	gadgets.window.adjustHeight();
	setInterval(refreshIframe, 45000);
	
	try{
		applyAds('adDivTop', 'topAd');
		applyAds('adDivBottom', 'bottomAd');
		if(OS_USER_TYPE != "friendster"){ sr_gof()};
	}catch(ex){
		$('topAd').innerHTML =  '<iframe id=ad1 src="http://ads.socialmedia.com/myspace/monetize.php?width=645&height=60&pubid=dbca0dcd5a282e3c790056cc68783379&bgcolor=FFFFFF&bordercolor=FFFFFF" border="0" width="645" height="60" name="socialmedia_ad" scrolling="no" frameborder="0"></iframe>';
		$('bottomAd').innerHTML = '<iframe src="'+SERVER_URL+'cubics_ad.html" id=ad2 style="border:0px;" width="665" height="75" scrolling="no" frameborder="0"></iframe>';
	} 
	
}

var hideTabs = function(msg) {
	/*
	init();
	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);
	*/
	$("allContent").innerHTML = "<img style='margin-left: 100px;' src='"+SERVER_URL+"img/add_app.jpg' />";
	gadgets.window.adjustHeight();
}

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(){
	req_getSurvey();
}

var loadSurvey = function(id){
	if (id != undefined){
		surveyId = id;
	}
	if (userId != null){
		Request.sendGET(SERVICE_URL+"/survey/"+userId+"/"+surveyId, resp_loadSurvey);
		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;
	$("surveyHeader").innerHTML =
	"<table><tr><td><img src='"+surveyImgUrl+"'></td>"+
		"<td><h1>"+SURVEY.title+"</h1><div class=lightGreyText>"+SURVEY.description+"</div></td>"+
	"</tr></table>";
	resp_getSurvey(response);
}

