var reviewSubjectDlg;

function showReviewSubjectDlg(sid) {
//  if (GLOBALS.uid < 0) {
//    window.location = GLOBALS.loginUrl + '?subjectId=' + sid + '&next=viewSubject';
//    return;
//  }

  if (!reviewSubjectDlg) {
    reviewSubjectDlg = new ReviewSubjectDlg(sid);
	  reviewSubjectDlg.spawnOverlay();
  }
  else
  {
	  reviewSubjectDlg.reinitialize();
  }
  reviewSubjectDlg.show();
}

ReviewSubjectDlg = function(sid){


    this.submitTrigger = function() {
	// used to trigger form from inside the editor iframe

	$('#reviewForm').submit();
    }

    this.printRelationships = function() {

	out = '<select id="reviewSubject_RelationshipType" name="relationshipType">' +
	    '<option id="reviewSubject_srt_UNKNOWN" value="UNKNOWN">my relationship with ' + GLOBALS['sname'] + ' is&hellip;</option>' +
	    '<option id="reviewSubject_srt_CLIENT" value="CLIENT">(Potential) Client</option>' +
	    '<option id="reviewSubject_srt_SUPPLIER" value="SUPPLIER">Supplier</option>' +
	    '<option id="reviewSubject_srt_CO_WORKER" value="CO_WORKER">Co-worker</option>' +
	    '<option id="reviewSubject_srt_FRIEND" value="FRIEND">Friend</option>' +
	    '<option id="reviewSubject_srt_FAMILY" value="FAMILY">Family</option>' +
	    '<option id="reviewSubject_srt_READER_LISTENER_VIEWER" value="READER_LISTENER_VIEWER">Reader/Listener/Viewer</option>' +
	    '<option id="reviewSubject_srt_CRITIC_OBSERVER" value="CRITIC_OBSERVER">Critic/Observer</option>' +
	    '<option id="reviewSubject_srt_PEER" value="PEER">Peer</option>' +
	'</select>';

	return out;
    }

    this.loadRoles = function(withCheckbox) {

	// boolean argument withCheckbox controls whether or not to create checkboxes

	theUrl = GLOBALS['contextPath'] + '/ajax/reviewSubject?init&subjectId=' + sid;

	$.ajax({
	    async: false,	// these roles must load before anything else happens
	    url: theUrl,
	    type: 'GET',
	    dataType: 'json',
	    error: function(){
		alert('Error loading subject roles.');
	    },
	    success: function(arg){
		nuRolesHtml = '';

		for (i=0; i< arg['subjectRoles'].length; i++) {
		    if (withCheckbox) {
			nuRolesHtml += '<input type="radio" name="roleIds" value="' + arg['subjectRoles'][i]['roleId'] + '" class="roleIds">';
		    }
		    nuRolesHtml += '<span class="roleFont">' + arg['subjectRoles'][i]['roleName'] + '</span><br />';
		}

		$('#roleList').html(nuRolesHtml);
	    }
	});

    }

    this.spawnOverlay = function() {

	//editor init

	theEditor		= new FCKeditor('fck-content');
	theEditor.BasePath	= GLOBALS['contextPath'] + '/js/fckeditor/';
	theEditor.Height	= '250';

	//produce the overlay

	$('#subjectPane').append(
	    '<div id="reviewOverlay" style="display:none">' +
		'<div id="rsDirections"></div>' +
		'<form action="' + GLOBALS['contextPath'] + '/ajax/reviewSubject?save" method="POST" id="reviewForm">' +
			theEditor.CreateHtml() +
			'<input type="hidden" name="content" value="" />' +
			'<input type="hidden" name="subjectId" value="' + sid + '" />' +
			 this.printRelationships() +
		'</form>' +
	    '</div>'
	);

	//make it resizable

	this.overlay = $('#reviewOverlay');

	this.overlay.draggable({ handle: '#rsDirections' }).resizable({
		handles:	'se',
		minWidth:	'400',
		minHeight:	'300',

		//jQuery UI's resizable().alsoResize is buggy when used with FCKEditor
		//so use start/stop events instead and hide contents during resize

		start:		function(){
		    $('#reviewForm').hide();
		},
		stop:		function() {
		    nuFrameHeight = $('#reviewOverlay').height() - 50;
		    $('#fck-content___Frame').height(nuFrameHeight);
		    $('#reviewForm').show();
		}
	 });

	// this works around a bug with jQuery UI < 1.6rc4 and Safari that makes
	// select dropdowns unusable when inside a resizable() or draggable() element

	if ( jQuery.browser.safari ) {
	    jQuery('#reviewSubject_RelationshipType').hover(function() {
		    $('#reviewOverlay').resizable('destroy');
		    $('#reviewOverlay').draggable('destroy');
		},
		function() {
		    $('#reviewOverlay').draggable().resizable({
			handles:	'se',
			minWidth:	'400',
			minHeight:	'300',

			start:		function(){
			    $('#reviewForm').hide();
			},
			stop:		function() {
			    nuFrameHeight = $('#reviewOverlay').height() - 50;
			    $('#fck-content___Frame').height(nuFrameHeight);
			    $('#reviewForm').show();
			}
		    });
		}
	    );
	}

	//form submit event

	$('#reviewForm').submit(function(){
	    theForm = $(this);
	    go	= true;


	    // get checked roles from left column

	    theRoles = $('#roleList input[name=roleIds]:checked');

	    // roles validation

	    if (theRoles.length < 1) {
		go = false;
		alert('Please select a role from the left column.');
	    }
	    else {

		 //generate hidden fields for role values

		theForm.append('<div style="display:none" id="rolesDiv"></div>');

		theRoles.each(function() {
		    $('#rolesDiv').append('<input type="hidden" class="roleFont" name="roleId" value="' + this.value +'" />');
		});

		 //more validation

		if (FCKeditorAPI.GetInstance('fck-content').GetHTML() == '') {
		    go = false;
		    alert('Please enter a review of this subject in the editor.');
		}

		else if (theForm.children('#reviewSubject_RelationshipType').val() == 'UNKNOWN') {
		    go = false;
		    alert('Please choose a relationship.');
		}
	    }

	    // get editor content

	    theForm.children('input[name=content]').val(FCKeditorAPI.GetInstance('fck-content').GetHTML());

	    // submit the form, hide the overlay, reload roles

	    if (go) {
		$.ajax({
		    url: this.action,
		    type: 'POST',
		    data: $(this).serialize(),
		    dataType: 'json',
		    error: function(){
			alert('Error processing the review.');
		    },
		    success: function(arg){
			if (arg['error']) {

			    message = '';

			     for (var i = 0; i < arg.errors.length; i++) {
				message += arg['errors'][i] + '\n\n';
			     }
			    alert('Error(s): \n\n' + message);
			}
			if (arg['redirectTo']) {
			    window.location = arg['redirectTo'];
			}
		    }
		});
		reviewSubjectDlg.hide();
	    }
	    return false;
	});

    }

    this.show = function() {

	this.overlay.fadeIn(1500);

	// button turns to arrow

	$('#subjectPane').prepend(
	    '<div id="rsBtn-wrapper">' +
		'<div class="doBBox"><span id="rsBtn-message">please select a <span class="roleFont">Role</span></span>' +
	    '</div>'
	);

	theArrow 	= $('#rsBtn-wrapper');
	theTrigger	= $('#reviewSubjectButton');
	theMessage	= $('#rsBtn-message')

	theArrow.css({
	    'left':	theTrigger.offset().left,
	    'top':	0
	});

	theTrigger.hide();
	theArrow.show();

	theArrow.animate({
	    left	: 270,
	    top		: 60
	}, 1500 );

	// create radio buttons and add role link

	reviewSubjectDlg.loadRoles(true);

	// change arrow to 'thanks' after a role is selected, update role in directions

	$('#roleList input[name=roleIds]').change(function(){
	    theMessage.hide();
	    theMessage.html('thanks');
	    theMessage.fadeIn();

	    theRole 		= $(this).next(".roleFont").html();
	    theRole		= theRole.replace(/^\* /, '');
	    theDirections 	= 'please review ' + GLOBALS['sname'] + ' in the <span class="roleFont">Role</span> of ' + theRole;

	    $('#rsDirections').html(theDirections);
	});

    }

    this.hide = function() {

	this.overlay.hide();

	// reset review button, remove role radio buttons, role values in overlay

	$('#rsBtn-wrapper, #roleList input.roleIds, #rolesDiv').remove();
	$('#reviewSubjectButton').show();
    }

    this.reinitialize = function () {

	// reset editor area, reset all css affected by resizable()

	FCKeditorAPI.GetInstance('fck-content').SetHTML('');
	$('#fck-content___Frame').height(250);
	this.overlay.css({'width':400, 'height':300, 'left':'277px', 'top':'105px'});
    }
}