var newSurvey = {title:"", desc:"", image:"noimage.jpg", questions: ""};
var container;
var errorDiv;
var targetIndex=0;
var targetsArray;
var questionIndex = 0;
var answerIndex = 0;
var surveyId = 1;
var surveyURL = "http://www.myspace.com/330787305";
var approved = true;
var osContainer;
var TAKEN_SURVEYS = 1;
var CREATED_SURVEYS = 2;
var inviteMessage = null;
var isSuperApp = true;
var isQuize;

var initMaker = function(){
	isSuperApp = true;
	try{
		inviteMessage = opensocial.newMessage("Hey, install this amazing app [app]. There are so many surveys and you can also create yours. Pass the surveys and compare your results with me and other friends.");
	}catch(e){
		
	}
	surveyTitle = "Matchmaking SURVEYS!";
	SERVICE_URL = SERVICE_URL+"/"+surveyType; 
	if (isQuize){
		MAKER_URL = "http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=115528";
		surveyTitle = "QUIZZES!";
	}
	req_getAdsData();
	req_getRightBar();
}

var loadMakerFirstTab = function(){
	surveyURL = MAKER_URL;
	surveyImgUrl = IMG_URL+"makerlogo.png";
	var params = opensocial.getEnvironment().getParams();
	var temp_survey_id;
	
	if(params["surveyId"]){
		temp_survey_id=params["surveyId"];
	}else if(surveyId>1){
		temp_survey_id=surveyId;
	}	

	if (params["surveyId"] || surveyId>1){
		if (userId != null){
			loadSurvey(temp_survey_id);
		}else{
			Request.sendGET(SERVICE_URL+"/surveyInfo/"+temp_survey_id, resp_getSurveyInfo);
			home();
		}
	}else{
		home();
	}
}

var resp_getSurveyInfo = function(response){
	SURVEY = response.data;
	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>";
}

var createSurvey = function(){
	selectTab("create");
	showError("");
	newSurvey.image = "noimage.jpg";
	targetIndex = 0;
	var str="<h1>Step 1: Choose a Title, Image and a Decsription for Your "+APP_NAME+" </h1>"+
			"<table>"+
				"<tr>"+
					"<td class=label>Title: *</td>"+
					"<td><input style='width: 295px;' id='srv_title' />*</td>"+
				"</tr>"+
				"<tr>"+
					"<td></td>"+
					"<td id='surveyImg'><img class=preview src='"+SURVEY_IMG_URL+"noimage.jpg'  /></td>"+
				"</tr>"+
				"<tr>"+
					"<td class=label>Choose Image:</td>"+
					"<td>"+
						'<form enctype="multipart/form-data" action="'+SERVER_URL+'Upload" method="post" '+
							 'onsubmit="return AIM.submit(this, {onStart : startUpload, onComplete : completeUpload})">'+
							'<input id="uploadImgFile" type="file" name="image" />'+
							'<input style="margin-left:6px;" id="uploadImg" type="submit" value="Upload" /> *'+
							'<input id="uploadImgName" type="hidden" name=fileName />'+
						'</form>'+
					"</td>"+
				"</tr>"+
				"<tr>"+
					"<td class=label>Description:</td>"+
					"<td valign=top><textarea style='width: 295px; height: 100px;'></textarea>*</td>"+
				"</tr>"+
				"<tr>"+
					"<td class=label>Confirm a user is over 18:</td>"+
					"<td><input type=checkbox id='over18' /></td>"+
				"</tr>"+
				"<tr>"+
					"<td colspan=2 align=right><input id='nextToQuestions' type='button' value='Next' onclick='addTargets()' /></td>"+
				"</tr>"+
			"</table>";	
	container.innerHTML = str;
}

var addQuestions = function(){
	if (isQuize) {
		var targetDiv = $("targets");
		var inputs = targetDiv.getElementsByTagName("input");
		showError("");
		var targetStr = "";
		var targetCount = targetDiv.childNodes.length;
		var tCount = 0;
		targetsArray = new Array();
		var errorText=false;
		for (var i = 1; i <= targetCount; i++) {
			var inputs = $("target" + i).getElementsByTagName("input");
			var texts=$("target" + i).getElementsByTagName("textarea");
			 
			 if(texts[0].value != ""||inputs[3].value != ""||inputs[0].value!="") 
			 {
			 	 tCount++;
			 } 
			 else
			 {
			 	break;
			 }
			if (texts[0].value != "") {
			
				targetStr += "&targetText_" + tCount + "=" + encodeURIComponent(texts[0].value);
				targetsArray.push(encodeURIComponent(texts[0].value));
				}
			else{
				errorText="Please specify text for every result";
				//isErrorOccured=true;break;
			}
				if (inputs[3].value != "") {
					targetStr += "&targetImageUrl_" + tCount + "=" + encodeURIComponent(inputs[3].value);
				}
				else
				{
					errorText="Please upload image for every result";
					//isErrorOccured=true;break;
				}
				if (inputs[0].value!="")
				 {
				 targetStr+= "&targetDesc_"+tCount+"="+encodeURIComponent(inputs[0].value);
				 }
				 else
				 {
				 	errorText="Please specify short description for every result";
					//isErrorOccured=true;break;
				 }
				
			
			
			
		}
			
		if (tCount < 2) {
			showError("You must type at least 2 results.");
			return;
		}else 
		if (errorText) {
				showError(errorText);
				return;
			}
			else
		{
			targetStr += "&targetCount=" + tCount;
			newSurvey.targets = targetStr;
		}
	}
	var str="<h1>Step 2: Add Questions & Answers</h1>"+
			"<div id=questions></div>"+
			"<input type='button' value=Next onclick=finalStep() class=button ></input>";	
	questionIndex = 0;				
	container.innerHTML = str;
	showError("");
	addQuestion(true,targetsArray);
	addQuestion(false);
	addQuestion(false);
	addQuestion(false);
}

var addTargets=function(){
	var inputs = document.getElementsByTagName("input");
	var desc = document.getElementsByTagName("textarea")[0].value;
	var srv_title = document.getElementById("srv_title").value;//inputs[0].value
	if (desc == "" || desc == "") {
		showError("Please specify description.");
		return;
	}
	else 
		if (desc.length > 254) {
			showError("Description is too long.");
			return;
		}
		else if(!newSurvey.image||newSurvey.image=="noimage.jpg")
		{
			showError("Please upload image");
			return;
		}
		else if(srv_title=="")
		{
			showError("Please specify title");
			return;
		}
		else {
			newSurvey.title = encodeURIComponent(srv_title);
			newSurvey.over18 = document.getElementById("over18").checked ? 1 : 0; //inputs[4].checked ? 1 : 0;
			newSurvey.desc = encodeURIComponent(desc);
			
			newSurvey.type = surveyType;
		}
	
		if (isQuize) {
			var str = "<h1>Step 2: Add Results</h1>" +
			"<div id=targets></div>" +
			"<input type='button' value=Next onclick=addQuestions() class=button ></input>";
			questionIndex = 0;
			container.innerHTML = str;
			showError("");
			addTarget(true);
			addTarget(false);
			addTarget(false);
		}else{
			addQuestions();
		}
}

var addTarget=function(isFirst){
	targetIndex++;
	var targetsDiv = $("targets");
	var div = document.createElement("div");
	var str = "<table><tbody id=target"+targetIndex+">";
	if (isFirst) {
		str+="<tr><td colspan='4' align='right'><input type=button value='Add Result' onclick='addTarget()'/></td></tr>"
		str += "<tr><td>&nbsp;</td><td>Text</td><td>Short Description</td><td>Image</td></tr>";
	}
	str+=
						"<tr>"+
							"<td class=label>Result"+targetIndex+":</td>"+
							"<td><textarea 'questionInput' rows='2' cols='20'></textarea></td>"+
							"<td  valign='top'><input class='shortDesc'/></td>"+
							"<td valign='top'>"+
								"<form enctype='multipart/form-data' action='"+SERVER_URL+"Upload' method='post' "+ //"+SERVER_URL+"
									"onsubmit='return AIM.submit(this, {onStart : startTargetsUpload, onComplete : completeTargetsUpload, id : \"t"+targetIndex+"\"})'>"+
									"<input id='uploadImgTargetFile_t"+targetIndex+"' type='file' name='image' />"+
									"<input style='margin-left:6px;' id='uploadImg_t"+targetIndex+"' type='submit' value='Upload' />"+
									"<input id='uploadImgTName_t"+targetIndex+"'type='hidden' name=fileName />"+
								"</form>"+
						   "</td>"+
						   "<td id='targetImage_t"+targetIndex+"' style='display: none'><img class=preview src='"+SURVEY_IMG_URL+"noimage.jpg' /></td>";
//		 if(isFirst) str += "<td valign='top'><input type=button value='Add Result' onclick='addTarget()'/></td>";
				   
				    str+="</tr></table>";
	div.innerHTML = str; 				
	targetsDiv.appendChild(div);
	adjustHeight();
}

var createTargetOption=function(currentAnswerIndex)
{
	var targetOptions="";
	var selectedIndex=currentAnswerIndex%targetsArray.length;
	if(targetsArray){
		for(var j=0;j<targetsArray.length;j++){
			targetOptions+="<option value='"+j+"'"+(selectedIndex==j?" selected='selected'":"")+"'>";
			targetOptions+=targetsArray[j];
			targetOptions+="</option>"
		}
	}
	return targetOptions;
}
var addQuestion = function(isFirst){
	questionIndex++;
	var targetOptions="";
	var targetsSelect="";
//	if(targetsArray){
//		for(var i=0;i<targetsArray.length;i++){
//			targetOptions+="<option value='"+i+"'>";
//			targetOptions+=targetsArray[i];
//			targetOptions+="</option>"
//		}
//	}
	var questionsDiv = $("questions");
	var div = document.createElement("div");
	var str = "<table><tbody id=question"+questionIndex+">"+
						"<tr>"+
							"<td class=label>Question"+questionIndex+":</td>"+
							"<td><input class='questionInput' /></td>"+
							"<td class='imgUploadTd'>"+
								"<form enctype='multipart/form-data' action='"+SERVER_URL+"Upload' method='post' "+ //"+SERVER_URL+"
									"onsubmit='return AIM.submit(this, {onStart : startQuestionsUpload, onComplete : completeQuestionsUpload, id : \"q"+questionIndex+"\"})'>"+
									"<input id='uploadImgQuestionFile_q"+questionIndex+"' type='file' name='image' />"+
									"<input style='margin-left:6px;' id='uploadImg_q"+questionIndex+"' type='submit' value='Upload' />"+
									"<input id='uploadImgQName_q"+questionIndex+"'+ type='hidden' name=fileName />"+
								"</form>"+
						   "</td>"+
						   "<td id='questionImage_q"+questionIndex+"' style='display: none'><img class=preview src='"+SURVEY_IMG_URL+"noimage.jpg' /></td>";
		 if(isFirst) str += "<td><input type=button value='Add Question' onclick='addQuestion()'/></td>";
				  if (isQuize){
					targetOptions=createTargetOption(answerIndex+1);
					targetsSelect=targetOptions!=""?"<select name='targets' id='targets_"+questionIndex+"_1'>"+targetOptions+"</select>":"";
				  }
				   str+="</tr>"+
						"<tr>"+
							"<td class=label>Answers:</td>"+
							"<td><input class='questionInput' id='answer_a"+(answerIndex+1)+"' /></td>"+
							"<td class='imgUploadTd'>"+
								"<form enctype='multipart/form-data' action='"+SERVER_URL+"Upload' method='post' "+ //"+SERVER_URL+"
									"onsubmit='return AIM.submit(this, {onStart : startAnswerUpload, onComplete : completeAnswerUpload, id : \"a"+(answerIndex+1)+"\"})'>"+
									"<input id='uploadImgAnswerFile_a"+(answerIndex+1)+"' type='file' name='image' />"+
									"<input style='margin-left:6px;' id='uploadImg_a"+(answerIndex+1)+"' type='submit' value='Upload' />"+
									"<input id='uploadImgAName_a"+(answerIndex+1)+"' type='hidden' name=fileName />"+
								"</form>"+
						   "</td>"+
						   "<td id='answerImg_a"+(answerIndex+1)+"'style='display: none'><img class=preview src='"+SURVEY_IMG_URL+"noimage.jpg' /></td>"+
						"<td id='answerTarget_t"+(answerIndex+1)+"'>"+targetsSelect+"</td>"+
						"</tr>"+
						"<tr>"+
							"<td></td>"+
							"<td><input class='questionInput'  id='answer_a"+(answerIndex+2)+"'/></td>"+
							"<td class='imgUploadTd'>"+
								"<form enctype='multipart/form-data' action='"+SERVER_URL+"Upload' method='post' "+//"+SERVER_URL+"
									"onsubmit='return AIM.submit(this, {onStart : startAnswerUpload, onComplete : completeAnswerUpload, id : \"a"+(answerIndex+2)+"\"})'>"+
									"<input id='uploadImgAnswerFile_a"+(answerIndex+2)+"' type='file' name='image' />"+
									"<input style='margin-left:6px;' id='uploadImg_a"+(answerIndex+2)+"' type='submit' value='Upload' />"+
									"<input id='uploadImgAName_a"+(answerIndex+2)+"' type='hidden' name=fileName />"+
								"</form>"+
						   "</td>"+
						   "<td id='answerImg_a"+(answerIndex+2)+"' style='display: none'><img class=preview src='"+SURVEY_IMG_URL+"noimage.jpg' /></td>";
						
						if (isQuize){
							targetOptions=createTargetOption(answerIndex+2);
							targetsSelect=targetOptions!=""?"<select name='targets' id='targets_"+questionIndex+"_2'>"+targetOptions+"</select>":"";
						}
						str+="<td id='answerTarget_t"+(answerIndex+2)+"'>"+targetsSelect+"</td>"+
						"</tr>"+
						"<tr>"+
							"<td></td>"+
							"<td><input type=button value='Add Answer' onclick=addAnswer("+questionIndex+") /></td>"+
						"</tr>"+
					"</table>";
	div.innerHTML = str; 				
	questionsDiv.appendChild(div);
	answerIndex+=2;
	adjustHeight();
}

var addAnswer = function(questionId){
	answerIndex ++;
	var table = $("question"+questionId);
	var row = document.createElement("tr");
	var cell1 = document.createElement("td");
	var cell2 = document.createElement("td");
	var cell3 = document.createElement("td");
	var cell4 = document.createElement("td");
	var cell5=document.createElement("td");
	cell4.style.display = "none";
	cell2.innerHTML = "<input class='questionInput'  id='answer_a"+answerIndex+"'/>";
	cell3.className = 'imgUploadTd';
	cell3.innerHTML = "<form enctype='multipart/form-data' action='"+SERVER_URL+"Upload' method='post' "+
									"onsubmit='return AIM.submit(this, {onStart : startAnswerUpload, onComplete : completeAnswerUpload, id : \"a"+answerIndex+"\"})'>"+
									"<input id='uploadImgAnswerFile_a"+answerIndex+"' type='file' name='image' />"+
									"<input style='margin-left:6px;' id='uploadImg_a"+answerIndex+"' type='submit' value='Upload' />"+
									"<input id='uploadImgAName_a"+answerIndex+"' type='hidden' name=fileName />"+
					  "</form>";
	cell4.id = "answerImg_a"+answerIndex;
	cell4.innerHTML = "<img class=preview src='"+SURVEY_IMG_URL+"noimage.jpg' />";
	row.appendChild(cell1);
	row.appendChild(cell2);
	row.appendChild(cell3);
	row.appendChild(cell4);
	if(targetsArray)
	{
		var selectedIndex=answerIndex%targetsArray.length;
		var targetOptions="";
		var targetsCell=document.createElement("select");
		targetsCell.name="targets_"+questionId+"_"+answerIndex;
		for(var j=0;j<targetsArray.length;j++)
		{
			targetOptions+="<option value='"+j+(selectedIndex==j?" selected='selected'":"")+"'>";
			targetOptions+=targetsArray[j];
			targetOptions+="</option>"
		}
		targetOptions.innerHTML+="</select>"
		targetsCell.innerHTML=targetOptions;
		cell5.appendChild(targetsCell);
		row.appendChild(cell5);
	}
	table.insertBefore(row, table.lastChild);
	adjustHeight();
}

var finalStep = function(){
	var questionsDiv = $("questions");
	var inputs = questionsDiv.getElementsByTagName("input");
	showError("");
	var questionStr = "";
	var questionCount = questionsDiv.childNodes.length;
	var qCount = 0;
	var aCount = 0;
	for (var i=1; i<=questionCount;i++){
		var inputs = $("question"+i).getElementsByTagName("input");
		var selects;//=$("question"+i).getElementsByTagName("select");
		if ((inputs[0].value != "") || (inputs[3].value != "") ){
			qCount++;
			questionStr += "&questionText_"+qCount+"="+encodeURIComponent(inputs[0].value);
			if(inputs[3].value != "") {
				questionStr += "&questionImageUrl_"+qCount+"="+encodeURIComponent(inputs[3].value);
			}
			aCount = 0;
			var id = "";
			for (var j=4;j<inputs.length;j++){
				if ((inputs[j].type == "text" && inputs[j].value != "") || (inputs[j].type == "hidden" && inputs[j].value != "")){
					var answerId = (inputs[j].id).substring((inputs[j].id).indexOf("_")+1, (inputs[j].id).length);
					if(answerId != id) {
						aCount++;
						id = answerId;
					}
					selects=document.getElementById("targets_"+qCount+"_"+aCount);
					if(selects)
						questionStr +="&answerTarget_"+qCount+"_"+aCount+"="+encodeURIComponent(selects.options[selects.selectedIndex].value);
					
					if(inputs[j].type == "text" && inputs[j].value != "") {
						questionStr += "&answerText_"+qCount+"_"+aCount+"="+encodeURIComponent(inputs[j].value);
					}
					if(inputs[j].type == "hidden" && inputs[j].value != "") {
						questionStr += "&answerImageUrl_"+qCount+"_"+aCount+"="+encodeURIComponent(inputs[j].value);
					}
				}
			}
			if (aCount>=2){
				questionStr += "&answerCount_"+qCount+"="+aCount;
			}else{
				showError("Each question must have at least 2 answers.");
				return;
			}
		}
	}
	if (qCount<2){ //4
		showError("You must type at least 2 questions and 2 answers for each.");
	}else{
		questionStr += "&questionCount="+qCount;
		newSurvey.questions = questionStr;
		req_createSurvey();
	}
}

var req_createSurvey = function(){
	newSurvey.appURI = "";
	newSurvey.createApp = "0";
	if(!surveyType)  surveyType = 1;
	var data = "query=addSurvey&userId="+userId+"&title="+newSurvey.title+"&survey_type="+surveyType+
			   "&img="+newSurvey.image+"&over18="+newSurvey.over18+"&createApp="+newSurvey.createApp+
			   "&desc="+newSurvey.desc+"&url="+newSurvey.appURI+"&"+newSurvey.questions+"&"+newSurvey.targets+"&surveyType="+surveyType;
	data += "&"+getUserPostData();
	Request.sendPOST(SERVICE_URL, data, resp_createSurvey);
}

var resp_createSurvey = function(response){
	var surveyId = response.text;
	showError("");
	var surveyId = response.text;
	showError("");
	var str="<div align='center' style='margin-top:30px;font-size:14px;width:100%'>"+
			"<div style='font-weight:bold'>Thank you for creating the survey!</div>"+
			"After we review and approve the content, we will publish your survey.<br><br>"+
			"<a href='javascript:loadSurvey("+surveyId+")'><b>Now go on!!! Be the first to take the survey!!!</b></a>"+
			"</div>";
	container.innerHTML = str;
}

var showFinalNote = function(){

	var str="<div align='center' style='margin-top:30px;font-size:14px;width:100%'>"+
			"<div style='font-weight:bold'>Thank you for creating the survey!</div>"+
			"After we review and approve the content, we will publish your survey.<br><br>"+
			"<a href='javascript:loadSurvey("+surveyId+")'><b>Now go on!!! Be the first to take the survey!!!</b></a>"+
			"</div>";

	container.innerHTML = str;
}
var req_userSurveys = function(page, type){
	selectTab("userSurveys_"+type);
	var typeText = "My";
	if (type == TAKEN_SURVEYS){
		typeText = "Taken";
	}
	container.innerHTML =
	  "<div class=title>"+typeText+" "+(isQuize?"Quizzes":"Surveys")+"</div>"+
	 '<div class=usrcontent id="userSurveys"><div style="height:200px;"><div class=loading>Loading...</div></div></div>'+	
	 '<div id="ad3" style="width:728px;height:90px;overflow:hidden;"></div>'+
	 // '<div>'+getAd(3)+'</div>'+
	 "<div class=title>Active Today</div>"+
	 "<div class=content id='today'><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('adMiddle', 'ad3');

}

var resp_userSurveys = function(response){
	var userSurveys = response.data.surveys;
	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 "+(isQuize?"surveys":"quizzes")+". <a href='javascript:createSurvey()'>Create a Survey</a></h1>";
		}else if (type == TAKEN_SURVEYS){
			str = "<h1>You haven't taken any "+(isQuize?"survey":"quiz")+". <a href='javascript:getPublicSurveys()'>Click here</a> to pass a survey.</h1>";
		}
	}else{
		str+="<table cellspacing=12>";
		for (var i=0;i<userSurveys.length;i++){
			srv = userSurveys[i];
			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='"+SURVEY_IMG_URL+srv.imgUrl+"' /></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</a></div>"+
						"<div style='margin:3px 0px;'><a href='javascript:loadSurvey("+srv.id+")'>View</a></div>"+
						"<div style='margin:3px 0px;'><a href='javascript:req_getResultsForBulletin("+srv.id+",\""+srv.title+"\", \""+srv.imgUrl+"\")'>Share</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 publish = function(id){
	var data = "query=updateSurveyStatus&surveyId="+id+"&status=0&msg=";
	Request.sendPOST(SERVICE_URL, data, resp_publish);
}
var resp_publish = function(response){
	var id = response.text;
	$("publish"+id).innerHTML = "";
	var rejectMsg = $("rejectMsg"+id);
	if (rejectMsg) rejectMsg.innerHTML = "";
	var status = $("status"+id);
	status.innerHTML = "<span style='color:blue'>Approval pending</span>";
}

////////////////////////////////////// file upload /////////////////////////////////////////////////
var startUpload = function(){
	$("uploadImg").disabled = true;
	$("nextToQuestions").disabled = true;
	var fileName = $("uploadImgFile").value;
	if (fileName == ""){
		return false;
	}else{
		fileName = fileName.substring(fileName.lastIndexOf("."), fileName.length);
		newSurvey.image = (new Date()).getTime()+fileName;
		$("uploadImgName").value = newSurvey.image;
		return true;
	}
}

var completeUpload = function(){
	$("uploadImg").disabled = false;
	$("nextToQuestions").disabled = false;
	$("surveyImg").innerHTML = "<img class=preview src='"+SURVEY_IMG_URL+newSurvey.image+"' />";
}

/////////////////////////////// Upload images for questions and answers  /////////////////////////////////////////////////

var startQuestionsUpload = function(qId){
	$("uploadImg_"+qId).disabled = true;
	var fileName = $("uploadImgQuestionFile_" + qId).value;
	if (fileName == ""){
		return false;
	}else{
		fileName = fileName.substring(fileName.lastIndexOf("."), fileName.length);
		$("uploadImgQName_"+qId).value = (new Date()).getTime()+fileName;
	}
}

var completeQuestionsUpload = function(qId){
	$("uploadImg_"+qId).disabled = false;
	$("questionImage_"+qId).innerHTML = "<img class=preview src='"+SURVEY_IMG_URL+newSurvey.image+"' />";
}
var startTargetsUpload=function(tId)
{
		$("uploadImg_"+tId).disabled = true;
	var fileName = $("uploadImgTargetFile_" + tId).value;
	if (fileName == ""){
		return false;
	}else{
		fileName = fileName.substring(fileName.lastIndexOf("."), fileName.length);
		$("uploadImgTName_"+tId).value = (new Date()).getTime()+fileName;
	}
}

var completeTargetsUpload = function(qId){
	$("uploadImg_"+qId).disabled = false;
	$("targetImage_"+qId).innerHTML = "<img class=preview src='"+SURVEY_IMG_URL+newSurvey.image+"' />";
}
var startAnswerUpload = function(aId){
	$("uploadImg_"+aId).disabled = true;
	var fileName = $("uploadImgAnswerFile_"+aId).value;
	if (fileName == ""){
		return false;
	}else{
		fileName = fileName.substring(fileName.lastIndexOf("."), fileName.length);
		$("uploadImgAName_"+aId).value = (new Date()).getTime()+fileName;
	}
}

var completeAnswerUpload = function(aId){
	$("uploadImg_"+aId).disabled = false;
	$("answerImg_"+aId).innerHTML = "<img class=preview src='"+SURVEY_IMG_URL+newSurvey.image+"' />";
}

////////////////////////////// end
var AIM = {

    frame : function(c) {

        var n = 'f' + Math.floor(Math.random() * 99999);
        var d = document.createElement('DIV');
        d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\', \''+c.id+'\')"></iframe>';
        document.body.appendChild(d);

        var i = document.getElementById(n);
        if (c && typeof(c.onComplete) == 'function') {
            i.onComplete = c.onComplete;
        }

        return n;
    },

    form : function(f, name) {
        f.setAttribute('target', name);
    },

    submit : function(f, c) {
        AIM.form(f, AIM.frame(c));
        if (c && typeof(c.onStart) == 'function') {
            return c.onStart(c.id);
        } else {
            return true;
        }
    },

    loaded : function(id, qId) {
        var i = document.getElementById(id);
        if (typeof(i.onComplete) == 'function') {
            i.onComplete(qId);
        }
    }
}

///////////////////////// edit survey /////////////////////
var editSurvey = function(id){
	var srv = getUserSurveyById(id);
	var editCont = $("editCont"+id);
	if (editCont.style.display != "none"){
		editCont.style.display = "none";
	}else{
		var str = "<input value='"+srv.url+"' />"+
				  "<input style='margin-left:5px;' type=button value='Save' onclick='req_updateSurvey("+srv.id+")' />"+
				  "<input style='margin-left:5px;' type=button value='Cancel' onclick='closeEdit("+srv.id+")' />";
	    editCont.style.display = "";
	    editCont.firstChild.innerHTML = str;
	}
}

var closeEdit = function(id){
	var editCont = $("editCont"+id);
	editCont.style.display = "none";
}

var req_updateSurvey = function(id){
	var srv = getUserSurveyById(id);
	var newUrl = $("editCont"+srv.id).getElementsByTagName("input")[0].value;
	if (newUrl != srv.url){
		var data = "query=updateSurveyURL&surveyId="+id+"&url="+newUrl;
		Request.sendPOST(SERVICE_URL, data, doNothing);
		srv.url = newUrl;
	}
	closeEdit(id);
}

/////////////////////////
var fillMakerBody = function(){
	isQuize = surveyType == SURVEY_TYPE_QUIZZ;
	APP_NAME = isQuize ? "Quiz" : "Survey";
	APP_NAMES = isQuize ? "Quizzes" : "Surveys";
	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");
	allContent = $("allContent");
	var is_quiz=(surveyType!='undefined'&& surveyType==SURVEY_TYPE_QUIZZ);
	allContent.innerHTML = 
	'<div id="surveyHeader" style="margin-bottom:10px;"></div>'+
	//'<div style="margin-left:5px;margin-bottom:10px;color:#EE656C;font-size:17px;">Great News!!! Now you can send <a style="color:#708D33" href="javascript:req_getUserMsgs()">SPECIAL GIFTS</a> to your friends and people you share opinion with. <a style="color:#708D33" href="javascript:req_getUserMsgs()">Check out!!!</a></div>'+
	'<iframe src="'+SERVER_URL+'survey_to_promote.html" style="border:0px;" width="840" height="100" scrolling="no" frameborder="0"></iframe>'+
	'<table cellspacing=0 cellpadding=0>'+
		'<tr class="tabs" id="tabContainer">'+
			'<td name=home id ="home"><a href="javascript:home()">Home</a></td>'+
			'<td name=userSurveys_1 id ="userSurveys_1"><a href="javascript:req_userSurveys(1, 1)">Taken '+APP_NAMES+'</a></td>'+
			'<td name=userSurveys_2 id="userSurveys_2" style="border-width:1px;"><a class=lastTab href="javascript:req_userSurveys(1, 2)">My '+APP_NAMES+'</a></td>'+
			'<td name=take id="take_survey" style="display:none"><a href="javascript:req_getSurvey()">Take '+APP_NAME+'</a></td>'+
			'<td name=results id="srvResults" style="display:none"><a href="javascript:req_getResults()">Results</a></td>'+
			'<td name=inbox id="srvInbox"><a href="javascript:req_getUserMsgs()">Funbox</a></td>'+
			'<td name=invite id="srvInvite"><a href="javascript:showMakerInviteTab()">Invite Friends</a></td>'+
			'<td name=public><a href="javascript:getPublicSurveys()">Fun '+APP_NAMES+'</a></td>'+
			'<td name=users id="srvUsers"><a href="javascript:getUsers()">Cool People</a></td>'+
			'<td name=create id ="srvCreate"><a href="javascript:createSurvey()">Create '+(is_quiz?'Quiz':'Survey')+'</a></td>'+
			'<td name=quizcreate  id ="quizCreate"><a target="_blank" href="'+(is_quiz?MAKER_URL:QUIZ_MAKER_URL)+'">Create '+(is_quiz?'Survey':'Quiz')+'</a></td>'+
		'<td name=quizcreate  id ="quizCreate"><a target="_blank" href="'+TEST_MAKER_URL+'">Create Test</a></td>'+
		'</tr>'+
	'</table>'+
	'<div style="margin-top:10px;width:728px;height:90px;overflow:hidden;" id="adTop"></div>'+
	//'<div style="margin-top:5px;" id="adDiv1">'+getAd(1)+'</div>'+
	'<table class=container><tr>'+
		'<td width=75% valign=top>'+
			'<div id=domain></div>'+
			'<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="adMiddle"></div>'+
			'<div style="margin-top:5px;width:728px;height:90px;overflow:hidden;" id="adBottom"></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 id="adBottom">'+
	'<div><a target=_blank href="http://monitis.com/publicReports/report_37.html" style="color:#4DB3FF; font-size:15px;">'+
	'Uptime By Mon<span style="color:#6EFF00">i</span><span style="color:#FFAC00">t</span><span style="color:#FF0300">i</span>s</a></div>';
	container = $("container");
	errorDiv = $("error");
	setInterval(refreshIframe, 45000);
	getUser();
	
	try{
		applyAds('adDivTop', 'adTop');
		applyAds('adDivMiddle', 'adMiddle');
		applyAds('adDivBottom', 'adBottom');
	    sr_gof();
	 }catch(ex){
		var adStr = '<iframe frameborder="0" src = "http://adturns.com/ad.php?c=67" width="728" height="90" border="0" style="border: none; overflow: hidden" frameborder="0"  scrolling="no" ></iframe>';
		$('adDivTop').innerHTML = adStr;
		$('adDivBottom').innerHTML = adStr;
	 }
	    
	    req_channel_statistics("canvas");
}


var fillQuizMakerBody = function(){

isQuize = surveyType == SURVEY_TYPE_QUIZZ;
APP_NAME = isQuize ? "Quiz" : "Survey";
APP_NAMES = isQuize ? "Quizzes" : "Surveys";
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");
allContent = $("allContent");

allContent.innerHTML = 
'<div id="surveyHeader" style="margin-bottom:10px;"></div>'+
'<table id="tableTabs" cellspacing=0 cellpadding=0 align="right">'+
	'<tr class="tabs" id="tabContainer">'+
		'<td name=home id ="home"><a href="javascript:home()">Home</a></td>'+
		'<td name=userSurveys_1 id ="userSurveys_1"><a href="javascript:req_userSurveys(1, 1)">Taken '+APP_NAMES+'</a></td>'+
		'<td name=userSurveys_2 id="userSurveys_2" ><a class=lastTab href="javascript:req_userSurveys(1, 2)">My '+APP_NAMES+'</a></td>'+
		'<td name=take id="take_survey" style="display:none"><a href="javascript:req_getSurvey()">Take '+APP_NAME+'</a></td>'+
		'<td name=results id="srvResults" style="display:none"><a href="javascript:req_getResults()">Results</a></td>'+
		'<td name=inbox id="srvInbox"><a href="javascript:req_getUserMsgs()">Funbox</a></td>'+
		'<td name=invite id="srvInvite"><a href="javascript:showMakerInviteTab()">Invite Friends</a></td>'+
		'<td name=public><a href="javascript:getPublicSurveys()">Fun '+APP_NAMES+'</a></td>'+
		'<td name=users id="srvUsers"><a href="javascript:getUsers()">Cool People</a></td>'+
		'<td name=create id ="srvCreate"><a href="javascript:createSurvey()">Create '+APP_NAME+'</a></td>'+
		'<td name=quizcreate id ="quizCreate"><a target="_blank" href="'+MAKER_URL+'">Create Survey'+'</a></td>'+
	'</tr>'+
'</table>'+
'<table id="subTabsTable"cellspacing=0 cellpadding=0 width=100%>'+
'<tr>'+
	'<td>'+
		'<table width=100% cellspacing=0 cellpadding=0><tr>'+
			'<td>'+
				'<img src="'+SERVER_URL+'img/midd_left.png" />'+
			'</td>'+
			'<td width=100% height=30px  style="background:url('+SERVER_URL+'img/andTab.png) repeat-x;">'+
				'<div id="subTabsDiv">'+
				
				'</div>'+
			'</td>'+
			'<td>'+
				'<img src="'+SERVER_URL+'img/midd_right.png" />'+
			'</td>'+
		'</tr></table>'+
	'</td>'+
'</tr>'+
'<tr><td>'+
'<table  cellspacing=0 cellpadding=2px><tr>'+
	'<td width=10px style="background:url('+SERVER_URL+'img/border_left.png)"></td>'+
	'<td width=99% style="background:url('+SERVER_URL+'img/border_midd.png)"></td>'+
	'<td width=10px style="background:url('+SERVER_URL+'img/border_right.png)"></td>'+
'</tr></table>'+	
'</td></tr>'+
'</table>'+
'<div style="margin-top:5px;width:728px;height:90px;overflow:hidden;" id="adTop"></div>'+

//'<div style="margin-top:5px;" id="adDiv1">'+getAd(1)+'</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>'+
		'<div style="margin-top:5px;width:728px;height:90px;overflow:hidden;" id="adMiddle"></div>'+
		'<div style="margin-top:5px;width:728px;height:90px;overflow:hidden;" id="adBottom"></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>';

	container = $("container");
	errorDiv = $("error");
	setInterval(refreshIframe, 45000);
	getUser();
	
try{
	applyAds('adDivTop', 'adTop');
	applyAds('adDivMiddle','adMiddle');
	applyAds('adDivBottom','adBottom');
	sr_gof();
}catch(ex){
				var adStr = '<iframe frameborder="0" src = "http://adturns.com/ad.php?c=67" width="728" height="90" border="0" style="border: none; overflow: hidden" frameborder="0"  scrolling="no" ></iframe>';
				$('adTop').innerHTML = adStr;
				$('adBottom').innerHTML = adStr;
		}
	
	req_channel_statistics("canvas");

}


var hideMakerTabs = function(msg) {
	
	$("userSurveys_1").style.display = "none";
	$("userSurveys_2").style.display = "none";
	$("srvInvite").style.display = "none";
	$("srvCreate").style.display = "none";
	$("srvInbox").style.display = "none";
	$("srvUsers").style.border = "1px solid #898989";
	/*
	initMaker();
	
	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: 70px;' src='"+SERVER_URL+"img/add_app.jpg' />";
	gadgets.window.adjustHeight();
}

var postMakerInvite = function(){
	var subject;
	var content;
	subject = "Matchmaking SURVEYS";
	content = "Have you seen the amazing <a href='"+surveyURL+"'>Matchmaking SURVEYS! </a> application? "+
	"There are so many surveys and you can also <a href='"+surveyURL+"'>create</a> yours. "+
	"<a href='"+surveyURL+"'>Pass</a> the surveys and <a href='"+surveyURL+"'>compare</a> your results with me and other friends."+
	"<br><a href='"+surveyURL+"'><img src='"+surveyImgUrl+"' >Pass "+surveyTitle+" now!!!</a>";
	postTo_(subject, 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;' id=friendList></div>";
    container.innerHTML = str;
    initFriend();
   // Invite.show(id, title, img);
} 

var recently;
var giftGivers;
var popularPlayers;

var home = function(){
	selectTab("home");
	/*if (typeof newDesign != 'undefined' && newDesign) {
//		var subStr = 
//	'<table style="margin-left:20px" cellspacing=0 cellpadding=0><tr>'+
//		'<td>'+
//			'<a style="color:#6D60B0" href="swd"> Active Today <a/> | '+
//		'</td>'+
//		'<td>'+
//			'<a style="color:#6D60B0" href="ef"> Jast Taken  <a/> | '+
//		'</td>'+
//		'<td>'+
//			'<a style="color:#6D60B0" href="ef"> Jast Created <a/> | '+
//		'</td>'+
//		'<td>'+
//			'<a style="color:#6D60B0" href="ef"> Most Popular <a/> | '+
//		'</td>'+
//		'<td>'+
//			'<a style="color:#6D60B0" href="ef"> View All <a/>  '+
//		'</td>'+
//	'</tr></table>';
//	$("subTabsDiv").innerHTML = subStr;
	var str = "<table cellspacing=0 cellpadding=2 style='margin-top:-3px' width=100%><tr>"+
		"<td valign=top>"+
		"<div class=title >Recently Taken</div>"+
		"<div class=usrcontent_ ><div id='just_taken'><div class=loading>Loading...</div></div></div>"+
		//'<div >'+getAd(3)+'</div>'+	
		'</td><td valign=top>'+
		"<div class=title >Popular Surveys</div>"+
		"<div class=content id='popular'><div class=loading>Loading...</div></div>"+
		"</td></tr>"+
		"<tr><td colspan='2'><div >"+getAd(4)+"</div></td></tr>"+
		"<tr><td valign=top>"+
		"<div class=title >Generous Giftgivers</div>"+
		"<div class=usrcontent_ ><div id='giftGivers'><div class=loading>Loading...</div></div></div>"+
		//'<div >'+getAd(5)+'</div>'+	
		'</td><td valign=top width=50%>'+
		"<div class=title >Most Popular Giftreceivers</div>"+
		"<div class=usrcontent_><div id='popularPlayers'><div class=loading>Loading...</div></div></div>"+
		
		"</td>"+
		"</tr></batle>";

	}
	else {
	*/
	var str = "<div class=title>Recently Taken</div>" +
	"<div class=usrcontent_ ><div id='just_taken'><div class=loading>Loading...</div></div></div>" +
	'<div id="ad3" style="width:728px;height:90px;overflow:hidden;">' +
	//getAd(3) +
	'</div>' +
	"<div class=title>Recently Popular Surveys</div>" +
	"<div class=content id='today'><div class=loading>Loading...</div></div>"+
	'<div id="ad5"  style="width:728px;height:90px;overflow:hidden;">' +
	//getAd(5) +
	'</div>' +
	"<div class=title>New Surveys</div>" +
	"<div class=content id='just_created'><div class=loading>Loading...</div></div>";
	newDesign = false;
	//}
	container.innerHTML = str;
	popularPage = 1;
	todayPage = 1;
	recentlyCreatedPage = 1;
	//Request.sendGET(SERVICE_URL + "/firstPage/" + APP_COUNT + "/" + RECEIVERS_COUNT+"/"+newDesign, resp_getFirstPage);
	Request.sendGET(SERVICE_URL + "/firstPage/" + APP_COUNT + "/" + RECEIVERS_COUNT+"/"+false, resp_getFirstPage);
	

////////////	document.getElementById("allContent").innerHTML += "<input type='button' onclick='applyMiddleAd(\"adDivMiddle\",\"ad3\");applyMiddleAd(\"adDivMiddle\",\"ad5\")'  value='applyMiddleAd' />";
	applyMiddleAd('adMiddle', 'ad3');
	applyMiddleAd('adMiddle','ad5');

}
var closeMsgDiv = function(){
	var node = $("msgDiv");
	node.parentNode.removeChild(node);
}

var resp_getFirstPage = function(response){
	var colCount=5;
	var surveyColCount = 3;
	var smileColCount=7;

	/*if(typeof newDesign!='undefined'&&newDesign){
		colCount=2;
		surveyColCount=2;
		smileColCount=4;
		RECEIVERS_COUNT=6;
	
		var data = response.data;
		var recentlyData = data.recently;
		recently = new Paging("recently", recentlyData.users.length, "", recentlyData, "just_taken", null ,colCount,smileColCount);
		var str = getSurveysHTML(data.popular, "req_getPopularSurveys", "popularSrv1", null, 2,surveyColCount);
		$("popular").innerHTML = "<div id=popularSrv1>"+str+"</div>";
		var giftGiversData = data.giftGivers;
		giftGivers = new Paging("giftGivers", giftGiversData.users.length, SERVICE_URL+"/giftGivers/"+RECEIVERS_COUNT, giftGiversData, "giftGivers",null,colCount,smileColCount);
		var popularPlayersData = data.popularPlayers;
		popularPlayers = new Paging("popularPlayers", popularPlayersData.users.length, SERVICE_URL+"/popularplayers/"+RECEIVERS_COUNT, popularPlayersData, "popularPlayers",null,colCount,smileColCount);
		var refreshData = setInterval( "refreshRecentlyData()", 20000 );
	}else{*/
	
		var data = response.data;
		var recentlyData = data.recently;
		if(recentlyData.users != null) recently = new Paging("recently", recentlyData.users.length, "", recentlyData, "just_taken", null ,colCount,smileColCount);
		var str = getSurveysHTML(data.todaySurveys, "req_getTodaySurveys", "todaySrv1", null, 2,surveyColCount);
		$("today").innerHTML = "<div id=todaySrv1>"+str+"</div>";
		var str = getSurveysHTML(data.newSurveys, "req_getRecentlyCreatedSurveys", "recentSrv1", null, 2,surveyColCount);
		$("just_created").innerHTML = "<div id=recentSrv1>"+str+"</div>";
	//}
}
var timesSent = 0;
var refreshRecentlyData = function(){
	var recentlyDiv = $("just_taken");
	if(recentlyDiv && timesSent<4){
		var callback=selectedTab=="home"?resp_getRecentlyTakenMaker:resp_getRecently;
		Request.sendGET(SERVICE_URL+"/getRecentlyTaken/"+Math.random(), callback);
		timesSent++;
	}
}

var resp_getRecentlyTakenMaker = function(response){
	var recentlyData = response.data.recently;
	var recently = new Paging("recently", recentlyData.users.length, "", recentlyData, "just_taken",null,typeof newDesign!='undefined'&&newDesign?2:4,typeof newDesign!='undefined'&&newDesign?4:7);
}

var totalLikeMe;
var curSrvPage = 1;
var postResults = function(url, title, imgUrl, total, msgCount){
	var subject = title;
	imgUrl = SURVEY_IMG_URL+imgUrl;
	var content = "Come on, join me and play <a href='"+url+"'>"+title+"</a>. "+
				  "I have got "+total+" people like me, "+msgCount+" emoticons and gifs."+
				  "<a style='float:left' href='"+url+"'><img src='"+imgUrl+"' /></a>";
	postTo_(subject, content, user, "BULLETINS");
}


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){
		return;
	}
	else if (response.text == ""){
		loadSurvey(surveyId);
	}
	else{
		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();
	}
}
