// Hey Fl1xt3r & Sl1d3, thanks for looking :)
var current_taken_quiz_data = null;
var friend_selector = null;
var current_viewer_object = null;
var ruids = 15;
var processed_uids = 0;
var result = 0;
function movies_quiz_jstl_template_calculateScore(quizId, total_questions, post_bulletin)
{
	var radios = document.getElementsByTagName("input");
	var checked_correct = 0;
	var checked_incorrect = 0;
	var total_questions = total_questions;
    var movie_question_and_choice = new Hash();

    if(post_bulletin == undefined || post_bulletin == null)
    {
    	post_bulletin = false;
	}

	//default_random_param.set("random", Math.random());
	movie_question_and_choice.set("quizId", quizId);

	for(var i =0; i < radios.length; i++)
	{
		var radio = radios[i];
		if(radio.type == "radio" && radio.checked == true)
		{
			var choice_id = radio.getAttribute("choice");

			if(radio.getAttribute("attribute") == "true")
			{
				checked_correct++;

                if(radio.getAttribute("question") != null)
				{
					// for question # answered true.
					movie_question_and_choice.set("question_" + radio.getAttribute("question"), choice_id + "|1");
				}
			}
			// not simple 'else' for purpose
			else if(radio.getAttribute("attribute") == "false")
			{
				checked_incorrect++;

                if(radio.getAttribute("question") != null)
				{
					// for question # answered true.
					movie_question_and_choice.set("question_" + radio.getAttribute("question"), choice_id + "|0");
				}
			}
		}
	}

	if((checked_correct + checked_incorrect) != total_questions)
	{
		alert("Please answer all questions first");
		return;
	}


	result = (checked_correct / total_questions ) * 100;

	if(container != "myspace.com")
	{
		if(container != "orkut.com")
		{
		    $("multiQuiz_quizHolder").hide();
			$("multiQuiz_friendSelectorHolder").show();

			if($("multiQuiz_friendSelectorHolder").style.display != "block")
			{
				$("multiQuiz_friendSelectorHolder").style.display = "block";
			}
		}

		movies_save_movie_trivia_showScores();
	}
	else
	{
		$("movie_quiz_jstl_template_getscore_button").hide();
		$("movie_quiz_jstl_template_getscore_link").hide();
	}

	movie_question_and_choice.set("quizScore", result);
	movie_question_and_choice.set("quizTitle", $("movie_trivia_quiz_title").innerHTML);
	movies_save_movie_trivia_choices(movie_question_and_choice, post_bulletin);
}

function movies_save_movie_trivia_showScores()
{
	var radios = document.getElementsByTagName("input");
    for(var i =0; i < radios.length; i++)
	{
		var radio = radios[i];
		if(radio.type == "radio" && radio.checked == true)
		{
        	if(radio.getAttribute("attribute") == "false")
			{
			    var label = $("label_for_" + radio.id);
				label.style.color = "#FF0000";
				label.style.fontWeight = "bold";
			}
		}

 		if(radio.getAttribute("attribute") != null)
		{
			radio.disabled = true;

			if(radio.getAttribute("attribute") == "true")
			{
	            var label = $("label_for_" + radio.id);
				label.style.color = "#00FF00";
				label.style.fontWeight = "bold";
			}
		}
	}
	$("movie_quiz_jstl_template_getscore_result_score").innerHTML = result;
	$("movie_quiz_jstl_template_getscore_button").hide();
	$("movie_quiz_jstl_template_getscore_result_div").show();
}

function movies_save_movie_trivia_choices(movie_question_and_choice, post_bulletin)
{
	var save_path = "google_apps/movies/server/SaveMovieTriviaQuizChoices.php";
	var viewer = null;
	var viewerFriends = null;

	if(post_bulletin == undefined || post_bulletin == null)
	{
		post_bulletin = false;
	}

	if(container != "myspace.com")
	{
	    var movies_save_movie_trivia_choices_response = function(data)
		{
        	if(container != "orkut.com")
			{
		        var req = opensocial.newDataRequest();
			    req.add(req.newFetchPersonRequest('OWNER'), 'owner');
			    req.send(onLoadFriends.bind(this));
			}
		}

		// this is only hi5...
		var onLoadFriends = function (data)
	    {
		    this.viewer = data.get('owner').getData();
		    current_viewer_object = this.viewer;		    

			movie_question_and_choice.set("ownerName", this.viewer.getDisplayName());
			movie_question_and_choice.set("type", "activity");

            genericJSONPost("google_apps/movies/server/hi5_submit_comments.php",
				movie_hi5_submit_comments_cb.bind(this),
					movie_question_and_choice.toQueryString());
		}

       	genericJSONPost(save_path,
				movies_save_movie_trivia_choices_response.bind(this),
				movie_question_and_choice.toQueryString());
	}
	else
	{
		showbulletin = post_bulletin;

		if(showbulletin == true)
		{
			movie_question_and_choice.set("showbulletin", 1);
		}
		else
		{
			movie_question_and_choice.set("showbulletin", 0);
		}

		genericJSONPost(save_path,
			movies_save_quiz_callback,
			movie_question_and_choice.toQueryString());
	}

	current_taken_quiz_data = movie_question_and_choice;
}

function movie_hi5_submit_comments_cb(data)
{

}

var movies_aftersave_callback = null;

function movies_save_quiz_callback(data)
{
    var show_dialog = "1";
    if (typeof(data) == "object" && data.return_data != null)
    {
        var return_data_JSON = data.return_data.evalJSON();
        show_dialog = return_data_JSON.sent_bulletin;
    }
    if(container == "orkut.com")
	{
		$("multiQuiz_quizHolder").show();
	}
	else
	{
		if(movies_aftersave_callback != null && typeof(movies_aftersave_callback) == "function")
		{
            if (show_dialog == "0")
            {
                multiquiz_fs0_post_cb();
            }
            else
            {
                movies_aftersave_callback();
            }
		}
		else
		{
            $("multiQuiz_friendSelectorHolder").show();

			if($("multiQuiz_friendSelectorHolder").style.display != "block")
			{
				$("multiQuiz_friendSelectorHolder").style.display = "block";
			}
		}
	}
}

function loadFriend_selector()
{
    if(!moviesr && container == "myspace.com")
    {
	    friend_selector = new FriendSelector("friend_selector", "multiQuiz_friendSelector", function(data){});
		friend_selector.bToggleText = false;
    	friend_selector.bToggleSelectAll = false;
    	friend_selector.UIPageSize = 25;
    	friend_selector.setClickCallBack(function(data){if(data["checked"]){friend_selector_click_cb(data);}}.bind(this));

    	$("movies_multiquiz_fs_button1").hide();
    	$("movies_multiquiz_fs_button2").hide();
	}
	else
	{
	    friend_selector = new FriendSelector("friend_selector", "multiQuiz_friendSelector", handle_friend_selector_submit);
	    friend_selector.UIPageSize = 25;
	    friend_selector.bToggleText = false;
        friend_selector.setClickCallBack(function(data) {
		    displayFriendsNo(friend_selector.selectedTotal);
		});
	}

	friend_selector.setPageLoadCallBack(movies_show_loading(false));
	friend_selector.CONTAINER_MAX = 40;
	friend_selector.gotoPage(1);//if(!moviesr){friend_selector.selectAll();}
}

function friend_selector_click_cb(data)
{
	var uid = data["id"];
	current_taken_quiz_data.set("pc", "1");
	current_taken_quiz_data.set("proccessed", (processed_uids+1));
    current_taken_quiz_data.set("friend_ids", uid);
    current_taken_quiz_data.set("showbulletin", 0);

    displayFriendsNo((processed_uids + 1),true);
	genericJSONPost("google_apps/movies/server/myspace_submit_comments.php",
			movies_multiquiz_pc_callback.bind(this),
			current_taken_quiz_data.toQueryString());
}

function movies_multiquiz_pc_callback(data)
{
	processed_uids++;

	if(processed_uids >= ruids)
	{
		movies_save_movie_trivia_showScores();
	    $("multiQuiz_quizHolder").show();
		$("multiQuiz_friendSelectorHolder").hide();
	}
	else
	{
		displayFriendsNo(processed_uids, true);
	}
}

function handle_friend_selector_submit(data)
{
	var total = friend_selector.aFriends.length;
	var required = ruids;

	if(total <= required)
	{
		required = total;
	}

	if(moviesr)
	{
		required = 0;
	}

	if(data == null || data['ID_LIST'] == null || data['ID_LIST'].length <= 0 && !moviesr)
	{
		if(container == "myspace.com")
		{
			$("max_to_select").innerHTML = required;
	        $("fs_0_holder").show();
		}
		else
		{
			alert("Please select at least " + required + " friends in order to see your score!" );
		}

		return;
	}
	else
	{
		var count = data["ID_LIST"].split(",").length;

		if(count < required && !moviesr)
		{
            if(container == "myspace.com")
			{
		        $("max_to_select").innerHTML = required;
		        $("fs_0_holder").show();
			}
			else
			{
				alert("Please select at least " + required + " friends in order to see your score!");
			}
			return;
		}
	}

	if(container != "myspace.com")
	{
		var viralChannels = new ViralityChannels();
	    viralChannels.setQuizId(current_taken_quiz_data.get("quizId"));
		viralChannels.setQuizTitle(current_taken_quiz_data.get("quizTitle"));
		viralChannels.setQuizScore(current_taken_quiz_data.get("quizScore"));
		viralChannels.setTargetIds(data['ID_LIST']);

		if(container == "orkut.com")
		{
			viralChannels.createActivity(current_viewer_object);
		}
		else
		{

	        current_taken_quiz_data.set("ownerName", current_viewer_object.getDisplayName());

			current_taken_quiz_data.set("type", "notification");
			current_taken_quiz_data.set("friend_ids", data['ID_LIST']);

	        genericJSONPost("google_apps/movies/server/hi5_submit_comments.php",
				movie_hi5_submit_comments_cb.bind(this),
					current_taken_quiz_data.toQueryString());

			//viralChannels.sendNotification(current_viewer_object);
		}
	}

	var notification_count = data['ID_LIST'].split(",").length;

	var track_hash = new Hash();
	track_hash.set("count", notification_count);

	if(container == "myspace.com")
	{
		if(notification_count < required)
		{
			$("max_to_select").innerHTML = required;
			$("fs_0_holder").show();
			return;
		}
		else
		{
			$("fs_0_holder").hide();
		}

		if(data['ID_LIST'].length > 0)
		{
			current_taken_quiz_data.set("friend_ids", data['ID_LIST']);
			current_taken_quiz_data.set("newinstall", is_new());
			current_taken_quiz_data.set("showbulletin", 1);

			multiquiz_fs_showinstructions();

            after_instructions_function = function() {
                genericJSONPost("google_apps/movies/server/myspace_submit_comments.php",
					movies_multiquiz_track_callback.bind(this),
					current_taken_quiz_data.toQueryString());
			}
		}
	}
	else
	{
		track_hash.set("event", "hi5-movies-notif-accepted-sent");
		genericJSONPost("google_apps/movies/server/tracker.php",
			movies_multiquiz_track_callback.bind(this),
			track_hash.toQueryString());
	}
}

function movies_multiquiz_track_callback(data)
{
	movies_save_movie_trivia_showScores();
    $("multiQuiz_quizHolder").show();
	$("multiQuiz_friendSelectorHolder").hide();
}

function movies_likeness_quiz_save_choices()
{
	// everything ok
}

function displayFriendsNo(friendNo, cd){
	if(cd == undefined || cd == null) { cd = false; }
	var friends_text =  " friend selected for a challenge!";
	if(cd){var friend_text="friends";var left=(ruids-friendNo);if(left==1){friend_text="friend"};friends_text=" Select <span style='font-size:16pt;color:#008000;'>" + left + "</span> more " + friend_text + " in order to see your score!";

	var multiQuiz_friendsSelectedCount = $("multiQuiz_friendsSelectedCount"); multiQuiz_friendsSelectedCount.innerHTML = friends_text;return;}

	if (friendNo == 0)
	{
	    friends_text = 'Please select at least one friend for a challenge!';
	}

	if(friendNo > 1)
	{
	    friends_text = ' friends selected for a challenge!';
	}

    var multiQuiz_friendsSelectedCount = $("multiQuiz_friendsSelectedCount");

    if(friendNo == 0)
    {
    	multiQuiz_friendsSelectedCount.innerHTML = friends_text;
	}
	else
	{
		multiQuiz_friendsSelectedCount.innerHTML = "<span style=\"color:#15A42B;font-weight:bold;\">" + friendNo + "</span>" + friends_text;
	}
}

function movies_settings_useSkinOnClick(skin_name)
{
	var save_path = "google_apps/movies/server/SaveSettings.php";
    var movies_settings_params = new Hash();
	movies_settings_params.set("random", Math.random());
	movies_settings_params.set("skinname", skin_name);

    genericJSONPost(save_path,
			movies_settings_useSkinOnClick_response.bind(this),
				movies_settings_params.toQueryString());
}

function movies_settings_useSkinOnClick_response(data)
{
	alert("Your profile has been updated. Next, take a trivia quiz!");
}

function multiquiz_compareWithFriends(quizId)
{
    var viralChannels = new ViralityChannels();
	viralChannels.setQuizId(current_taken_quiz_data.get("quizId"));
	viralChannels.setQuizTitle(current_taken_quiz_data.get("quizTitle"));
	viralChannels.setQuizScore(current_taken_quiz_data.get("quizScore"));
	viralChannels.shareApplication();
}


function movies_quiz_label_mouseover(label)
{
	label.style.textDecoration = "underline";
	label.style.backgroundColor = "#EAFFCC";
}

function movies_quiz_label_mouseout(label)
{
	label.style.textDecoration = "none";
	label.style.backgroundColor = "#ffffff";
}

function multiquiz_goToNextQuiz(quizId)
{
	var quizId = new Number(quizId);

	goto_canvas_page('MoviesMultiQuizPage?quizId=' + (quizId + 1));
}

function movies_aftercomment_cb(toid, type, result)
{
	if(result == 1)
	{
		var params = new Hash();

		params.set("userId", toid);
		params.set("type", type);
		params.set("result", result);

        genericJSONPost("google_apps/movies/server/MySpaceCommentSend.php",
				movies_after_comment_cb_cb.bind(this), params.toQueryString());
	}
/*
	if(result == 0)
	{
		alert("You just clicked Cancel, you must click Add in order to see your score!");
	}
*/
}

function movies_after_comment_cb_cb(data)
{
	/* ignore */
}


function movies_ratings_init()
{
	movies_show_loading(false);
	// movies_rating_main
	$("movies_rating_main").innerHTML = "test";

    var jtemplate = new JTemplate();
	var ratings_param = new Hash();
	ratings_param.set("random", Math.random());
	jtemplate.registerAfterGenerateCallback(movies_ratings_init_finish);
	jtemplate.generate("movies_ratings_template.php", "GetRatings.php", "movies_rating_main", ratings_param);
	// movies_rating_main
}

function movies_ratings_init_finish()
{
	movies_ratings_addToolTip();
	document.onmousemove = positiontip;
}

function movies_rating_mouseOver(movieId, starNum)
{
	for(var i = 0; i < 5; i++)
	{
		var star = $("movies_rating_star_" + movieId + "_" + i);

		if(i <= starNum)
		{
			star.src = "http://dev2.rockyou.com/google_apps/movies/images/star_1.png";
		}
		else
		{
			star.src = "http://dev2.rockyou.com/google_apps/movies/images/star_0.png";
		}
	}

	var tooltip_star = $("movies_rating_star_" + movieId + "_" + starNum);
	ddrivetip(tooltip_star.getAttribute("tooltiptext"))
}

function movies_rating_mouseOut(movieId, original)
{
	for(var i = 0; i < 5; i++)
	{
		var star = $("movies_rating_star_" + movieId + "_" + i);

		if(i < original)
		{
			star.src = "http://dev2.rockyou.com/google_apps/movies/images/star_1.png";
		}
		else
		{
			star.src = "http://dev2.rockyou.com/google_apps/movies/images/star_0.png";
		}
	}

	hideddrivetip()
}

function movies_rating_onClick(movieId, rating)
{
    for(var i = 0; i < 5; i++)
	{
		var star = $("movies_rating_star_" + movieId + "_" + i);

		star.onmouseout = null;
		star.onmouseover = null;

		if(i <= rating)
		{
			star.src = "http://dev2.rockyou.com/google_apps/movies/images/star_1.png";
		}
	}

	ddrivetip("<p>Thanks for your rating!</p>");
	movies_ratings_saveRating(movieId, rating);
}

function movies_ratings_saveRating(movieId, rating, comment)
{
	if(comment == undefined || comment == null)
	{
		comment = "";
	}

    var params = new Hash();

	params.set("rating", rating);
	params.set("comment", comment);
	params.set("movieId", movieId);

    genericJSONPost("google_apps/movies/server/SaveRating.php",
			movies_ratings_saveRating_cb.bind(this), params.toQueryString());
}

function movies_ratings_saveRating_cb(data)
{
	setTimeout("hideddrivetip()", 700);
}

function movies_ratings_getDescription(rating, movie_title)
{
	var text = "Rate this movie with " + (rating +1) + " stars";

	if(rating == "0")
	{
		text = "WTF?! This was rediculously bad!";
	}
	else if(rating == "1")
	{
		text = "Bad, boring and ugly";
	}
	else if(rating == "2")
	{
		text = "Good movie, but I probably would not watch it again.";
	}
	else if(rating == "3")
	{
		text = "Very good flick, I can even watch it again.";
	}
	else if(rating == "4")
	{
		text = "An exceptional movie, with amazing acting and story line!";
	}

	if(movie_title == undefined || movie_title == null)
	{
		movie_title = "Rate this movie";
	}

	text = "<div id='ToolTipTextWrap'>" + movie_title + "</div><p>" + text + "</p>";
	return text;
}
/**
 * Tooltip stuff
 */
var offsetfromcursorX = -7; //Customize x offset of tooltip
var offsetfromcursorY = 23; //Customize y offset of tooltip

var offsetdivfrompointerX = 13; //Customize x offset of tooltip DIV relative to pointer image
var offsetdivfrompointerY = 13; //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1).

function movies_ratings_addToolTip()
{
	var thealinks = document.getElementsByTagName("img");

	if (!thealinks)
	{
		return;
	}

	for(var x=0;x!=thealinks.length;x++)
	{
		if(thealinks[x].className == "addToolTip")
		{
			var id_parts = thealinks[x].id.split("_");
			var rating = id_parts[4];
			var tooltip_text = movies_ratings_getDescription(rating, thealinks[x].title);
			//thealinks[x].setAttribute("tooltiptext", thealinks[x].title);
			thealinks[x].setAttribute("tooltiptext", tooltip_text);
			thealinks[x].removeAttribute("title");
			//thealinks[x].onmouseover= function gomouseover(){ddrivetip(this.getAttribute("tooltiptext"))};
			//thealinks[x].onmouseout= function gomouseout(){hideddrivetip();};
		}
	}
}

var ie  = document.all;
var ns6 = document.getElementById && !document.all;

var enabletip = false;

function ietruebody(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function ddrivetip(thetext, thewidth, thecolor)
{
	if (ns6||ie)
	{
		if (typeof thewidth !== "undefined")
		{
			$("theToolTip").style.width = thewidth +"px";
		}

		if (typeof thecolor!=="undefined" && thecolor!=="")
		{
			$("theToolTip").style.backgroundColor = thecolor;
		}

		$("theToolTip").innerHTML = thetext;
		enabletip = true;
		return false;
	}
}

function positiontip(e)
{
	if (enabletip)
	{
    	var nondefaultpos=false;
		var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
		var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;

		//Find out how close the mouse is to the corner of the window
		var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20;
		var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20;

		var rightedge = ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX;
		var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY;

		var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000;

		//if the horizontal distance isn't enough to accomodate the width of the context menu
		if (rightedge< $("theToolTip").offsetWidth)
		{
			//move the horizontal position of the menu to the left by it's width
			$("theToolTip").style.left=curX-$("theToolTip").offsetWidth+"px";
			nondefaultpos=true;
		}
		else if (curX<leftedge)
		{
			$("theToolTip").style.left="5px";
		}
		else
		{
			//position the horizontal position of the menu where the mouse is positioned
			$("theToolTip").style.left=curX+offsetfromcursorX-offsetdivfrompointerX+"px";
			$("ToolTipPointer").style.left=curX+offsetfromcursorX+"px";
		}

		//same concept with the vertical position
		if (bottomedge<$("theToolTip").offsetHeight){
			$("theToolTip").style.top=curY-$("theToolTip").offsetHeight-offsetfromcursorY+"px";
			nondefaultpos=true;
		}
		else
		{
			$("theToolTip").style.top=curY+offsetfromcursorY+offsetdivfrompointerY+"px";
			$("ToolTipPointer").style.top=curY+offsetfromcursorY+"px";
		}

		$("theToolTip").style.visibility="visible";

		if (!nondefaultpos)
		{
			$("ToolTipPointer").style.visibility="visible";
		}
		else
		{
			$("ToolTipPointer").style.visibility="hidden";}
		}
}

function hideddrivetip()
{
	if (ns6||ie)
	{

		enabletip = false;

		$("theToolTip").style.visibility="hidden";
		$("ToolTipPointer").style.visibility="hidden";
		$("theToolTip").style.left="-1000px";
		$("theToolTip").style.backgroundColor='';
		$("theToolTip").style.width='';
	}
}

