/**
 * @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_ColumnSettings = function(params) {
		var self = this;

		// Initialize parameters
		self.params = $.extend({
			id: '',
			base_url: '',
			columns: null,
			ratio: {2: {aside: 3, main: 9}, 3: {aside: 3, main: 6}},
			html_order: null,
			boundary: null,
			sortable: false,
			resizable: true,
		}, params);

		// Get container
		self.container = self.container || $('#' + self.params.id);

		// Initialize functionality
		$(window).load($.proxy(self.init, self));

		// Handle window resize event
		$(window).resize(function(event) {
			if (event.target == window) {
				self.timer && clearTimeout(self.timer);
				self.timer = setTimeout($.proxy(self.init, self), 500);
			}
		});
	};

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

			// Check element's visibility
			var container = self.container;

			while (container[0].nodeName != 'BODY') {
				if (container.hasClass('hide') || container.css('display') == 'none') {
					return;
				}

				container = container.parent();
			}

			// Hide all container element of column width option type
			$('.it-form-field-column-settings > ul').addClass('hide');

			// Get nested column(s)
			self.columns = self.columns || self.container.children('li');

			// Set default boundary to parent element
			if (!self.params.boundary) {
				self.params.boundary = self.container.parent();
			}

			// Reset width for necessary elements
			self.columns.children().css('width', 0);
			self.container.css('width', '100%').removeClass('hide');

			// Initialize variables
			self.maxWidth = self.params.boundary.width();
			self.maxHeight = self.columns.height();
			self.spacing = parseInt(self.columns.css('margin-right'));
			self.step = parseInt((self.maxWidth - (self.spacing * 11)) / 12);

			// Calculate width for resizable columns
			var total = 0;

			self.columns.children().each(function(i, e) {
				// Calculate column width
				var	span = parseInt($(e).attr('class').replace('col-md-', '')),
					width = (self.step * span) + (self.spacing * (span - 1));

				$(e).css('width', width + 'px');

				// Count total width
				total += $(e).parent().outerWidth(true);
			});

			// Update width for container
			self.container.css('width', total + 'px');

			// Initialize sortable
			if (self.params.sortable) {
				self.container.sortable({
					axis: 'x',
					placeholder: 'ui-state-highlight',
	
					start: function(event, ui) {
						ui.placeholder.append(ui.item.children().clone());
					},
	
					stop: function(event, ui) {
						// Refresh columns ordering
						self.columns = self.container.children('li');
	
						// Re-initialize resizable
						self.initResizable();
					}
				});
	
				self.container.disableSelection();
			}

			// Initialize resizable
			if (self.params.resizable) {
				self.initResizable();

				// Generate grid preview
				self.grids = self.container.parent().children('.it-form-field-column-settings-grid-preview');

				if (!self.grids.length) {
					self.grids = $('<div />', {'class': 'it-form-field-column-settings-grid-preview'}).appendTo(self.container.parent());
		
					for (var i = 0; i < 11; i++) {
						self.grids.append($('<div />'));
					}
				}
	
				self.grids.children().each(function(i, e) {
					// Calculate left position for this grid
					var left = (self.step * (i + 1)) + (parseInt(self.columns.css('margin-left')) * (i + 1)) + (parseInt(self.columns.css('margin-right')) * i);
	
					$(e).css({
						top: '-' + self.maxHeight + 'px',
						left: left + 'px',
						height: self.maxHeight + 'px'
					});
				});

				// Initialize tool-tips
				self.container.find('.caption > .has-tips').tipsy({
					gravity: 'nw',
					fade: true
				});
			}

			// Un-hide all container element of column width option type
			$('.it-form-field-column-settings > ul').removeClass('hide');

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

		setColumns: function(columns) {
			var self = this;

			// Get columns
			self.columns = self.columns || self.container.children('li');

			// Clone container to store new column set
			var container = self.container.clone().empty(), total_span = 0;

			// Destroy resizable objects
			self.columns.children().each(function(i, e) {
				!$(e).hasClass('ui-resizable') || $(e).resizable('destroy');
			});

			// Process new column set
			columns = columns.split(',');

			for (var i = 0; i < columns.length; i++) {
				var	column = self.columns.filter('#' + self.params.id + '-' + columns[i]).removeClass('first-column').removeClass('last-column'),
					input = column.find('input');

				if (!column.length) {
					column = self.columns.eq(0).removeClass('first-column').removeClass('last-column').clone().attr('id', self.params.id + '-' + columns[i]);
					input = column.find('input');

					if (columns[i] == 'main-content') {
						column.html(self.params.columns[columns[i]]);
					} else {
						var link = column.find('.caption > a');

						if (!link.length) {
							link = $('<a class="it-sidebar-settings icon-cog has-tips" target="_blank" />').appendTo(column.find('.caption').html(''));
						}

						link.attr('href', self.params.base_url).attr('original-title', self.params.columns ? self.params.columns[columns[i]] : columns[i]);
					}

					var field_name = input.attr('name'), new_field_name = columns[i];

					// Check if HTML order is specified
					if (self.params.html_order && typeof self.params.html_order[columns[i]] != 'undefined') {
						new_field_name = self.params.html_order[columns[i]] + ':' + new_field_name;
					}

					// Update column name
					input.attr('name', field_name.replace(/^(.+)\[[^\]]+\]$/, '$1[' + new_field_name + ']'));
					input.closest('*[data-target]').attr('data-target', new_field_name);
				}

				// Set necessary class for first and last column
				i > 0 || column.addClass('first-column');
				i < (columns.length - 1) || column.addClass('last-column');

				// Re-append columns to container
				container.append(column);

				// Count total span
				total_span += parseInt(input.val().replace('col-md-', ''));
			}

			// Check if column span need to be altered
			if (total_span != 12) {
				var num_col = columns.length, has_main = container.children('#' + self.params.id + '-' + 'main-content');

				if (has_main.length && self.params.ratio && self.params.ratio[num_col]) {
					container.children().each(function(i, e) {
						var is_main = $(e).attr('id') == (self.params.id + '-' + 'main-content') ? true : false;

						if (is_main) {
							$(e).find('input').val('col-md-' + self.params.ratio[num_col].main);
							$(e).children('div').removeAttr('class').addClass('col-md-' + self.params.ratio[num_col].main);
						} else {
							$(e).find('input').val('col-md-' + self.params.ratio[num_col].aside);
							$(e).children('div').removeAttr('class').addClass('col-md-' + self.params.ratio[num_col].aside);
						}
					});
				} else {
					container.find('input').val('col-md-' + (12 / columns.length));
					container.find('li > div').removeAttr('class').addClass('col-md-' + (12 / columns.length));
				}
			}

			// Reset container and column set
			self.columns = null;

			self.container.empty().append(container.children());
			container.remove();

			// Re-initialize
			self.init();
		},

		initResizable: function() {
			var self = this;

			self.columns.children().each(function(i, e) {
				// Reset resizable column
				!$(e).hasClass('ui-resizable') || $(e).resizable('destroy');

				// Initialize resizable column
				if (i + 1 < self.columns.length) {
					$(e).resizable({
						handles: 'e',
						minWidth: self.step,
						grid: [self.step, self.maxHeight],

						start: function(event, ui) {
							// Store original width
							ui.element.data('originalWidth', ui.element.width());

							// Get element that represents next sibling column 
							ui.element.data('nextColumn', ui.element.parent().next().children());

							// Store original width for next sibling element
							ui.element.data('nextColumnOriginalWidth', ui.element.data('nextColumn').width());

							// Calculate max span
							var maxSpan = -1
								+ parseInt(ui.element.children('input').val().replace('col-md-', ''))
								+ parseInt(ui.element.data('nextColumn').children('input').val().replace('col-md-', ''));

							ui.element.data('maxSpan', maxSpan);

							// Show grid preview
							self.grids.show();

							// Temporary disable sortable move icon
							if (self.params.sortable) {
								var allSortableLists = $('.it-form-field-column-settings > ul.ui-sortable');
	
								allSortableLists.attr('class', allSortableLists.attr('class').replace('ui-sortable', 'ui-unsortable'));
							}
						},

						resize: function(event, ui) {
							var span = parseInt(ui.element.width() / self.step);

							// Verify span
							if (span > ui.element.data('maxSpan')) {
								span = ui.element.data('maxSpan');
							} else if (span < 1) {
								span = 1;
							}

							// Calculate correct width to align column
							var	thisWidth = (self.step * span) + (self.spacing * (span - 1)),
								nextWidth = ui.element.data('nextColumnOriginalWidth') - (thisWidth - ui.element.data('originalWidth'));

							// Snap column to grid
							ui.element.css('width', thisWidth + 'px');

							// Update field value and column class
							ui.element.children('input').val('col-md-' + span);
							ui.element.attr('class', ui.element.attr('class').replace(/\bcol-md-\d+\b/, 'col-md-' + span));

							// Resize next sibling element as well
							ui.element.data('nextColumn').css('width', nextWidth + 'px');

							// Update field value and column class
							ui.element.data('nextColumn').children('input').val('col-md-' + (ui.element.data('maxSpan') - span + 1));
							ui.element.data('nextColumn').attr('class', ui.element.data('nextColumn').attr('class').replace(/\bcol-md-\d+\b/, 'col-md-' + (ui.element.data('maxSpan') - span + 1)));
						},

						stop: function(event, ui) {
							// Hide grid preview
							self.grids.hide();

							// Restore sortable move icon
							if (self.params.sortable) {
								var allSortableLists = $('.it-form-field-column-settings > ul.ui-unsortable');
	
								allSortableLists.attr('class', allSortableLists.attr('class').replace('ui-unsortable', 'ui-sortable'));
							}

							// Trigger change event on associated field
							ui.element.parent().parent().find('input').trigger('change');
						}
					});
				}

				$(e).parent().css('box-shadow', $(e).children().css('box-shadow'));
			});
		}
	};
})(jQuery);
