/**
 * @version    $Id$
 * @package    IT_Theme_Framework
 * @author     InnoThemes Team <support@innothemes.com>
 * @copyright  Copyright (C) 2012 InnoThemes.com. All Rights Reserved.
 * @license    GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Websites: http://www.innothemes.com
 */

(function($) {
	$.IT_SampleData = function(params) {
		var self = this;

		// Initialize parameters
		self.params = $.extend({
			base_url: ''
		}, params);

		// Initialize functionality
		self.init();
	};

	$.IT_SampleData.prototype = {
		init: function() {
			var self = this;

			// Init button to install sample data
			$('#it-install-sample-data').unbind('click').bind('click', function(event) {
				event.preventDefault();
	
				// Setup modal to install sample data
				$.IT_SampleData.modal = $('#it-install-sample-data-modal').dialog({
					modal: true,
					autoOpen: false,
					draggable: false,
					resizable: false,
					dialogClass: 'jsn-master',
					width: 800,
					height: 600,
					open: function() {
						// Empty modal content
						$.IT_SampleData.modal.addClass('it-loading').html('');
	
						// Load confirmation screen
						$.getJSON(
							self.params.base_url + '?it-gadget=sample-data&action=confirm',
							function(response, status, request) {
								// Show confirmation screen
								$.IT_SampleData.modal.removeClass('it-loading').html(response.data);
	
								// Setup buttons
								self.start();
							}
						);
					},
					close : function() {
						$.IT_SampleData.modal.dialog('destroy');

						// Check if theme customizer needs to be refreshed
						if (self.reload_theme_customizer) {
							window.location.reload();
						}
					}
				});

				$.IT_SampleData.modal.dialog('open');
			});

			// Handle window resize event to update modal position
			$(window).resize(function() {
				if ($.IT_SampleData.modal) {
					$.IT_SampleData.modal.dialog('option', 'position', 'center');
				}
			});

			// Check if data backup available
			var backup = $('#it-data-backup');

			if (backup.length) {
				var buttons = backup.find('#it-restore-backup-data, #it-remove-backup-data');

				buttons.unbind('click').bind('click', function(event) {
					event.preventDefault();

					// Detect action
					var action = $(this).attr('id') == 'it-restore-backup-data' ? 'restore' : 'remove', button = $(this);

					// Set loading state
					button.children('b').html(button.attr('loading-text')).parent().prepend('<i class="it-icon-loading it-loading" />');

					// Disable buttons
					buttons.addClass('disabled');

					// Request server-side script to restore/remove backup data
					$.getJSON(
						self.params.base_url + '?it-gadget=sample-data&action=' + (action == 'restore' ? 'restore-backup' : 'remove-backup'),
						function(response, status, request) {
							if (status == 'success' && response.status == 'success') {
								button.children('b').html(response.data).parent().children('.it-icon-loading.it-loading').remove();

								if (action == 'restore') {
									// Refresh window
									window.location.reload();
								} else {
									// Hide backup data information after 3 second
									setTimeout(function() {
										backup.fadeOut('slow');
									}, 3000);
								}
							} else {
								button.html(status == 'success' ? response.data : request.responseText);
							}
						}
					);
				});
			}
		},

		start: function() {
			var	self = this,
				btnInstall = $.IT_SampleData.modal.find('button.btn-install');

			// Handle confirmation action
			$.IT_SampleData.modal.find('#it-confirm-agreement').unbind('click').bind('click', function() {
				if (this.checked) {
					btnInstall.removeAttr('disabled');
				} else {
					btnInstall.attr('disabled', 'disabled');
				}
			});

			// Init button to load sample data installation screen
			btnInstall.unbind('click').bind('click', function(event) {
				event.preventDefault();
				$.getJSON(
					self.params.base_url + '?it-gadget=sample-data&action=confirmed',
					function(response, status, request) {
						// Show sample data installation screen
						$.IT_SampleData.modal.html(response.data);

						// Start download sample data package
						self.download();
					}
				);
			});

			// Init button to cancel sample data installation
			$.IT_SampleData.modal.find('button.btn-cancel-install').unbind('click').bind('click', function(event) {
				event.preventDefault();
				$.IT_SampleData.modal.dialog('close');
			});
		},

		download: function(upload) {
			var	self = this,
				download = upload || $('#it-install-sample-data-download-package'),
				toolbar = $('#it-install-sample-data-toolbar');

			// Get buttons
			self.btnConfirmInstall = toolbar.children('button.btn-confirm-install');

			self.btnFinishInstall = toolbar.children('button.btn-finish-install').unbind('click').bind('click', function(event) {
				event.preventDefault();
				$.IT_SampleData.modal.dialog('close');
			});

			self.btnCancelInstall = toolbar.children('button.btn-cancel-install').unbind('click').bind('click', function(event) {
				event.preventDefault();
				$.IT_SampleData.modal.dialog('close');
			});

			// Download sample data package
			$.getJSON(
				self.params.base_url + '?it-gadget=sample-data&action=download' + (upload ? '&uploaded=1' : ''),
				function(response, status, request) {
					// Indicate that download step is completed
					download.addClass('it-complete');

					if (response.status != 'success') {
						// Switch status
						download.find('i.jsn-icon-loading').removeClass('jsn-icon-loading').addClass('jsn-icon-remove');

						// Show error message
						download.find('span.it-status').html(response.data);

						if (response.status == 'outdate' || upload) {
							// Show failure message box
							self.finish('failure', response.data);
						} else {
							// Switch to manual installation mode
							self.manualInstall();
						}
					} else {
						// Switch status
						download.find('i.jsn-icon-loading').removeClass('jsn-icon-loading').addClass('jsn-icon-ok');
	
						if (response.data != '') {
							// Process plugins list
							self.processPlugins(response.data);
						} else {
							// Start importing sample data
							self.import();
						}
					}
				}
			);
		},

		manualInstall: function() {
			var	self = this,
				upload = $('#it-install-sample-data-upload-package'),
				manualInstall = $('#it-install-sample-data-manually');

			// Show manual sample data installation form
			manualInstall.removeClass('hide');

			// Init toolbar buttons
			self.btnConfirmInstall.removeClass('hide').unbind('click').bind('click', function(event) {
				event.preventDefault();

				if (manualInstall.find('input[type="file"]').attr('value') == '') {
					var status = manualInstall.find('span.it-status').removeClass('hide');

					return setTimeout(function() {
						status.fadeOut({
							always: function() {
								status.addClass('hide').css('display', '');
							}
						});
					}, 1000);
				}

				// Submit upload form
				manualInstall.children('form').submit();

				// Hide upload form
				manualInstall.addClass('hide');

				// Hide 'Continue' button
				self.btnConfirmInstall.addClass('hide');

				// Switch loading status
				upload.removeClass('hide');
			});

			// Setup handler
			manualInstall.children('iframe').unbind('load').bind('load', function() {
				// Hide manual install form
				manualInstall.addClass('hide').find('.jsn-icon-loading').removeClass('jsn-icon16');

				// Parse response data
				if (response = $(this).contents().text().match(/\{"status":[^,]+,"data":[^\}]+\}/)) {
					response = $.parseJSON(response[0]);
				} else {
					response = {status: 'failure', data: $(this).contents().text()};
				}

				if (response.status == 'success') {
					self.download(upload);
				} else {
					// Show failure message box
					self.finish('failure', response.data);
				}
			});
		},

		processPlugins: function(listPlugins) {
			var	self = this,
				requiredPlugins = $('#it-install-sample-data-required-plugins');

			// Get element containing optional plugins
			self.optionalPlugins = $('#it-install-sample-data-optional-plugins');

			if (listPlugins.required) {
				// Show list of required plugins
				requiredPlugins.removeClass('hide').html(listPlugins.required);

				// Install required plugins
				self.installPlugins(requiredPlugins);
			}

			if (listPlugins.optional) {
				// Show list of optional plugins
				self.optionalPlugins.html(listPlugins.optional);

				// Setup plugin details toggle
				self.optionalPlugins.find('a.it-plugin-details-toggle').unbind('click').bind('click', function(event) {
					event.preventDefault();

					if ($(this).children().hasClass('icon-plus-sign')) {
						// Show plugin details then switch toggle icon
						$(this).parent().children('p.it-plugin-details').removeClass('hide');
						$(this).children().removeClass('icon-plus-sign').addClass('icon-minus-sign');
					} else {
						// Hide plugin details then switch toggle icon
						$(this).parent().children('p.it-plugin-details').addClass('hide');
						$(this).children().removeClass('icon-minus-sign').addClass('icon-plus-sign');
					}
				});

				// Setup 'Continue' button
				self.btnConfirmInstall.unbind('click').bind('click', function(event) {
					event.preventDefault();

					// Hide 'Continue' button
					self.btnConfirmInstall.addClass('hide');

					// Install optional plugins
					self.installPlugins(self.optionalPlugins);
				});

				if (!listPlugins.required) {
					// Show list of optional plugins
					self.optionalPlugins.removeClass('hide');

					// Show 'Continue' button
					self.btnConfirmInstall.removeClass('hide');
				}
			}
		},

		installPlugins: function(listPlugins) {
			var self = this;

			// Hide all unnecessary elements
			listPlugins.find('input, span.label, a.it-plugin-details-toggle, p.it-plugin-details').addClass('hide');

			// Find all selected plugins
			self.beingInstalled = [];

			listPlugins.find('input').each(function(i, e) {
				if (e.type == 'hidden' || e.checked) {
					self.beingInstalled.push(e);
				}
			});

			if (self.beingInstalled.length) {
				// Start install selected plugins
				self.installing = 0;
				self.installPlugin();
			} else {
				// Start importing sample data
				self.import();
			}
		},

		installPlugin: function() {
			var	self = this,
				plugin = self.beingInstalled[self.installing].value,
				listPlugin = $(self.beingInstalled[self.installing]).parent().parent();

			// Show loading status
			listPlugin.find('i.jsn-icon-loading').addClass('jsn-icon16');

			// Request server to install plugin
			$.ajax({
				url: self.params.base_url + '?it-gadget=sample-data&action=install-plugin&plugin=' + plugin,
				complete: function(request, status) {
					// Indicate that plugin installation step is completed
					listPlugin.addClass('it-complete');

					// Parse response data
					if (response = request.responseText.match(/\{"status":[^,]+,"data":[^\}]+\}/)) {
						response = $.parseJSON(response[0]);
					} else {
						response = {status: 'failure', data: ''};
					}

					if (response.status != 'success') {
						// Switch status
						listPlugin.find('i.jsn-icon-loading').removeClass('jsn-icon-loading').addClass('jsn-icon-remove');

						// Show error message
						listPlugin.find('span.it-status').html(response.data);
					} else {
						// Switch status
						listPlugin.find('i.jsn-icon-loading').removeClass('jsn-icon-loading').addClass('jsn-icon-ok');
					}

					// Increase the number of installed plugin
					self.installing++;

					if (self.installing < self.beingInstalled.length) {
						// Send request to install next selected plugin
						self.installPlugin();
					} else {
						// Installed all plugins
						if (self.optionalPlugins.html() != '' && self.optionalPlugins.hasClass('hide')) {
							// Show list of optional plugins
							self.optionalPlugins.removeClass('hide');

							// Show 'Continue' button
							self.btnConfirmInstall.removeClass('hide');
						} else {
							// Start importing sample data
							self.import();
						}
					}
				}
			});
		},

		import: function() {
			var	self = this,
				element = $('#it-install-sample-data-import-data');

			// State that sample data is being imported
			element.removeClass('hide');

			// Import sample data
			$.ajax({
				url: self.params.base_url + '?it-gadget=sample-data&action=import-data&import=1',
				complete: function(request, status) {
					// Indicate that import step is completed
					element.addClass('it-complete');

					// Parse response data
					if (response = request.responseText.match(/\{"status":[^,]+,"data":[^\}]+\}/)) {
						response = $.parseJSON(response[0]);
					} else {
						response = {status: 'failure', data: ''};
					}

					if (response.status == 'success') {
						// Switch status
						element.find('i.jsn-icon-loading').removeClass('jsn-icon-loading').addClass('jsn-icon-ok');

						// Show success message box
						self.finish('success', response.data);

						// Set a flag for reloading theme customizer
						self.reload_theme_customizer = true;
					} else {
						// Switch status
						element.find('i.jsn-icon-loading').removeClass('jsn-icon-loading').addClass('jsn-icon-remove');

						// Show failure message box
						self.finish('failure', response.data);
					}
				}
			});
		},

		finish: function(status, message) {
			// Prepare status
			status = status || 'success';

			if (status != 'success' && status != 'failure') {
				status = 'failure';
			}

			var self = this, element = $('#it-install-sample-data-' + status + '-message').removeClass('hide');

			// Set success message if any
			if (message) {
				element.find('.it-status-message').html(message).parent().removeClass('hide');
			}

			// Toggle buttons
			self.btnFinishInstall.removeClass('hide');
			self.btnConfirmInstall.addClass('hide');
			self.btnCancelInstall.addClass('hide');
		}
	};
})(jQuery);
