var newSurvey = {title:"", desc:"", image:"noimage.jpg", questions: ""};
var container;
var errorDiv;
var questionIndex = 0;
var answerIndex = 0;
var surveyId = 1;
var profileCode;
var canvasCode;
var surveyURL = "http://www.myspace.com/330787305";
var approved = true;
var osContainer;
var container
var radioName;

var createTest = function(){
	showError("");
	selectTab("test");
	showLoading();
	
	newSurvey.image = "";
	var str="<h1>Step 1: Choose a Title for Your Trivia </h1>"+
			"<div class=small>Upload Picture for Your Trivia. Add the shorter description about Your Trivia.</div>"+
			"<table>"+
				"<tr>"+
					"<td class=label>Title:</td>"+
					"<td><input style='width: 295px;' />*</td>"+
				"</tr>"+
				"<tr>"+
					"<td></td>"+
					"<td id='surveyImg'><img class=preview src='"+SURVEY_IMG_URL+"noimage.jpg' /></td>"+
				"</tr>"+
				"<tr>"+
					"<td class=label>Upload Photo:</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 colspan=2 align=right><input id='nextToQuestions' type='button' value='Next' onclick='addQuestions()' /></td>"+
				"</tr>"+
			"</table>";	
	container.innerHTML = str;
}

var addQuestions = function(){

	var inputs = document.getElementsByTagName("input");
	var desc = document.getElementsByTagName("textarea")[0].value;
	if (desc == "" || inputs[0].value == "" || newSurvey.image == ""){
		showError("Fill in the required fields.");
	}else if (desc.length > 254){
		showError("Description is too long.");	
	}else{
		errorDiv.innerHTML = "";
		newSurvey.title = encodeURIComponent(inputs[0].value);
		newSurvey.desc = encodeURIComponent(desc);	
		
		var str = "<h1>Step 2: Add Questions & Answers</h1>"+
					"<div class=small>Make your questionary more powerful.</div>"+
					"<div id=questions></div>";
					
			container.innerHTML = str;			
			questionIndex = 0;
			showError("");
		for(var i = 0;i<5;i++){
			addQuestion(true);
		}
		
		container.innerHTML += "<input type='button' value=Finish onclick=finalStep() class=button ></input>";
	}
}

var addQuestion = function(isFirst){
	questionIndex++;
	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><select><option value = '1'>1</option><option value = '2'>2</option>"+
							"<option value = '3'>3</option><option value = '4'>4</option></select><font size='2' color = '#595959'> Point</font></td>"+
							"<td align='center' width = '350' height = '70' class='imgUploadTd'>"+
								"<h4 class='choose' style='cursor:pointer' onclick = 'question(this)'><font color = '#595959'>choose image</font></h4>"+
						   "</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>";
				   str+="</tr>"+
						"<tr>"+
							"<td class=label>Answers:</td>"+
							"<td><input class='questionInput' id='answer_a"+(answerIndex+1)+"' /></td>"+
							"<td><input type='radio' checked name='true"+questionIndex+"'>true</td>"+
							"<td width = '350' height = '70' align='center' id = 'answer' class='imgUploadTd'>"+
								"<h4 class='choose' style='cursor:pointer' onclick = 'answer(this)'><font color = '#595959'>choose image</font></h4>"+
						   "</td>"+
						   "<td id='answerImg_a"+(answerIndex+1)+"'style='display: none'><img class=preview src='"+SURVEY_IMG_URL+"noimage.jpg' /></td>"+
						"</tr>"+
						"<tr>"+
							"<td></td>"+
							"<td><input class='questionInput'  id='answer_a"+(answerIndex+2)+"'/></td>"+
							"<td><input type='radio' name='true"+questionIndex+"'>true</td>"+
							"<td width = '350' height = '70' align='center' id='secondAnswer' class='imgUploadTd'>"+
								"<h4 class='choose' style='cursor:pointer' onclick = 'answer(this)'><font color = '#595959'>choose image</font></h4>"+
						   "</td>"+
						   "<td id='answerImg_a"+(answerIndex+2)+"' style='display: none'><img class=preview src='"+SURVEY_IMG_URL+"noimage.jpg' /></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 question = function(node)
{
		var str = "<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>";

		node.parentNode.innerHTML = str;			
}

var answer = function(node)
{
		var str =  "<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>";
								
		node.parentNode.innerHTML = str;							
}


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");
	cell5.style.display = "none";
	cell2.innerHTML = "<input class='questionInput'  id='answer_a"+answerIndex+"'/>";
	cell3.innerHTML = "<input type='radio' name='true"+questionId+"'>true";
	cell4.className = 'imgUploadTd';
	cell4.align = "center";
	cell4.style.width = "350";
	cell4.style.height = "70";	
	cell4.innerHTML = "<h4 class='choose' style='cursor:pointer' onclick = 'answer(this)'><font color = '#595959'>choose image</font></h4>"; 

					
	cell5.id = "answerImg_a"+answerIndex;
	cell5.innerHTML = "<img class=preview src='"+SURVEY_IMG_URL+"noimage.jpg' />";
	row.appendChild(cell1);
	row.appendChild(cell2);
	row.appendChild(cell3);
	row.appendChild(cell4);
	row.appendChild(cell5);
	table.insertBefore(row, table.lastChild);
	//adjustHeight();
}

var finalStep = function(){
	var questionsDiv = $("questions");
	var questionCount = questionsDiv.childNodes.length;
	var qCount = 0;
	var aCount = 0;
	var cCount = 0;
	var questionStr = "";
	var questionIndex = "";
	for(var i = 1 ; i <= questionCount ; i++)
	{
	
		var inputs = $("question"+i).getElementsByTagName("input");
		var select = $("question"+i).getElementsByTagName("select");
		if (inputs[0].value != "")
		{
			qCount++;
			questionStr += "&questionText_"+qCount+"="+encodeURIComponent(inputs[0].value);
			for (var j=1;j<inputs.length;j++){
				if(inputs[j].type == 'hidden' && inputs[j].value != ""){
					questionStr += "&questionImageUrl_"+qCount+"="+encodeURIComponent(inputs[j].value);
					questionIndex = j;
					break;
				}
			}
			aCount = 0;
			var id = "";
			
			for (var j=1;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(inputs[j].type == "text" && inputs[j].value != "" && j != questionIndex) {
						aCount++;
						questionStr += "&answerText_"+qCount+"_"+aCount+"="+encodeURIComponent(inputs[j].value);
					}
					if(inputs[j].type == "hidden" && inputs[j].value != "" && j != questionIndex) {
						questionStr += "&answerImageUrl_"+qCount+"_"+aCount+"="+encodeURIComponent(inputs[j].value);
					}
					
				}
			}
			
			questionStr += "&cost_"+qCount+"="+select[0].value;
			cCount = 0;
			for(var j = 1;j<inputs.length;j++)
			{
				if(inputs[j].type == "radio")
					{
						cCount++;
						if(inputs[j].checked){
							questionStr += "&correct_"+qCount+"_"+cCount+"=1";
							}
							else{
								questionStr += "&correct_"+qCount+"_"+cCount+"=0";
								}
					}
			}
			
			if (aCount>=2){
				errorDiv.innerHTML = "";
				questionStr += "&answerCount_"+qCount+"="+aCount;
			}else{
				showError("Each question must have at least 2 answers.");
				return;
			}
						
		}
		
	}
	if (qCount<5){
		errorDiv.innerHTML = "";
		showError("You must type at least five question and 2 answers.");
	}else{
		questionStr += "&questionCount="+qCount;
		newSurvey.questions = questionStr;
		req_createTest();
		//container.innerHTML = "";	
	}
	
}


var req_createTest = function(){
	
	var data = "query=addtest&userId="+userId+"&title="+newSurvey.title+"&img="+newSurvey.image+
					"&desc="+newSurvey.desc+"&"+newSurvey.questions+"&"+getUserPostData();
		Request.sendPOST(SERVICE_URL, data, resp_createTest);
}
var resp_createTest = function(response){
	var resp = response.data;
	var testId = resp.id;
	overCreate(testId);
}
var overCreate = function(testId){
	surveyId = testId;
	var str="<div align='center' style='margin-top:30px;font-size:14px;width:100%'>"+
	   "<div style='font-weight:bold'>Thank you for creating the Trivia!</div>"+
	   "After we review and approve the content, we will publish your Trivia.<br><br>"+
	   "<a href='javascript:takeThisTest("+surveyId+")'><b>Now go on!!! Be the first to take the Trivia!!!</b></a>"+
	   "</div>";
	   
   var cont = document.getElementById("container");
   	cont.innerHTML = str;

}
////////////////////////////////////// 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 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>';
        container.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);
        }
    }
}

