var questionContainerHeights = new Object();
var lastBlogItemId = 0;

/* add moo.fx to questionContainer elements */			
// window.onload = function() {
Event.observe(window, 'load', function() { // using prototype event to avoid overwrites from inline body onloads
	var questionContainers = document.getElementsByClassName("questionContainer");
	var i;
	for(i=0; i < questionContainers.length; i++) {
		var a = questionContainers[i];
		questionContainerHeights[a.id] = new fx.Combo(a.id, {duration: 400});
		questionContainerHeights[a.id].hide();
		a.style.display = ""
	}
	var queryString = location.search.substring(1);
	if(queryString != "") {
		var queryStringObject = queryString.parseQuery();
		var voteBoxIndex;
		if(queryStringObject.OpenVoteBoxId != null) {
			voteBoxIndex = "questionContainer_" + queryStringObject.OpenVoteBoxId;
			if(questionContainerHeights[voteBoxIndex] != null) {
				questionContainerHeights[voteBoxIndex].toggle();
			}
		}
	}
});

/* Submit answer for a question */
function answerQuestion(questionId, blogItemId, answer, isCommunity, rurl) {
	var timeString = new Date().getTime();
	//alert(rurl);
	rurl= encodeURI(rurl)
	//alert(rurl);
	var params = 'questionId='+questionId+'&blogItemId='+blogItemId+'&answer='+answer+'&ts='+timeString +'&is_community='+ isCommunity+ '&referring_url='+ rurl;
	//alert(params)
	new Ajax.Request('/utility/ajax/voting/answer_question.asp', {method:'post', parameters: params, onSuccess:handleRating, onFailure:handlerRatingError});
}

/* Get back a JSON object that indicates whether the user is logged in 
  If logged in, also returns list of commands to be executed to change styles */
var handleRating = function(t) {
	var jsonText;
	var jsonObject;
	
	//try{
	//	bObj.removeScriptTag();
	//	jsonObject = t;
	//}
	//catch(error){
	//	alert("error section");
		jsonText = t.responseText;
		jsonObject = jsonText.parseJSON();
	//}
	
	// If the user was able to vote (i.e. logged in)
	if( jsonObject.loggedIn != "false") {
		// Change display to reflect vote
		var i, j;
		var commandList = jsonObject.commandList;
		ExecuteCommandList(commandList);
	} else {
		// Not able to vote (not logged in)
		// must send store the id of the blog item being voted on		
		// lastBlogItemId = returnVals[1];
		// open login box
		lastBlogItemId = jsonObject.openBlogItemId;
		if(lightboxHash.loginLightbox != undefined) {
			lightboxHash.loginLightbox.activate();
		}
	}
}

/* An Error Occurred */
var handlerRatingError = function(t) {
	alert("An error occurred while voting. Please contact the website administrator.");
}

/* this function takes a command list which is an array with commands of the form
 {"type": "type_value", "attribute": "att_value"} */
function ExecuteCommandList(commandList) {
	for(i=0; i < commandList.length; i++) {
		if(commandList[i].type == 'id') {
			var tmpElement = document.getElementById(commandList[i].type_value);
			if(commandList[i].attribute == 'class') {
				tmpElement.className = commandList[i].att_value;
			} else if(commandList[i].attribute == 'width') {
				tmpElement.style.width = commandList[i].att_value;
			}
		} else if(commandList[i].type == 'class') {
			var ratingLinks = document.getElementsByClassName(commandList[i].type_value);
			for(j=0; j < ratingLinks.length; j++) {
				if(commandList[i].attribute == 'class') {
					ratingLinks[j].className = commandList[i].att_value;
				} else if(commandList[i].attribute == 'width') {
					ratingLinks[j].style.width = commandList[i].att_value;
				}			
			}
		}
	}
}


/************************** Voting Widget ******************************************/

/* Submit answer for a question */
function answerQuestionWidget(questionId, blogItemId, answer, isCommunity, rurl, domain) {
	var timeString = new Date().getTime();
	//alert(rurl);
	rurl= encodeURI(rurl)
	//alert(rurl);
	var params = 'questionId='+questionId+'&blogItemId='+blogItemId+'&answer='+answer+'&ts='+timeString +'&is_community='+ isCommunity+ '&referring_url='+ rurl;
	//alert(params)
	//new Ajax.Request('/utility/ajax/voting/answer_question.asp', {method:'post', parameters: params, onSuccess:handleRating, onFailure:handlerRatingError});

	// The web service call
	var req  = 'http://www.' + domain + '/utility/ajax/voting/answer_question.asp?callback=handleRatingWidget&' + params; 
	// Create a new request object
	bObj = new JSONscriptRequest(req); 
	// Build the dynamic script tag
	bObj.buildScriptTag(); 
	// Add the script tag to the page
	bObj.addScriptTag();
}

/* Get back a JSON object that indicates whether the user is logged in 
  If logged in, also returns list of commands to be executed to change styles */
var handleRatingWidget = function(t) {
	//var jsonText;
	var jsonObject;
	
	jsonObject = t;
	bObj.removeScriptTag();
	
	// If the user was able to vote (i.e. logged in)
	if( jsonObject.loggedIn != "false") {
		// Change display to reflect vote
		var i, j;
		var commandList = jsonObject.commandList;
		ExecuteCommandList(commandList);
	} else {
		// Not able to vote (not logged in)
		// must send store the id of the blog item being voted on		

		// For Pop-up login page
		var params = 'questionId='+jsonObject.questionId+'&blogItemId='+jsonObject.blogItemId+'&answer='+jsonObject.answer+'&is_community='+ jsonObject.isCommunity+ '&referring_url='+ jsonObject.rurl;
		window.open("http://edit." + jsonObject.domain + "/community/security/secure_community_login.asp?votingwidget=true&url=" + URLEncode("http://www." + jsonObject.domain + "/utility/ajax/voting/voting_login_popup.asp?confirm=true&"+params), "login", "width=300,height=300");
		
	}
}

/************************** End Voting Widget ******************************************/


function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	//var plaintext = document.URLForm.F1.value;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
}
