/**
 * Javascript for knerd classifieds section
 */

jQuery(document).ready(function($) {

	KJClassifieds.instance.setupBindings();

	KJClassifieds.instance.setupSearchResultBindings($("#classy_ajax_search #classy_search_results"));

}); // end document.ready()


/************************************************************************
 * Encapsulation for "inbox" view / js functionality (Singleton model)
 ***********************************************************************/

function KJClassifieds() {
	/**
	 * checkbox filters on left side
	 */
	this.$checkboxes = [];

	/**
	 * search form
	 */
	this.$searchform = null;

	this.loadingContent = '<p class="loading-msg">Loading</p>';

}
/**
 * set up a static reference to singleton
 * (setting it up this way for Eclipse's benefit, I know it's not optimal.)
 * @var KJClassifieds
 */
KJClassifieds.instance = new KJClassifieds();

/**
 * setup initial jquery bindings for KJClassifieds
 */
KJClassifieds.prototype.setupBindings = function() {

	/**
	 * search form
	 */
	KJClassifieds.instance.$searchform = $("#frmSearchClassifieds").ajaxForm({
		target: "#classy_ajax_search",
		beforeSubmit: function() {
			// show a "loading" message
			$("#classy_ajax_search").empty().append(KJClassifieds.instance.loadingContent);

			// make sure search result div is visible
			KJClassifieds.instance.showSearchResults();
		},
		success: function() {
			KJClassifieds.instance.setupSearchResultBindings($("#classy_ajax_search #classy_search_results"));
		}
	});

	/**
	 * post ad button
	 */
	$("#btnPostClassyAd").click( function() { KJClassifieds.instance.showAdForm('new', 1); } );

	$("#btnMyClassyAds").click( function() { KJClassifieds.instance.showMyAds(1); } );

	/**
	 * checkbox filters
	 */
	KJClassifieds.instance.$checkboxes = $("#classy_search_checkboxes input:checkbox").click( KJClassifieds.instance.clickedCheckboxFilter );
};

/**
 * when user checks a checkbox filter, we may need to automatically
 * check or uncheck other boxes
 */
KJClassifieds.prototype.clickedCheckboxFilter = function() {
	// if 'all' is checked, uncheck all others
	var cat = $(this).attr("value");
	if (cat == 'all') {
		if ($(this).is(":checked")) {
			// 'all' is checked, so CHECK all other categories
			KJClassifieds.instance.$checkboxes.attr("checked","checked");
		}
	} else {
		if ( ! $(this).is(":checked") ) {
			// when a box is unchecked, 'all' no longer applies, so uncheck the 'all' box
			KJClassifieds.instance.$checkboxes.filter("[value=all]").removeAttr("checked");
		}
	}
};

/**
 * Load and display the "Post ad" form
 * triggered when "Post Ad" button is clicked
 * @return
 */
KJClassifieds.prototype.showAdForm = function(adID, fromPage) {
	KJClassifieds.instance.hideAllAjaxContent(); // hide other ajax content

	// load and show 'post ad' form
	var $ad_form = $("#classy_ajax_post").html(KJClassifieds.instance.loadingContent).load("/scripts/classifieds/ajax.classy-edit-form.php", {
			ad_id: adID
		},
		function() { // set up bindings for the <form>
			KJClassifieds.instance.setupAdFormBindings($ad_form, fromPage);
		}
	)
	.show();
};

/**
 *
 * @param $ad_form
 * @param fromPage (page in 'Manage My Ads' to jump back to after successful ad/edit
 * @return
 */
KJClassifieds.prototype.setupAdFormBindings = function($ad_form, fromPage) {
	// knerd buttons
	$ad_form.find(".knerd-button").button();

	// show different form fields based on which category is chosen
	$ad_form.find("[name='category']").change(function() {
		// show or hide form-parts based on which category is choosen
		var cat = $(this).val();
		var $formParts = $ad_form.find(".form-parts .form-part").hide(); // hide ALL form-part blocks
		if (cat != "") {
			$formParts.filter(".form-part-"+$(this).val()).show(); // show ONE form-part block
			$ad_form.find("input:submit").show();
		} else {
			$ad_form.find("input:submit").hide(); // hide the 'submit' button until they've choosen a category
		}
	})
	.change(); // trigger event handler so that appropriate form sections are displayed when editing

	// textarea counter TODO: may not need
	$ad_form.find("textarea[name=description]").textareaCount({
		'maxCharacterSize': 500, // matches limit set in PHP.
		'textFontSize': '12px',
		'textColor': '#5C2306',
		'textAlign': 'right',
		'warningColor': '#CC3300',
		'warningNumber': 40,
		'isCharacterCount': true,
		'isWordCount': false
	});

	// ajaxForm binding to handle ad submission
	$ad_form.find("#frmEditCreateClassified").ajaxForm({
		beforeSubmit: function() {
			$("#classy_form_feedback").empty().show();
		},
		success: function(response, status, xhr, $form) {
			var $feedbackDiv = $("#classy_form_feedback");
			$feedbackDiv.empty();
			try {
				var json = $.parseJSON(response);
				if (json.success) { // successfully added new ad, or updated an existing ad.
					$feedbackDiv.text("Success! (json)");

					// now give user option to upload pics, if it was a new ad
					if (json.allow_pic_upload) {
						KJClassifieds.instance.showPicUploadForm(json.classified_id, fromPage);
					}
					else {
						//show it in the 'my ads' section now
						KJClassifieds.instance.showMyAds(fromPage); // jump back to 'fromPage' for seamlessness
					}
				}
				else {
					// display error messages
					displayErrorMessages($feedbackDiv, json.messages);
				}
			} catch (err) {
				debugLog(err);
			}
		}
	});
};

/**
 * Pic uploads, associate with classified
 * @param adID
 * @param fromPage what page in 'manage my ads' to jump back to after done editing ad
 * @return
 */
KJClassifieds.prototype.showPicUploadForm = function(adID, fromPage) {
	KJClassifieds.instance.hideAllAjaxContent(); // hide other ajax content

	var $picContainer = $("#classy_upload_pics").load("/scripts/classifieds/ajax.pic-upload-form.php", {
			ad_id: adID,
			from_page: fromPage
		},
		function() {
			KJClassifieds.instance.setupPicUploadFormBindings($picContainer, adID);
		}
	)
	.show();
};

/**
 *
 * @param $picContainer
 * @param fromPage
 * @return
 */
KJClassifieds.prototype.setupPicUploadFormBindings = function($picContainer, adID) {

	// buttons
	$picContainer.find(".knerd-button").button();

	$picContainer.find(".btn-del-classy-image").filter("[rel!='edit']").hide();

	var $picForms = $picContainer.find("form.frm-classy-pic-upload");

	// submit the upload form as soon as an image is selected
	$picForms.find(":file").change(function() {
		$(this).closest("form.frm-classy-pic-upload").submit();
	});

	// The actual ajax form (handle submit, validation, etc)
	$picForms.ajaxForm({
		dataType: 'json',
		iframe: true,
		data: {
			ad_id: adID,
			method: "ajax_uploadImage"
		},
		beforeSubmit: function(arr, $form, options) {
			// start spinner
			$form.find(".spinner").show();

			// clear out old messages/images
			$form.find(".image-preview").empty();
		},
		success: function(json, xhr, status, $form) {
			// stop spinner
			$form.find(".spinner").hide();

			// initialize 'pic_id' input
			var $pic_id_input = $form.find("input[name='pic_id']");
			$pic_id_input.val('');

			if (json.success) {
				// Successfully uploaded image, path = json.new_image_path
				if (json.new_image_path) {
					var $newImage = $("<img alt='' />").attr("src", json.new_image_path);
					$form.find(".image-preview").html($newImage); // display image

					$form.find(".btn-del-classy-image").show();   // show delete button
					$form.find(".file-input").hide(); // hide the file input

					$pic_id_input.val(json.new_image_id); // so that delete button knows what to delete..
				}
			} else {
				// ERROR uploading image
				var defaultMessage = "An error occured, please check the image and try again"; // used if json.messages is empty
				displayErrorMessages($form.find(".image-preview"), json.messages, defaultMessage);
			}
		}
	});

	// DELETE IMAGE
	$(".btn-del-classy-image").click(function(event) {
		event.preventDefault();

		var $picForm = $(this).closest("form");

		var picID = $picForm.find("input[name='pic_id']").val();
		//debugLog("delete image: " + picID);

		showAjaxLoad( $picForm.find(".image-preview") );

		$.post("/scripts/classifieds/ajax-classy-hook.php", {
				method: 'ajax_deleteImage',
				pic_id: picID
			},
			function(response) {

				hideAjaxLoad( $picForm.find(".image-preview") );

				try {
					var json = $.parseJSON(response);
					if (json.success) {
						// image successfully removed, emptying preview and clearing form (check hidden value)
						$picForm.find(".image-preview").empty();
						$picForm.clearForm(); // unreliable -- must clear out values manually below..
						$picForm.find(":hidden").val('');
						$picForm.find(":file").val('');

						$picForm.find(".btn-del-classy-image").hide(); // hide delete button
						$picForm.find(".file-input").show();           // show file input
					}
					else {
						// failed to delete image, show messages
						var $msgs = $("<div></div>");
						displayErrorMessages($msgs, json.messages, "Error: could not delete pic, displayig error messages in image-preview pane");
						$picForm.find(".image-preview").append($msgs);
					}
				} catch (err) {
					debugLog(err);
				}
			},
			'html'
		);
	});
};

/**
 * this only makes the search results visible, the ajax functionality is set up in setupBindings with ajaxForm
 * @return
 */
KJClassifieds.prototype.showSearchResults = function() {
	KJClassifieds.instance.hideAllAjaxContent(); // hide other ajax content
	$("#classy_ajax_search").show();
};
/**
 * After search results are added to the DOM, we need to setup bindings for
 * the elements therein
 * @return
 */
KJClassifieds.prototype.setupSearchResultBindings = function($results) {

	// knerd buttons
	$results.find(".knerd-button").button();

	// the "read more" / "read less" toggle
	var $readMoreLinks = $results.find(".toggle-link");
	$readMoreLinks.click(function(event) {
		var $desc = $(this).closest(".description");
		$desc.find(".toggle-me").toggle();
		event.preventDefault();
	});

	// hover effect for search results
	$results.find(".classy-search-result").hover(
			function() { $(this).addClass("hover"); },   // mouse-over
			function() { $(this).removeClass("hover"); } // mouse-out
	);

	// Set up pagination controls for search results (that were just displayed)
	var $pagerButtons = $results.find(".pagination a");
	$pagerButtons.click( function(event) {
		event.preventDefault();
		var currentPage = parseInt(KJClassifieds.instance.$searchform.find(":hidden[name=display_page]").val());
		var newPage = -1;
		if ($(this).hasClass("next")) {
			newPage = currentPage+1;
		}
		else if ($(this).hasClass("prev")) {
			newPage = currentPage-1;
		}
		else if ($(this).hasClass("jump-to-page")) {
			newPage = parseInt($(this).text());
		}

		if (newPage > 0) {
			KJClassifieds.instance.$searchform.find(":hidden[name=display_page]").val(newPage);
			KJClassifieds.instance.$searchform.submit();
		}
	});
};

/**
 * load and display the "My Ads" view
 */
KJClassifieds.prototype.showMyAds = function(pageNum) {
	KJClassifieds.instance.hideAllAjaxContent();// hide other ajax content

	// load content thru ajax call
	var $myads = $("#classy_my_classifieds").html(KJClassifieds.instance.loadingContent).load("/scripts/classifieds/ajax.classy-my-ads.php", {
		display_page: pageNum
	},
	function() { // content loaded, setup bindings now
		KJClassifieds.instance.setupMyAdsBindings($myads);
	})
	.show(); // make visible
};
/**
 * bind knerd-buttons (and anything else we need for JS)
 *
 * @param $myads The container for the just-loaded "Manage My Ads" content
 */
KJClassifieds.prototype.setupMyAdsBindings = function($myads) {
	$myads.find(".knerd-button").button();

	$myads.find("#my_classifieds_list > .my-classified").hover(
			function() { $(this).addClass("hover"); },    // mouse-over
			function() { $(this).removeClass("hover"); }  // mouse-out
	);
};

KJClassifieds.prototype.displayAd = function(adID) {
	KJClassifieds.instance.hideAllAjaxContent(); // hide other ajax content
	var $container = $("#classy_display_ad").html(KJClassifieds.instance.loadingContent).load("/scripts/classifieds/ajax.view-ad.php", {
			ad_id: adID
		},
		function() {
			// setup bindings for the 'view ad' page
			$container.find(".knerd-button").button();
			$container.find(".back-to-search").click(function(event) {
				event.preventDefault();
				KJClassifieds.instance.showSearchResults();
			});
		}
	)
	.show();
};

/**
 * hides all .classy-ajax-content blocks
 * @return
 */
KJClassifieds.prototype.hideAllAjaxContent = function() {
	$("#classy_right_col .classy-ajax-content").hide();
};

KJClassifieds.prototype.deleteAd = function(adID, fromPage) {

	var sel = '#my_classified_' + adID;
	var $adToDelete = $(sel);

	jConfirm("Really delete ad?", "Delete Confirmation", function(resp) {
		if (resp) {
			$.post("/scripts/classifieds/ajax-classy-hook.php", {
					method: "ajax_deleteAd",
					args: [adID]
				},
				function(response) {
					try {
						var json = $.parseJSON(response);
						if (json.success) {
							// successul delete
							$adToDelete.fadeOut("slow", function() {
								KJClassifieds.instance.showMyAds(fromPage);
							});
						}
						else {
							if (json.message) {
								jAlert(json.message, "Error");
							} else {
								jAlert("An error occured and this ad could not be deleted. Please try again later", "Error");
							}
						}
					} catch (err) {
						debugLog(err);
					}

				},
				'html'
			); // end $.post
		}
	});
}; // end deleteAd

/**
 * wrapper for showAdForm that tells it which ad to edit, and also what page
 * to jump back to after done editing.
 *
 * @param adID the ad id
 * @param fromPage the page in 'my ads' clicked from
 * @return
 */
KJClassifieds.prototype.editAd = function(adID, fromPage) {
	KJClassifieds.instance.showAdForm(adID, fromPage);
};

