/****************************************************************************
 * This file should be included via:
 * <script type="text/javascript" src="reviews.js"></script>
 * after main jquery.js has been included
 * ***************************************************************************/


/**
 * Function to configure "Do you want to review this XYZ?" layer
 * when user hovers over entity
 * For styling see: http://craigsworks.com/projects/qtip/docs/tutorials/#styling
 *
 * Usage: $(".selector").setupReviewToolTips('type');
 *
 * @author Ben Arwin
 */
//(function($) {

// Flag to indicate whether we've already bound all our events using .live()
$.knerd_review_events_already_bound = false;


$.fn.setupReviewTooltips = function (settings) {
	settings = $.extend({
		reviewType: 'undefined'
	}, settings);

	this.each(function() {
		$(this)
		//.qtip('destroy') // first clear out old qTip bound events for this object type so we don't wind up with dupes
		.qtip({
			content:
				'<div class="qtip-review-rollover">' +
				'<p>Would you like to see reviews for this '+settings.reviewType+'?</p>'+
				'<p><a class="show-reviews" href="javascript:$.show_review_modal(\''+settings.reviewType+'\', \''+$(this).attr('id')+'\', 1);">YES</a></p>' +
				'</div>',
			show:    'mouseover',
			hide:    { when: 'mouseout', fixed: true }, // fixed=true: will not hide if moused over, allowing contents to be clicked
			style: {
				name: 'light' // Inherit from preset style
			},
			position: {
				corner: {
					target: 'rightMiddle',
					tooltip: 'leftMiddle'
				}
			},
			style: {
				border: { width: 3, radius: 10, color: '#E17009'},
				width: 250
			}
		});
	});

	return this;
}; // End setupReviewTooltips custom jquery function

// load the "reviews" content (ajax getReviews.php) into a specified div
$.load_reviews_into_div = load_reviews_into_div;
function load_reviews_into_div(targetDiv, reviewType, id, pageNum)
{
	var $loadedReviews = $(targetDiv).load('/scripts/reviews/ajax/getReviews.php', {
			object_type: reviewType,
			object_id: id,
			p: pageNum
		},
		load_review_callback
	);

	showAjaxLoad($loadedReviews, {
		style:'overlay-light',
		loadingObj: $('<img src="/assets/images/ajaxload/circle_32x32-light.gif" alt="Loading..." width="32" height="32" />')
	});

	return $loadedReviews;
}

// wrapper for load_reviews_into_div that loads them into a modal jquery ui Dialog
$.show_review_modal = show_review_modal;
function show_review_modal(reviewType, id, pageNum)
{
	if ( ! (typeof($.dlg_knerd) == "undefined" || $.dlg_knerd == "undefined") ) {
		$.dlg_knerd.dialog("destroy"); // destroy old dialog so we don't eat up memory
	}

	var $myDialog = $('<div id="knerd_review_dlg_wrapper" class="modal"><div class="inner-ajax" style="position:relative; min-height:390px;"></div></div>');

	$.dlg_knerd = $myDialog.dialog({
			autoOpen: true,
			modal: true,
			title: "Reviews",
			width: 500,
			height: 435,
			close: function() {
				$myDialog.remove(); // kill the contents of the dialog
			}
	}); // end dialog()

	var $loadedReviews = $.load_reviews_into_div( $myDialog.find(".inner-ajax"), reviewType, id, pageNum);

}; // end show_review_modal()


/**
 * Any time we change the DOM in the review dialog, we need to re-register our
 * event handler functions. Otherwise the new content will not trigger the approprate response.
 */
function bindEventHandlers() {

	/* only bind events if they're not already bound (using .live() means only need to once) */
	if ( ! $.knerd_review_events_already_bound ) {

		$(".review-thumb-click").live("click", thumb_click); /* register call back for thumbs up/down clicks */

		$(".review-pagination a.page-link").live("click", paginatorClick ); /* pagination links */

		$(".review-form-toggle").live("click", function() {
			/* When the 'toggle' area is clicked, show/hide the formWrappe (which contains the form) */
			$(this).parent().find(".review-form-wrapper").slideToggle("slow");
		});

		$(".karma a").live("click", function() { return false; } );

		$(".review .delete-review").live("click", deleteReview);

		$.knerd_review_events_already_bound = true;
	}

	// Here we bind things that are safe to do every time (i.e. not "live()")

	// Hovers for 'karma'
	$(".karma a").hover(
		function() { $("<span style='padding-left:10px;'></span>").html($(this).attr("title")).appendTo($(this).parent()); },
		function() { $(this).parent().find("span:last").remove(); }
	);
	// Hover for .review
	$(".review").hover(
		function() { $(this).addClass('review-highlight'); },
		function() { $(this).removeClass('review-highlight'); }
	);


} // end bindEventHandlers


function deleteReview() {

	var reviewObj = $(this).closest(".review");
	var reviewID = reviewObj.attr("id");

	if (confirm("Are you sure you want to delete this review?")) {

		$.post("/scripts/reviews/ajax/processReview.php", {
				review_id: reviewID,
				action: "delete_review"
			},
			function(data) {
				var successFlag = "success:"; // must match flag in processReview.php
				if (data.indexOf(successFlag) == 0) {
					// review was deleted. success!
					reviewObj
						.html(data.substr(successFlag.length))
						.slideDown("fast", function() {
								$(this).highlightFade({}, function() { reviewObj.remove(); });
							});
				}
				else {
					// something went wrong
					alert(data);
				}
			}
		); // end $.post()

		showAjaxLoad(reviewObj); // start ajax spinner immediately

	} // end if confirm()

	return false; // prevent link from firing further
}

/**
 * start an ajax spinner on top of the $targetObj layer
 */
function showAjaxLoad($targetObj, settings) {
	if (typeof($targetObj) != "undefined" && $targetObj != null)
	{
		settings = $.extend({
			/* Default 'loading' graphic */
			loadingObj: $('<img src="/assets/images/ajaxload/circle_32x32.gif" alt="Loading..." width="32" height="32" />')
		}, settings);

		settings.loadingObj.addClass('ajax-loading-object');
		var coords     = _getVerticalCenterXandY($targetObj, settings.loadingObj);

		settings = $.extend({
			style:  'overlay-dark',
			imgTop:  coords.top,
			imgLeft: coords.left,
			height:  $targetObj.height(),
			width:   $targetObj.width()
		}, settings);

		settings.loadingObj.css({ 'top':settings.imgTop, 'left':settings.imgLeft });

		$("<div class='ajax-spinner'></div>")
			.addClass(settings.style)
			.css({  // make the overlay div the same size as the target div
				'height':  settings.height,
				'width':   settings.width,
				'padding-top': $targetObj.css('padding-top'), 'padding-right': $targetObj.css('padding-right'), 'padding-bottom': $targetObj.css('padding-bottom'),'padding-left': $targetObj.css('padding-left')
				//'margin-top': $targetObj.css('margin-top'), 'margin-right': $targetObj.css('margin-right'), 'margin-bottom': $targetObj.css('margin-bottom'),'margin-left': $targetObj.css('margin-left')
			})
			.append(settings.loadingObj)
			.prependTo($targetObj);
	}
}
/**
 * hide the ajax spinner (called from the callback after ajax request has succeeded)
 */
function hideAjaxLoad($targetObj) {
	if (typeof($targetObj) != "undefined" && $targetObj != null) {
		$targetObj.find(".ajax-spinner").remove();
	}
	else {
		$(".ajax-spinner").remove();
	}
}
/**
 * Used by showAjaxLoad()
 * Determine the appropriate 'top' and 'left' coordinates for obj so that it's both vertically and horizontally centered in wrapper
 * The 'obj' must have width and height attributes, or the function will fail.
 */
function _getVerticalCenterXandY(wrapper, obj) {

//	console.log("Width of wrapper is: " + wrapper.width() + " height of wrapper is "+wrapper.height());
//	console.log("Width of obj is: " + obj.attr('width') + " height of obj is "+obj.attr('height'));

	var ret = {
		left:  (  Math.round(wrapper.width() / 2) - Math.round(obj.attr('width') / 2) ),
		top: (  Math.round(wrapper.height() / 2) - Math.round(obj.attr('height') / 2) )
	};
	return ret;
}


function paginatorClick() {

	var $reviewWrapper = $(this).closest(".review-wrapper");

	showAjaxLoad($reviewWrapper, {
		style:'overlay-light',
		loadingObj: $('<img src="/assets/images/ajaxload/circle_32x32-light.gif" alt="Loading..." width="32" height="32" />')
	});

	$reviewWrapper.parent().load('/scripts/reviews/ajax/getReviews.php', {
		p: $(this).attr("rel")
	},
	load_review_callback );
	return false; // prevent link from firing
}


function load_review_callback(loadedDiv) {

	hideAjaxLoad($(loadedDiv)); // probably not necessary, but make sure

	/*
	 * Initialize dialog content (returned by getReviews) here:
	 */

	bindEventHandlers();

	$(".review-form") /* ajaxify the actual form */
	.ajaxForm({
		target: null,
		resetForm: false,
		success: function(data, statusText, xhr, $form) {

			var $reviewWrapper = $form.closest(".review-wrapper");
			var $messageDiv    = $reviewWrapper.find('.review-form-ajax-results');
			$messageDiv.html(''); // blank out any prior messages

			var successFlag = "success:"; // must match flag in processReview.php
			if (data.indexOf(successFlag) == 0) {
				/* Success! */

				// Remove the "no reviews yet" message"
				$reviewWrapper.find(".reviews-none-found").hide();

				// Reset and hide the form
				$form.resetForm();
				$form.closest(".review-form-wrapper").slideUp("slow", function() {
						// Add the review to the top of the reviews section (DOM manip)
						$(data.substr(successFlag.length))
							.prependTo($reviewWrapper.find(".reviews-current:last"))
							.highlightFade();
					});
			}
			else {
				// Validation problem - messages to the target div
				//targetDiv.html(data).highlightFade({bg_start:'red', bg_end:'#eee', duration:2000});
				$messageDiv.hide().html(data).fadeIn();
			}
		}
	}); // end ajaxForm
} // end load_review_callback()


/**
 * Receive "thumbs up" or "thumbs down" clicks from user and call
 * ajax script thumb.php
 * @return boolean Always returns false to prevent link from firing
 */
function thumb_click() {
	$(this).blur(); // get rid of annoying outline around thumb image

//	var msgTarget = $(this).parent().find(".thumbs-message");
//	var upCount   = $(this).parent().find(".thumbs-up-count");
//	var downCount = $(this).parent().find(".thumbs-down-count");
//	var type      = $(this).attr("rel");


	var myclick = this; // so we can reference the clicked object below

	$.get($(this).attr("href"), function(data) {

		//msgTarget.html(data); // DEBUG - shows ajax output
		var successFlag = "Success";
		if (data.indexOf(successFlag) == 0) { // succesfully registered thumb click
			/*
			 * Note: In this scope, $(this) is no longer the object that was clicked
			 */

			// Make this thumb "active"
			$(myclick).removeClass("thumb-inactive");

			// Find the "other thumb" and ensure it's de-activated
			var otherThumb = null;
			if ($(myclick).hasClass("thumbs-up")) {
				otherThumb = $(myclick).parent().find(".thumbs-down");
			}
			else {
				otherThumb = $(myclick).parent().find(".thumbs-up");
			}
			otherThumb.addClass("thumb-inactive");
		}
	});

	return false; // prevent link from firing

} // end thumb_click()



//// HOMETAB 'my reviews' button click
$("#changeMyReviews").live("click", function() {
	// Wrap show_review_modal() and send some special parameters
	// so that only this user's reviews are returned
	$.show_review_modal('mine');
});


//})(jQuery);
