/*  reviewjs.js
 *      
 *      This JavaScript file contains all JavaScript/AJAX Functionality related
 *      to reviews. It handles the inline AJAX Responses and will Live
 *      Preview for reviews.
 *
 *      The code in this file contains a large amount of jQuery calls. Do not
 *      attempt to load this library without first loading jQuery. This code
 *      is known to work with jQuery 1.2.6
 */

/*  initReviews()
 *      Initialise Review Centric JavaScript.
 *      Primarily, this involves the Live Preview Bindings for the Review Box.
 */
function initReviews()
{
    //Wait until the DOM is ready to be manipulated
    $(document).ready(function(){
		//Show all of the active elements
		$("#mode_area"  ).show();
		$("#verify"     ).hide();
		$("#submit_btn" ).hide();
		$("#edit_btn"   ).hide();
		
		/* Bind the Preview Button */
		$("#preview_btn").click(function(){
			/* Change Object Visibilities */
			/* Hide the Following */
			$("#preview_btn"    ).hide();
			$("#edit_area"      ).slideUp("normal");
			/* Show the Following */
			$("#edit_btn"       ).show().css('display', 'inline');
			$("#submit_btn"     ).show().css('display', 'inline');
			$("#preview_area"   ).slideDown("normal");
			$("#verify"         ).slideDown("normal");
			
			/* Handle the AJAX Live Preview */
			$("#live_preview").html('Loading...');
			$.post('reviewpreview.php', { 	review:     $("#review").val(), 
											reviewer:   $("#reviewer").val(), 
											chapter:    $("#chap_name").html()}, 
			function(data){
				$("#live_preview").html(data);
			});
		});
		
        /* Bind the Edit Button */
		$("#edit_btn").click(function(){
            /* Change Object Visibilities */
			/* Hide the Following */
			$("#edit_btn"       ).hide();
			$("#submit_btn"     ).hide();
			$("#preview_area"   ).slideUp("normal");
			$("#verify"         ).slideUp("normal");
			/* Show the Following */
			$("#preview_btn"    ).show();
			$("#edit_area"      ).slideDown("normal");
		});
	});
}

/*  initResponses()
 *      Initialise Response Centric JavaScript.
 *      Primarily, this involves rebinding the Respond links to thier inline
 *      AJAX Bindings.
 */
function initResponses(responseForm)
{  
    // Wait until the DOM is ready to be manipulated
    $(document).ready(function(){
        // Unbind the hrefs from the Respond Links
        $(".response_link").attr("href", "javascript:;");
        
        // Bind the Click Function
        $(".response_link").click( function() {
            //Dismantle any previous response boxes
            $(".respond_zone").slideUp('slow').html('');
            //Get Review Info
            var reviewInfo = getReviewInfo(this);
            //Insert new response box
            $(this).parents("blockquote").children(".respond_zone").html(draw_form(reviewInfo)).slideDown('slow');
            //Start the submit button disabled
            $("#response_submit_btn").get(0).disabled = true;
            //Set Bindings on Response Box
            setResponseBindings();
        });
        
        /*  draw_form()
         *      Draw the Inline AJAX Response Form
         */
        function draw_form(info)
        {
            var finalForm = responseForm;
            // Replace all instances of %VAR% in the form. VAR represents indices of info.
            jQuery.each(info, function(ind, val){
                finalForm = finalForm.replace('%' + ind + '%', val);
            });
            return finalForm;
        }
        
    });
}

/*  getReviewInfo()
 *      Extract information about a certain review.
 *      The refrenceElement passed to the function should represent a DOM
 *      Element which exists within the bounds of that review.
 */
function getReviewInfo(refrenceElement)
{
    var reviewInfo = $(refrenceElement).parents(".ReviewContent").eq(0).children(".ReviewInfo").eq(0).html();
    eval('reviewInfo = ' + reviewInfo + ';');
    return reviewInfo;
}

/*  setResponseBindings()
 *      This function rebinds the various buttons on the response form. This
 *      needs to be called each time the response form is created and inserted.
 */
function setResponseBindings()
{
    /* Rebind the Cancel Button */
    $("#response_cancel_btn").click(function(){
        $(this).parents(".respond_zone").slideUp('slow');
    });
    
    /* Rebind the Preview Button */
    $("#response_preview_btn").click(function(){
        //Bring the Preview Area in to View, and Remove the Edit area from View
        $("#response_edit"          ).slideUp('slow');
        $("#response_preview"       ).slideDown('slow');
        //Reconfigure the Action Buttons
        $("#response_edit_btn"      ).show().css('display', 'inline');
        $("#response_submit_btn"    ).show().css('display', 'inline');
        $("#response_preview_btn"   ).hide();
        //Disable the Submit Button until it passes all tests
        $("#response_submit_btn"    ).get(0).disabled = true;
        
        //Get Info about this Review
        var reviewInfo = getReviewInfo(this);
        
        //Process the Preview
        $.ajax({ cache: false, data: { mode: 'preview', parent: reviewInfo.reviewid, response: $("#response").val() }, error: function(XMLHttpRequest, textStatus, errorThrown){
            //An error occurred. Most likely scenario is a timeout.
            $("#response_preview_content").html("An error occurred whilst generating your preview.");
        }, success: function(data, textStatus){
            // Ajax Request Succeeded.
            //Parse the Response
            var previewInfo;
            eval('previewInfo = ' + data + ';');
            
            //Enable/Disable Submit Button according to the error state of the response
            $("#response_submit_btn").get(0).disabled = !previewInfo.accept;
            
            //Insert Error Messages
            if(!previewInfo.accept) {
                //There were errors
                $("#response_info"      ).html(unescape(previewInfo.errors));
                $("#response_error_bar" ).show();
            } else {
                //There were no errors
                $("#response_info"      ).html('');
                $("#response_error_bar" ).hide();
            }
            
            //Show Preview
            $("#response_preview_content").html(unescape(previewInfo.appendage));
            
            //Correct Review
            $("#response").val(unescape(previewInfo.response));
            
        }, timeout: 10000, type: 'POST', url: 'respond.php'});
    });
    
    /* Rebind the Edit Button */
    $("#response_edit_btn").click(function(){
        //Bring the Edit Area in to View, and Remove the Preview area from View
        $("#response_preview"       ).slideUp('slow');
        $("#response_edit"          ).slideDown('slow');
        //Reconfigure the action buttons
        $("#response_edit_btn"      ).hide();
        $("#response_preview_btn"   ).show().css('display', 'inline');
        $("#response_submit_btn"    ).hide();
        //Set the preview zone back to the loading indicator
        $("#response_preview_content").html('Loading...');
    });
    
    /* Rebind the Submit Button */
    $("#response_submit_btn").click(function(){
        //Hide the Action buttons whilst we push our response
        $("#response_buttons"   ).hide();
        $("#response_wait"      ).show().css('display', 'inline');
        
        //Get Info about this Review
        var reviewInfo = getReviewInfo(this);
        var submit_btn = this;
        
        //Process the Submit
        $.ajax({ cache: false, data: { mode: 'inline', parent: reviewInfo.reviewid, response: $("#response").val() }, error: function(XMLHttpRequest, textStatus, errorThrown){
            //An error occurred. Most likely scenario is a timeout.
            $("#response_info").html("An error occurred whilst submitting your response.<br />");
            //Reenable Action Buttons
            $("#response_buttons"   ).show().css('display', 'inline');
            $("#response_wait"      ).hide();
        }, success: function(data, textStatus){
            // Ajax Request Succeeded.
            //Parse the Response
            var submitInfo;
            eval('submitInfo = ' + data + ';');
            
            //Enable/Disable Submit Button according to the error state of the response
            $("#response_submit_btn").get(0).disabled = !submitInfo.accept;
            
            //Insert Error Messages
            if(!submitInfo.accept) {
                //There were errors
                $("#response_info"      ).html(unescape(submitInfo.errors));
                $("#response_error_bar" ).show();
            } else {
                //There were no errors
                $("#response_info"      ).html('');
                $("#response_error_bar" ).hide();
                
                //OK, Response Done!
                $(submit_btn).parents(".respond_zone").html('<br /><br />' + unescape(submitInfo.appendage)).removeClass("respond_zone");
            }            
        }, timeout: 10000, type: 'POST', url: 'respond.php'});
    });
}
