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 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 ADS_DATA = {};
var allowNotExactMatch = true;
var senderTypeId = 1;
var DATA;
var giftUrl = new Array();
var chooseSurveyStr=function(style)
{
	var str= typeof isQuize != "undefined" && isQuize ? "quiz" : "survey";
	switch(style)
	{
		case "upperCase": str=typeof isQuize != "undefined" && isQuize?"QUIZ":"SURVEY";break;
		case "startUpperCase": str=typeof isQuize != "undefined" && isQuize?"Quiz" :"Survey"; break;
		default:
	}
	return str;
}

var AD_SURVEYS = [
					  {url: MAKER_URL,
					   imgUrl: "logo.gif",
					   title: "Make a Survey"
					   }
					 ];
					 
//var isSuperApp = false;
var inviteMessage = null;
var surveyType;
var clearInt;

var init = function(){	
	try{
		inviteMessage = opensocial.newMessage("Let's play [app]. I want to compare our results.");
	}catch(ex){
		
	}
	SERVICE_URL = SERVICE_URL+"/"+SURVEY_TYPE_SURVEY; 
	req_getAdsData();
	req_getRightBar();

	if (userId == ADMIN_USER || userRegion == "California" || isCityFromAllowedList(userCity)){
		req_showDdomainOrNot();
	}
}

var req_showDdomainOrNot = function(){
	Request.sendGET(DOMAIN_SERVICE_URL+"/show/"+userId, resp_showDdomainOrNot);
}
var domains = [];
var resp_showDdomainOrNot = function(response){
	var data = response.data;
	if (data.allow == true && userAge >= parseInt(data.minAge) && userAge <= parseInt(data.maxAge)){
		if (userId == ADMIN_USER) profile = "464756567";
		var profile = replaceAll(userProfile.substring(23, userProfile.length), "_", "-");
		if (isNaN(profile)){
			Request.sendGET("http://aptdomain.name/check/"+profile, resp_checkDomainAvail);
		}
		/* domains[0] = "sdasd";
		domains[1] = "sdasd";
		resp_checkDomainAvail(); */
	}
}

var resp_checkDomainAvail = function(response){
	domains = eval("("+response.text+")");
	if (domains.length == 0) return;
	var str = "<div class=domain>"+
	"<div style='color:red; margin-bottom:10px;' id=domainError></div>"+
	"<b>Congratulations "+userName+" !!!</b>Get your own personal URL FREE!<br><br>";
	if (domains.length > 1){
		str += "Select a URL bellow and we will email you access details<br><br>"; 
		for (var i=0; i<domains.length;i++){
			str += "<div><input value='"+domains[i]+"' type=radio name=url><b>"+domains[i]+"</b></div>";
		}
	}else{
		str += "<b>"+domains[0]+"</b> URL is Available.";
	}
	str += "<br><br><b>Use this URL as your life long Internet address!</b>";
	str += "<br><br><input id=email ><input style='margin-left:10px' type=button onclick='req_registerDomain()' value='Email Me My URL'>";
	str += "<br><br><i>This is incredible offer courtesy of Aptdomain.com and"+ chooseSurveyStr("upperCase")+"S! Please note that overall process will take around 24 hours before your new URL will be available and it is FREE.</i>";
	str += "</div>";
	$("domain").innerHTML = str;
}
var pageSearch;
var req_surveybytitle = function(nextPage){
	title = $("textsearch").value;
	if(title == ""){	
		return;
	}
	if (nextPage == 1){
		pageSearch = 1;
		$("searchsurvey").innerHTML = "<div id=searchSrv1><div><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>";
		Request.sendGET(SERVICE_URL+"/searchbytitle/"+ encodeURIComponent(title)+"/15/1", resp_surveybytitle);
	}else{
		pageSearch = nextPage;
		if ($("searchSrv"+nextPage)){
			$("searchSrv"+nextPage).style.display = "";
			$("searchSrv"+(nextPage-1)).style.display = "none";
		}else{
			var height = $("searchSrv"+(pageSearch-1)).offsetHeight;
			$("searchSrv"+(pageSearch-1)).style.display = "none";
			$("searchsurvey").innerHTML += "<div style='height:"+height+"px;' id=searchSrv"+pageSearch+">Loading...</div>";
			Request.sendGET(SERVICE_URL+"/searchbytitle/"+encodeURIComponent(title)+"/12/"+pageSearch, resp_surveybytitle);
		}
	}
}

var resp_surveybytitle = function(response){
    var data = null;
	if(response != undefined ){  		//response.rc == 200
		data = response.data;
		if (data.surveys.length>0){
			var prevId = pageSearch>1 ? "searchSrv"+(pageSearch-1) : null;
			var str = getSurveysHTML(data, "req_surveybytitle", "searchSrv"+pageSearch,prevId, pageSearch+1);
		$("searchSrv"+pageSearch).innerHTML = str;
	}else{
		$("searchSrv"+pageSearch).innerHTML = "<h1>No results to display</h1>";
	}
	gadgets.window.adjustHeight();
	}else{
		$("searchSrv"+pageSearch).innerHTML = "<h1>HTTP/1.1 502 Bad Gateway. Try Again </h1>";
	}
	
}

var mailFilter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

var req_registerDomain = function(){
	var email = $("email").value;
	if (email == "" || !mailFilter.test(email)){
		$("domainError").innerHTML = "Email is not valid";
	}else{
		var url = "";
		if (domains.length>1){
			var inputs = $("domain").getElementsByTagName("input");
			for (var i=0;i<inputs.length;i++){
				if (inputs[i].type == "radio" && inputs[i].checked){
					url = inputs[i].value;
				}
			}
		}else{
			url = domains[0];
		}
		if (url != ""){
			if(!surveyType)  surveyType = 1;
			var data = getUserPostData()+"&email="+email+"&url="+encodeURIComponent("http://"+url)+"&query=adduser";
			data+="&surveyId="+surveyId+"&surveyType="+surveyType;
			Request.sendPOST(DOMAIN_SERVICE_URL, data,  resp_registerDomain);
			$("domainError").innerHTML = "";
		}else{
			$("domainError").innerHTML = "You haven't selected a url";
		}
	}
}

var resp_registerDomain = function(response){
	$("domain").innerHTML = "<b style='color:red;'>An email with url was sent to you!!!</b>";
}

var req_getRightBar = function(){
	Request.sendGET(SERVICE_URL+"/surveys_rb", resp_getRightBar);
	req_getRecentlyTaken();
	clearInt = setInterval(req_getRecentlyTaken, 20000);
}

var req_getAdsData = function(){
	Request.sendGET(SERVICE_URL+"/ad/"+userId+"/"+(isSuperApp?1:0), resp_getAdsData);
}

var timesRefreshed = 0;

var req_getRecentlyTaken = function(mandatory){
	if (timesRefreshed < 6  || mandatory){
		Request.sendGET(SERVICE_URL+"/getRecentlyTaken", resp_getRecentlyTaken);
		timesRefreshed++;
	}
}

var nextURL = null;
var nextURLs = [];

var resp_getRightBar = function(response){
	var data = response.data;
	if(typeof data !="undefined"){
		$("popular_rb").innerHTML = getRightBarSurveysHTML(data.popular);
		$("recent_rb").innerHTML = getRightBarSurveysHTML(data.recent);
		$("today_rb").innerHTML = getRightBarSurveysHTML(data.today);
		gadgets.window.adjustHeight();
	}
}

var userkey = "";
var resp_getAdsData = function(response){
	var data = response.data;
    if(typeof data != "undefined"){
	ADS_DATA = data.ads;
	for (var i=0; i<data.surveys.length;i++){
		if (data.surveys[i].id != surveyId){
			if (!(isSuperApp && data.surveys[i].url.indexOf("appId=101193")>0)){
				AD_SURVEYS[AD_SURVEYS.length] = data.surveys[i];
			}
		}
	}
	userkey = data.userkey;
    }
	//  $("adDiv2").innerHTML = getAd(2);
   //	try{loadMakerFirstTab();}catch(ex){req_getSurvey();}
	if(isSuperApp){
		loadMakerFirstTab();
	}else{
		req_getSurvey();
	}
		
    
}

var resp_getRecentlyTaken = function(response){

	var just_taken_rb = $("just_taken_rb");
	if(just_taken_rb != null &&   response.data != null){
		var str = "";
		
		var data = response.data.recently.users;
		var obj;
		if(data != null && data.length >0){
			for(var i=0;i<data.length && i<10;i++){
				obj = data[i];
				var link = (surveyType == SURVEY_TYPE_QUIZZ ? QUIZ_MAKER_URL : MAKER_URL)+"&appParams=%7B%22surveyId%22%3A"+obj.id+"%7D";
				//var link = surveyType == SURVEY_TYPE_QUIZZ ? QUIZ_MAKER_URL+"&appParams=%7B%22surveyId%22%3A"+obj.id+"%7D" : obj.url;
				//var link = obj.url;
				var target = "target=_blank";
				if (isSuperApp || link == null || link.indexOf("null")>0){
					link = "javascript:loadSurvey("+obj.id+")";
					target = "";
				}
				str +="<table><tr>"+
							"<td><img width=25px height=25px src='"+obj.user.thumbnail+"' /></td>"+
							"<td><a "+target+" href='"+link+"' >"+obj.title+"</a></td>"+
							"<tr><td colspan=2><a style='font-weight:normal' href='"+obj.user.profile+"'>"+obj.user.name+"</a></td></tr>"+
					  "</tr></table>";
				nextURLs[nextURLs.length] = link;
			}
		}
		str += "<div style='margin:5px 0px;'><a href='javascript:req_getRecentlyTaken(true)'>Refresh</a></div>";
		just_taken_rb.innerHTML = str;
	}else{
		clearInterval(clearInt);
	}
}

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{
		try{
			hideMakerTabs(msg);
		}catch(ex){
			hideTabs(msg);
		}
	}
}

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;
	if (isSuperApp){
		$("surveyHeader").innerHTML =
		"<table><tr><td><img src='"+surveyImgUrl+"' style='width:150px;height:150px;'></td>"+
			"<td style='width:400px;height:150px;overflow:hidden;'><h1>"+SURVEY.title+"</h1><div class=lightGreyText >"+SURVEY.description+"</div></td>"+
		"</tr></table>";
	}
	resp_getSurvey(response);
}

var getRightBarSurveysHTML = function(surveys){
	var str = "";
	var srv;
	for(var i=0;i<surveys.length;i++){
		srv = surveys[i];
		var link = (surveyType == SURVEY_TYPE_QUIZZ ? QUIZ_MAKER_URL : MAKER_URL)+"&appParams=%7B%22surveyId%22%3A"+srv.id+"%7D";
		//var link = surveyType == SURVEY_TYPE_QUIZZ ? QUIZ_MAKER_URL+"&appParams=%7B%22surveyId%22%3A"+srv.id+"%7D" : srv.url;
		//var link = srv.url;
		var target = "target=_blank";
		if (isSuperApp || link == null || link.indexOf("null")>0){
			link = "javascript:loadSurvey("+srv.id+")";
			target = "";
		}
		str +="<table><tr>"+
					"<td><img width=25px height=25px src='"+SURVEY_IMG_URL+srv.imgUrl+"' /></td>"+
					"<td><a "+target+" href='"+link+"' >"+srv.title+"</a></td>"+
			  "</tr></table>";
		nextURLs[nextURLs.length] = link; 	  
	}
	return str;
}

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 || response == undefined){
		logError();
		return;
	}
	if (response.error){
		hideTabs("User authorization failed. Check if you are logged in and refresh the page.");
		return;
	}
	var json = response.data;
	if(false && json.popularity < 10000 && !isSuperApp){
		/*var str = "<center><a target='_blank' href='http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=101193'"+
		 			"&appParams=%7B%22surveyId%22%3A"+surveyId+"%7D'>"+
					"<img src='"+IMG_URL+"merge.png'></a></center>";
		document.body.innerHTML = str;*/
		window.location.href = MAKER_URL+"&appParams=%7B%22surveyId%22%3A"+surveyId+"%7D";
	}else{
		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(ex){}
	   	
		surveyImgUrl = SURVEY_IMG_URL+SURVEY.imgUrl;
		surveyTitle = SURVEY.title;
		IS_APPROVED = SURVEY.status != 0;
		IS_SHARED = json.data.shared;
		surveyType = json.data.survey.survey_type;
		surveyURL = isSuperApp ? getMakerUrl()+"&appParams=%7B%22surveyId%22%3A"+surveyId+"%7D" : SURVEY.url;
		isQuize = surveyType == SURVEY_TYPE_QUIZZ;
		APP_NAME = isQuize ? "Quiz" : "Survey";
		APP_NAMES = isQuize ? "Quizzes" : "Surveys";
		SERVICE_URL = SERVER_URL+"SurveyService/"+surveyType;
		if (json.hasTaken){
			$("srvResults").style.display = "";
			$("take_survey").style.display = "none";
			selectTab("results");
			req_getMsgCount();
			if(surveyType==1){
				var questions = json.data.questions;
				totalTakenCount = questions[0].totalAnswers;
				req_likeMeFirst();
				showResults(questions);
			}else if(surveyType==2){
				var targets=json.data;
			    totalTakenCount=json.data.totalCount;
				QUIZE_RESULTS=targets;
			    req_likeMeFirst();
				showResults(targets.questions);
				showQuizeResults(targets);
			}
		}else{
			if (!isSuperApp){
				$("srvResults").style.display = "none";
				$("srvCompare").style.display = "none";
			}
			$("take_survey").style.display = "";
			$("srvResults").style.display = "none";
			selectTab("take");
			takeSurvey(SURVEY_QUESTIONS, SURVEY, HAS_PROFILE_INFO);
		}
	}
}

var req_getMsgCount = function(){
	Request.sendGET(SERVICE_URL+"/userMsgCount/"+userId+"/"+surveyId, resp_getMsgCount);
}

var resp_getMsgCount = function(response){
 if(response != undefined){
	msgCount = response.data;
	if (totalLikeMe != null){
		showPostUnderLikeMe();
	}
	}
}

var showPostUnderLikeMe = function(){
	var str = "<h1 class='postLikeMe'>"+totalLikeMe+" people are like you. ";
	if(msgCount == null || msgCount == "null" || msgCount == "undefined") str+= "You've not got any emoticons and gifts.";
	else str += "You've got "+msgCount+" emoticons and gifts." ;
	
	str += "<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 "+chooseSurveyStr() +"- <a href='"+surveyURL+"'>"+surveyTitle+"</a>. Enjoy and find more people aroud!";
	var title = "New "+chooseSurveyStr()+" added "+surveyTitle;
	postTo_(title, content, user, "BULLETINS");
}

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 "+ chooseSurveyStr("upperCase")+"</a>"+
				  "<br/><br/><a target='_blank' href='"+getMakerUrl()+"'>More "+APP_NAME+"</a> | <a target='_blank' href='"+getMakerUrl()+"'>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, "+msgCount+" emoticons and gifs from them."+
				  "<a style='float:left' href='"+surveyURL+"'><img src='"+surveyImgUrl+"' /></a>";
	postTo_(subject, content, user, "BULLETINS");
}

var likeMePage;
/////////////////////////////////////////// RESULTS ///////////////////////////////////////////
var req_getResults = function(){
	selectTab("results");
	if (!hasTaken) {
		requireTakeSurvey();
		return;
	}
	req_likeMeFirst();
	/*if(QUIZE_RESULTS!=null){
		showResults(SURVEY_QUESTIONS);
		showQuizeResults(QUIZE_RESULTS);
	}else if(SURVEY_QUESTIONS!=null){
		myResults="";
		showResults(SURVEY_QUESTIONS);
	}else{*/
		req_getMsgCount();
		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=adDiv3 style='width:728px;height:90px; overflow:hidden;'></div>"+
		 // "<div id=adDiv3 style='margin-bottom:8px'>"+getAd(3)+"</div>"+
		  "<div id=resultsDiv><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>";
	}else {
	str+="<div id=likeMeDiv></div>"+
		  "<div id=postUnderLikeMe></div>"+
		  "<div id=adDiv3 style='width:728px;height:90px; overflow:hidden;'></div>"+
		//  "<div id=adDiv3 style='margin-bottom:8px'>"+getAd(3)+"</div>"+
		  "<div id=resultsDiv><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>";
    }
	container.innerHTML = str;
    Request.sendGET(SERVICE_URL+"/peopleLikeMe/"+userId+"/"+surveyId+"/nogender/true/"+LIKEME_USER_COUNT+"/1", resp_likeMeFirst);
    
    applyMiddleAd('adMiddle', 'adDiv3');

}

var likeMePaging;
var resp_likeMeFirst = function(response){
 if(response != undefined || response.rc == 200){
	likeMeFirstResponse = response;
	var data = response.data;
	totalLikeMe = data.total;
	allowNotExactMatch = data.allowNotExactMatch;
	var str =  "";
	if (userId == ADMIN_USER){
		str += "<h1 class='postLikeMe'><a href='javascript:postNewSurvey()'>Post about new "+chooseSurveyStr()+"</a></h1>";
	}
	if (totalLikeMe > 0){
		str += "<div id=likeMeHeader></div>"+
			   "<div class=usrcontentMsg>"+
			  	"<div id=likeMe><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>"+
			   "</div>";
		$("likeMeDiv").innerHTML = str;
		updateLikeMeHeader();
		likeMePaging = new Paging("likeMePaging", totalLikeMe, SERVICE_URL+"/peopleLikeMe/"+userId+"/"+surveyId+"/nogender/"+allowNotExactMatch+"/"+LIKEME_USER_COUNT+"/1", data, "likeMe");
	}else{
		$("likeMeDiv").innerHTML = str;
	}
	if (msgCount != null){
		showPostUnderLikeMe();
	}
	gadgets.window.adjustHeight();
 }
}

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 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+"/1";
	likeMePaging = new Paging("likeMePaging", data.total, url, data, "likeMe");
}

var resp_getResults = function(response){

	if (response.errorCode || response == undefined || response.rc != 200){
		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;width:728px;height:90px; overflow:hidden;' id='ad10'></div>";
			//"<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;
		updateLikeMeHeader();
		if ($("adDiv3")){
			applyMiddleAd('adMiddle', 'adDiv3');
		}
		
		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;
   
   
  //  if ($("adDiv3")){  applyMiddleAd('adDiv3','ad10'); }
    applyMiddleAd('adMiddle','ad10');
  

gadgets.window.adjustHeight();				
}

var showResults = function(questions, flirt){
	var adIds= new Array();
	var colspan = 3;
	myResults = "";
	var str = "<form name=match id='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,userEmail;
	SURVEY_QUESTIONS = questions;
	totalTakenCount = questions[0].totalAnswers;
	updateLikeMeHeader();
	if ($("adDiv3")){ 
		applyMiddleAd('adMiddle', 'adDiv3');
	}
	
	for (var i=0;i<questions.length;i++){
		if (i!=0 && i % 4 == 0 && questions.length-i>2){
			var k = 3+i/4;
			str += "<tr><td style='padding:5px;height:90px; overflow:hidden;' colspan='"+(colspan+1)+"'  id='ad"+k+"' ></td></tr>"; 
			adIds.push("ad"+k);
			//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)
		{
		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>";
		}
		}
		else if(questions[i].userEmail)
		{
		userEmail=questions[i].userEmail;
		}
	}
	str+="<tbody></table></div></form>";
	if(!userEmail)
	{

	// stex Spell checka petq ...emaili hamar :)  
	str+="<table id='email_set'><tr><td class='postLikeMe' id='email_inform'><b>Please provide your email in order to help us to send you last updates about people like you:</b></td><td><input type='text' value='' id='newEmail' name='newEmail' id='newEmail'/><td>"+
	      "<td><img src='"+IMG_URL+"saveEmail.png' onclick=' save_email()'/><br><div id='save_result_div'></div></td></tr></table>";
	}
	else if(userEmail)
	  {
	   str+="<table id='email_set'><tr><td class='postLikeMe' id='email_inform'>Your provided email is "+userEmail+"</td></tr>"+
	   "<tr><td><b>Change Email: </b></td><td><input type='text' id='newEmail' value='' ><td>"+
	      "<td><img src='"+IMG_URL+"saveEmail.png' onclick=' save_email()'/><div id='save_result_div'></div></td></tr></table>";
	  } 
	 str+="</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;

	for(var i=0; i<adIds.length; i++){
		applyMiddleAd('adMiddle',adIds[i]);
	}


	gadgets.window.adjustHeight();
}
var save_email = function(){
	var newEmail = document.getElementById("newEmail").value;
	if (mailFilter.test(newEmail)) {
	
	data = "query=updateUserEmail&newEmail=" + newEmail + "&userId=" + userId;
	
	Request.sendPOST(SERVICE_URL, data, showEmailUpdateResult);
}
else
{
	$("save_result_div").style.color="red";
	$("save_result_div").innerHTML="Wrong email format";
}
	}
var showEmailUpdateResult=function(response){
if(!response.errorCode){
	$("save_result_div").style.color="green";
	$("save_result_div").innerHTML="Your email was successfully updated!!!";
	$("email_inform").innerHTML="Your provided email is "+$("newEmail").value+" ";

  }
}

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");
	try{
		$("take_survey").style.display = "";
		$("srvResults").style.display = "none";
	}catch(e){
		;
	}
	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){
	var adIds = new Array();
	if (selectedTab != "take") return;
	if (!hasProfileInfo) questions = questions.concat(additionalQuestions);
	var str = "";
	if (!isSuperApp){
		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].id == "age" || questions[i].id == "gender") continue;
		if(typeof questions[i].userEmail=='undefined'){
		if (i!=0 && i % 4 == 0 && questions.length-i>2){
			var k = 3+i/4;
			str += "<tr><td style='padding:5px;height:90px; overflow:hidden;' colspan=3 id='ad"+k+"'  ></td></tr>";
			//str += "<tr><td style='padding:5px;' colspan=3 >"+getAd(3+i/4)+"</td></tr>"; 
			adIds.push("ad"+k);
		}
		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>";
		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 += "<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>"+
		 "<div align=right style='text-align:right;margin-bottom:10px;'><input id=doneButton type=button value=Done onclick=saveResult() /></div>"; 
	fillContainer(str);
	
	//applyMiddleAd('adDivMiddle',adIds[0]);
	for(var i=0; i<adIds.length; i++){
		applyMiddleAd('adMiddle',adIds[i]);
	}
	
	adjustHeight();
}

var saveResult = function(){
	if(typeof OS_USER_TYPE == "undefined") OS_USER_TYPE = "myspace";
	$("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;
	data += "&resultStr="+resultStr+"&"+getUserPostData()+additional;
	Request.sendPOST(SERVICE_URL, data, resp_saveResult);
}

var resp_saveResult = function(response){
	if (response.errorCode || response == undefined || response.rc != 200){
		logError();
		return;
	}
	if (response.text == "ok"){
		hasTaken = true;
		HAS_PROFILE_INFO = true;		
		if ($("srvCompare")){
			$("take_survey").style.display = "none";
			$("srvResults").style.display = "";
			$("srvCompare").style.display = "";
			SURVEY_QUESTIONS = null;
			showInviteTab();
		}else{
			loadSurvey(surveyId);
		}
	}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;width:728px;height:90px;overflow:hidden;' 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 "+chooseSurveyStr()+". 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/>"+
				  "<a href='"+surveyURL+"'><img src='"+surveyImgUrl+"' /></a><br>"+
				  "You can also send a nice gift to me if we are compatible! "+
				  "Or create your own "+chooseSurveyStr()+" with <a href='"+MAKER_URL+"'>Survey Maker</a> and invite me to take it.";
		str += getPostToHTML(subject, text);
	}
    $("compareResult").innerHTML = str;
	
	applyMiddleAd('adMiddle', '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 "+chooseSurveyStr() +"with <a href='"+getMakerUrl()+"'>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 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 <a href='"+getMakerUrl()+"'>create</a> your own "+chooseSurveyStr()+" 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 "+chooseSurveyStr()+"</a> first.</center>";
}
///////////////////////////////////////// Match & Flirt ///////////////////////////////////////////////
var matchReqData;
var flirt = function(){
	selectTab("flirt");
	if (!hasTaken) {
		requireTakeSurvey();
		return;
	}
	container.innerHTML = "<div id=resultsDiv><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></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 || response == undefined || response.rc != 200){
		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 || response == undefined || response.rc != 200){
		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;width:728px;height:90px;overflow:hidden;' 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><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>"+
			  "</div>";
	    matchDiv.innerHTML = str;
	  	matchPaging = new Paging("matchPaging", total, SERVICE_URL, data, "matchUser", matchReqData );
	}
	
	applyMiddleAd('adMiddle', '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");
	showLoading();
	var str = "";
  if(OS_USER_TYPE == "myspace"){
		str+=  "<div class=title id='not_special'>Your Special Gifts () </div>"+
		  "<div class=usrcontentMsg>"+
		  	"<div id=special><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>"+
		  "</div>"+ 
		  '<div id="ad3" style="width:728px;height:90px;overflow:hidden;">'+
		  		//getAd(3)+
		  '</div>';
  }
		str+= "<div class=title id='not_"+NOT_TYPE_KISS+"'>People, who has sent you KISS ()</div>"+
			  "<div class=usrcontentMsg>"+
			  	"<div id=kiss><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>"+
			  "</div>"+
			  '<div  id="ad4" style="width:728px;height:90px;overflow:hidden;">'+
			  		//getAd(4)+
			  '</div>'+			  
			  "<div class=title id='not_"+NOT_TYPE_HUG+"'>People, who has sent you HUG ()</div>"+
			  "<div class=usrcontentMsg>"+
				  	"<div id=hug><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>"+
			  "</div>"+
			  '<div id="ad5" style="width:728px;height:90px;overflow:hidden;">'+
			  		//getAd(5)+
			  '</div>'+
			  "<div class=title id='not_"+NOT_TYPE_WINK+"'>People, who has sent you WINK ()</div>"+
			  "<div class=usrcontentMsg>"+
				  	"<div id=wink><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>"+
			  "</div>"+
			  '<div id="ad6" style="width:728px;height:90px;overflow:hidden;">'+
			  		//getAd(6)+
			  '</div>'+		  
			  "<div class=title id='not_"+NOT_TYPE_BEER+"'>People, who has sent you BEER ()</div>"+
			  "<div class=usrcontentMsg>"+
				  	"<div id=beer><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>"+
			  "</div>"+
			   '<div id="ad7" style="width:728px;height:90px;overflow:hidden;">'+
			  		//getAd(7)+
			  '</div>'+	
			  "<div class=title id='not_"+NOT_TYPE_FLOWER+"'>People, who has sent you FLOWER ()</div>"+
			  "<div class=usrcontentMsg>"+
				  	"<div id=flower><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>"+
			  "</div>"+
			   '<div id="ad8" style="width:728px;height:90px;overflow:hidden;">'+
			  		//getAd(8)+
			  '</div>'+	
			  "<div class=title id='not_"+NOT_TYPE_ICECREAM+"'>People, who has sent you ICE_CREAM ()</div>"+
			  "<div class=usrcontentMsg>"+
				  	"<div id=icecream><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>"+
			  "</div>"+
			  '<div id="ad9" style="width:728px;height:90px;overflow:hidden;">'+
			  		//getAd(9)+
			  '</div>'+
			   "<div class=title id='not_"+NOT_TYPE_SMILE+"'>People, who has sent you SMILE ()</div>"+
			  "<div class=usrcontentMsg>"+
			  	"<div id=smile><div class=loading><center><img src='"+SERVER_URL+"img/loader.gif' /></center></div></div>"+
			  "</div>";
	container.innerHTML = str;
	 if(OS_USER_TYPE == "myspace"){req_getUserGift(1);}

//	Request.sendGET(SERVICE_URL+"/userMsgs/"+userId+"/"+surveyId+"/"+USER_COUNT, resp_getUserMsgs);
	var not_type_id=2;
	function not_callback(response){
		resp_getUserMsgs(response);
		if (not_type_id<8){
			not_type_id++;
			Request.sendGET(SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+not_type_id+"/"+USER_COUNT+"/1",not_callback);
		}
	}
	Request.sendGET(SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+not_type_id+"/"+USER_COUNT+"/1",not_callback);

   
	setTimeout('fillMiddleAds()',8000);
	
}
var fillMiddleAds = function(){
	if($("ad3")){
		applyMiddleAd("adMiddle", "ad3");
		for(var i=4; i<=9; i++)	applyMiddleAd("adMiddle","ad"+i);	
	}else{
		applyMiddleAd("adDivMiddle", "ad4");
		for(var i=5; i<=9; i++)	applyMiddleAd("adMiddle","ad"+i);
	}
	
}
var req_getUserGift = function(page){
	PAGE_GIFT = page;
	Request.sendGET(GIFT_SERVICE_URL+"?&query=getgift"+"&receiverId="+userId+"&appId="+surveyId+"&senderTypeId="+senderTypeId+"&userCount="+GIFT_COUNT+"&page="+page,resp_getUserGift);
}

var resp_getUserGift = function(response){
	var data = response.data;
	DATA = data;
	var header = $("not_special");
	var headerTitle = header.innerHTML;
	var startIndex = headerTitle.lastIndexOf("(");
	var endIndex = headerTitle.lastIndexOf(")");
	var newTitle = headerTitle.substring(0, startIndex+1) + data.count + headerTitle.substring(endIndex, headerTitle.length);
	header.innerHTML = newTitle;
	var str = "<table class='matchUser' id='specialUser'>";
	var index = -1;
	var colCount = GIFT_COUNT/2;
	for(var i = 0;i<data.gifts.length;i++){
		index++;
		if (index % colCount == 0 ) str+= "<tr>";
	
		str += "<td class='userBox' width='20%'><table  width='150'><tr><td class=smallFont id='name'"+data.gifts[i].userId+">From: <a target=_blank href='"+data.gifts[i].userProfile+"'>"+data.gifts[i].userName+"</a>&nbsp;<input type='checkbox' checked ></td></tr>"+
				"<tr><td colSpan='2'><a target='_blank' href='"+data.gifts[i].giftUrl+"'><img class=specialImg src='"+data.gifts[i].imgUrl+"'></img></a></td></tr>"+
				"<tr><td class=smallFont colSpan='2'>Created at: <a class=smallFont style='color:#67A54B' target='_blank' href='"+data.gifts[i].giftUrl+"'><I>"+data.gifts[i].giftName+"</I></a></td></tr></table></td>";
		if (index % colCount == colCount-1) str += "</tr>";
	}
 if(OS_USER_TYPE == "myspace"){
 	str+="<tr class=paging><td><img src='"+IMG_URL+"specialGift.jpg' style='cursor: pointer' onclick='req_getGiftTypeSpecial()'></img></td><td id='selectFriend'></td><td colSpan='3' align='right'><table><tr><td id='previous'></td>";
 }

	var page = 1;
	if(data.count / GIFT_COUNT>1){
		for(var i = 0;i<data.count / GIFT_COUNT;i++){
			if(PAGE_GIFT == page){
				str+= "<td><a href='javascript:req_getUserGift("+page+")'><B>"+page+"</B></a></td>";
			}else{
				str+= "<td><a href='javascript:req_getUserGift("+page+")'>"+page+"</a></td>";
			}
			page++;
		}
		if(parseInt(PAGE_GIFT+1)<(data.count / GIFT_COUNT+1)){
			str+="<td><a href='javascript:req_getUserGift("+parseInt(PAGE_GIFT+1)+")'> Next</a></td>";
		}

		str += "</tr></table></td></tr>";
	}

	str+="</table>";
	$("special").innerHTML = data.count == 0 ? "<div style='color:#67A54B;padding:5px;font-size:14px;'>No special gifts yet :(</div>" : str;
	if(PAGE_GIFT>1){
		$("previous").innerHTML = "<a href='javascript:req_getUserGift("+parseInt(PAGE_GIFT-1)+")'> Previous</a>";
	}
}
var giftPopUpTop = 70;

var req_getGiftTypeSpecial = function(){
	giftPopUpTop = 70;
	var inputs = $("specialUser").getElementsByTagName("input");
	var countChecked = 0;
	for(var i = 0;i<inputs.length;i++){
		if(inputs[i].checked){
			countChecked++;
			break;
		}
	}
	if(countChecked != 0){
		$("selectFriend").innerHTML = "";
		Request.sendGET(GIFT_SERVICE_URL+"?&query=getgiftType" ,resp_getGiftTypeSpecial);
	}else{
		$("selectFriend").innerHTML = "<font color='red' size='2'><I>You haven't selected any friend.</I></font>";
	}
}

var resp_getGiftTypeSpecial = function(response){
	var data = response.data;
	var count = 0;
	var countChecked = 0;
	var inputs = $("specialUser").getElementsByTagName("input");
	var json = '{"recievers": [';
	for(var i = 0;i < inputs.length;i++){

		if (inputs[i].checked == true){
			countChecked++;
			json += '{"recieverId":'+DATA.gifts[i].userId+','+
					'"recieverName":"'+DATA.gifts[i].userName+'",'+
					'"recieverProfile":"'+DATA.gifts[i].userProfile+'",'+
					'"recieverThunb":"'+DATA.gifts[i].userThumb+'"}';

			count++;
			if(i+1 != inputs.length || countChecked != 5){
				json+=',';
			}
			
		}
		if(countChecked == 5){
			break;
		}
		
	}
	
	json+='],"senderId":'+userId+',"senderThumbnail":"'+userThumbnail+'","senderName":"'+userName+'","senderProfile":"'+userProfile+'","appId":'+surveyId+',"senderTypeId":'+senderTypeId;	

	if(count !=0){
		showGiftPopUp(json, data);
	}
}

var showGiftPopUp = function(json, data){
	
	/*
	var str = "<table>";
	var jsonStr = "";
	for(var i = 0; i < data.length; i++){
		jsonStr = '"giftTypeId":'+data[i].id+',"giftType":"'+data[i].type+'","appName":"'+data[i].name+'"}';
		
		giftUrl[i] = data[i].url+"&appParams="+encodeURIComponent(json+","+jsonStr);
		str += "<tr><td><a href='javascript:openGift("+i+")'><img src='"+data[i].imgUrl+"'></img></a></td>"+
				"<td><a href='javascript:openGift("+i+")'><font size='2' color='#003399'><I><B>"+data[i].name+"</B></I></font></a>"+
				"<div>"+data[i].description+"</div>"+
				"</td></tr>"; 
	}
	
	var bodyMask = document.createElement("div");
		bodyMask.className = "special-gift-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";
	var left = $("allContent").offsetWidth/2-150;
	wizardBox.style.left=left+"px";
	giftPopUpTop = giftPopUpTop ? giftPopUpTop : 70;
	wizardBox.style.top = giftPopUpTop+"px";
	wizardBox.style.width="330px";
	wizardBox.innerHTML = "<div style='border: 2px solid #4372CC;'><div class=title style='background: #6487CB;' ><table width='100%'><tr><td><font color='white' size='2'><B>Choose special gift and send it.</B></font></td><td align='right' style='color:white;cursor:pointer;font-weight:bold;font-size:13px;' onclick='closeWizard()'>X</td></tr></table></div>"+str+"</table></div>";
	document.body.appendChild(wizardBox);
	*/
	$("allContent").innerHTML = "<img style='margin-left: 100px;' src='"+SERVER_URL+"img/add_app.jpg' />";
}

var resp_getUserMsgs = function(response){
	if (response.errorCode || response == undefined) return;
	var json = response.data;
	var not_type = json.notType;
	var count=json.count;
	//if (typeof not_type != 'undefined' && note_type != null) {
	var header = $("not_" + not_type);
	var headerTitle = header.innerHTML;
	var startIndex = headerTitle.lastIndexOf("(");
	var endIndex = headerTitle.lastIndexOf(")");
	var newTitle = headerTitle.substring(0, startIndex+1) + count + headerTitle.substring(endIndex, headerTitle.length);
	header.innerHTML = newTitle;
	//}
	var data={users: json.users,available: ((count - USER_COUNT) > 0)}
	switch(not_type)
	{
		case NOT_TYPE_SMILE: 
				smilePaging = new Paging("smilePaging", count, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_SMILE+"/"+USER_COUNT, data, "smile");break;
		case NOT_TYPE_KISS:
				kissPaging = new Paging("kissPaging", count, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_KISS+"/"+USER_COUNT, data, "kiss");break;
 		case NOT_TYPE_HUG:
				hugPaging = new Paging("hugPaging", count, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_HUG+"/"+USER_COUNT, data, "hug");break;
		case NOT_TYPE_WINK:
				winkPaging = new Paging("winkPaging", count, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_WINK+"/"+USER_COUNT, data, "wink");break;
		case NOT_TYPE_BEER:
				beerPaging = new Paging("beerPaging", count, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_BEER+"/"+USER_COUNT, data, "beer");break;
		case NOT_TYPE_FLOWER:
				flowerPaging = new Paging("flowerPaging", count, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_FLOWER+"/"+USER_COUNT, data, "flower");break;
		case NOT_TYPE_ICECREAM:
				icecreamPaging = new Paging("icecreamPaging", count, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_ICECREAM+"/"+USER_COUNT, data, "icecream");break;		
	}
	gadgets.window.adjustHeight();
	
	/*smileCount =json.smileCount;
	kissCount = json.kissCount;
	hugCount = json.hugCount;
	winkCount = json.winkCount;
	beerCount = json.beerCount;
	flowerCount = json.flowerCount;
	icecreamCount = json.icecreamCount;
	var data = {users: json.smiles, available: ((smileCount - USER_COUNT) > 0)};
	smilePaging = new Paging("smilePaging", smileCount, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_SMILE+"/"+USER_COUNT, data, "smile");
	data = {users: json.kisses, available: ((kissCount - USER_COUNT) > 0)};
	kissPaging = new Paging("kissPaging", kissCount, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_KISS+"/"+USER_COUNT, data, "kiss");
	data = {users: json.hugs, available: ((hugCount - USER_COUNT) > 0)};
	hugPaging = new Paging("hugPaging", hugCount, SERVICE_URL+"/userMsgsByType/"+userId+"/"+surveyId+"/"+NOT_TYPE_HUG+"/"+USER_COUNT, data, "hug");
	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");
	gadgets.window.adjustHeight();*/
}

var req_getGiftType = function(obj, id){
	giftPopUpTop = findPosY(obj)-200;
	contId = $(id);
	Request.sendGET(GIFT_SERVICE_URL+"?&query=getgiftType" ,resp_getGiftType);
}

var resp_getGiftType = function(response){
	var count = 0;
	var countChecked = 0;
	var pg = contId.getAttribute("curPage");
	var inputs = $(contId.id+"_"+pg).getElementsByTagName("input");
	var json = '{"recievers": [';
	for (var i=0; i<inputs.length; i++){

		if (inputs[i].checked == true){
			countChecked++;
			var recieverName = $("name"+inputs[i].id).innerHTML;
			var recieverThunb = $("img"+inputs[i].id).src;
			var recieverProfile = $("img"+inputs[i].id).parentNode.href;
			json += '{"recieverId":'+inputs[i].id+','+
					'"recieverName":"'+recieverName+'",'+
					'"recieverProfile":"'+recieverProfile+'",'+
					'"recieverThunb":"'+recieverThunb+'"}';

			count++;
			if(i+1 != inputs.length || countChecked != 5){
				json+=',';
			}
		if(countChecked == 5){
			break;
			}
		}
		if(i == 5){
			break;
		}
	}
	json+='],"senderId":'+userId+',"senderThumbnail":"'+userThumbnail+'","senderName":"'+userName+'","senderProfile":"'+userProfile+'","appId":'+surveyId+',"senderTypeId":'+senderTypeId;
	
	var data = response.data;
	if(count !=0){
		showGiftPopUp(json, data);
	}
}
var openGift = function(index){
	open(giftUrl[index]);
	closeWizard();
	
}
var closeWizard = function(){
	document.body.removeChild($("body-mask"));
	document.body.removeChild($("wizardBox-dlg"));
}

var FriendPaging = function(friendPage) {
	var self = this;
	var containerId = "friend";
	this.compare = function(){
		selectTab("compare");
		if (!hasTaken) {
			requireTakeSurvey();
			return;
		}
		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 || response == undefined || response.rc != 200){
				logError();
				return;
			}
			
			var notifyIds = [];
			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;
				     notifyIds[notifyIds.length] = obj.id;
				}
			}
			var data = {users: json, available: ((friendsCount-allFriends.length)>0)};
			var str = getFriendsHTML(data);
			$("friend").innerHTML +=  "<div id=friend_"+friendPage+">"+str+"</div>";
			
			notifyMatchFriends(notifyIds);
		}
		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+"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 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()'>";
   	str+="<div style='margin: 30px 0px;' id=friend></div>";
/*    if(OS_USER_TYPE == "myspace"){ str+="<div style='margin: 30px 0px;' id=friend></div>";}
    else{                          str+="<div style='margin: 30px 0px;' id=friendList></div>";}*/
    container.innerHTML = str;
    Invite.show();
    
/*     if(OS_USER_TYPE == "myspace"){ 
        initFriend();
     } else{ 
        Invite.show();
     }*/
}

var fillBody = function(){
	isSuperApp = false;
	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.innerHTML = 
	'<iframe src="'+SERVER_URL+'survey_to_promote.html" style="border:0px;" width="840" height="100" scrolling="no" frameborder="0"></iframe>'+
	'<table><tr>'+
	'<td><table cellspacing=0 cellpadding=0>'+
		'<tr class="tabs" id="tabContainer">'+
			'<td name=take id="take_survey"><a href="javascript:req_getSurvey()">Take Survey</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:showInviteTab()">Invite Friends</a></td>'+
			'<td name=users><a href="javascript:getUsers()">Cool People</a></td>'+
			'<td name=public><a href="javascript:getPublicSurveys()">Fun Quizes</a></td>'+
			'<td name=create><a target="_blank" href="'+MAKER_URL+'">Create Survey</a></td>'+
			'<td name=settings id=settings><a href="javascript:settings()">Settings</a></td>'+
		'</tr>'+
	'</table></td>'+
	'</tr></table>'+
	'<div style="margin-top:5px;" 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><center><img src="'+SERVER_URL+'img/loader.gif" /></center></div></div>'+
			'<div style="margin-top:5px;" id="adBottom"></div>'+
			//////////'<div style="margin-top:5px;" id="adDiv2"></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><center><img src='"+SERVER_URL+"img/loader_small.gif' /></center></div></div>"+	
			"<div class=title_rb>Most Recent</div>"+
			"<div class=content_rb id='recent_rb'><div class=loading><center><img src='"+SERVER_URL+"img/loader_small.gif' /></center></div></div>"+	
			"<div class=title_rb>Most Popular</div>"+
			"<div class=content_rb id='popular_rb'><div class=loading><center><img src='"+SERVER_URL+"img/loader_small.gif' /></center></div></div>"+	
			"<div class=title_rb>Active Today</div>"+
			"<div class=content_rb id='today_rb'><div class=loading><center><img src='"+SERVER_URL+"img/loader_small.gif' /></center></div></div>"+
		'</td>'+
	'</tr></table>';
	
	container = $("container");
	errorDiv = $("error");
	loadRecentUsers();
	getUser();
	gadgets.window.adjustHeight();
	setInterval(refreshIframe, 45000);

		try{
			applyAds('adDivTop', 'adTop');
			applyAds('adDivBottom', 'adBottom');
			if(OS_USER_TYPE != "friendster"){ 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>';
			if ($('adTop')) $('adTop').innerHTML = adStr;
			if ($('adBottom')) $('adBottom').innerHTML = adStr;
		} 

	req_channel_statistics("canvas");
}



var hideTabs = function(msg) {
	$("take_survey").style.display = "none";
	$("srvResults").style.display = "none";
	$("srvCompare").style.display = "none";
	$("srvFlirt").style.display = "none";
	$("srvInbox").style.display = "none";
	$("srvInvite").style.display = "none";
	$("settings").style.display = "none";
	/*
	req_getRightBar();
	getPublicSurveys();
	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();
}

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(){
	if (isSuperApp){
		var surveyId = getRandomElement(AD_SURVEYS).id;
		loadSurvey(surveyId);
	}else{
		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;
}

