/**
 * @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_Form = function(params) {
		// Initialize parameters
		this.params = $.extend({
			mask_required: '.it-form-field-checkbox-image, .it-form-field-color-picker, .it-form-field-column-settings, .it-form-field-gradient-picker, .it-form-field-radio-image, .it-form-field-radio-image-inline, .it-form-field-social-channels, .it-form-field-typography, .chosen-box'
		}, params);

		// Get associated form
		this.form = $('#' + this.params.id);

		$(window).load($.proxy(this.init, this));
	};

	$.IT_Form.prototype = {
		init: function(event, section) {
			if (!section) {
				section = this.form;
			}

			if (this.params.tips) {
				// Init tool-tips
				section.find('.has-tips').tipsy({
					gravity: 'nw',
					fade: true
				});
			}

			if (this.params.accordions && (this.accordions = section.find('.it-form-accordion')).length) {
				// Check if form contains any accordion toggler?
				section.find('.it-form-fieldset-accordion-toggler').each($.proxy(function(i, e) {
					var accordion = $(e).closest('fieldset').find('.it-form-accordion');

					if (accordion.length) {
						// Define accordion class state
						this.accordionState = this.accordionState || {
							heading: {collapse: 'ui-corner-all', expand: 'ui-accordion-header-active ui-state-active ui-corner-top'},
							icon: {collapse: 'ui-icon-triangle-1-e', expand: 'ui-icon-triangle-1-s'},
							content: {collapse: '', expand: 'ui-accordion-content-active'}
						};

						$(e).children('.collapse-all').unbind('click').bind('click', $.proxy(function(event) {
							event.preventDefault();
							this.toggle_accordion(accordion);
						}, this));

						$(e).children('.expand-all').unbind('click').bind('click', $.proxy(function(event) {
							event.preventDefault();
							this.toggle_accordion(accordion, true);
						}, this));
					}
				}, this));

				// Init accordions
				this.accordions.accordion({
					collapsible: true,
					heightStyle: 'content',
					beforeActivate: $.proxy(function(event, ui) {
						if ($(event.target).closest('fieldset').find('.it-form-fieldset-accordion-toggler').length) {
							if (!ui.newHeader.length || !ui.newPanel .length) {
								ui.newHeader = ui.oldHeader;
								ui.newPanel = ui.oldPanel;
							}

							if (ui.newHeader.hasClass(this.accordionState.heading.collapse)) {
								// Close all currently open accordion
								ui.newHeader.parent().find('.ui-accordion-header').removeClass(this.accordionState.heading.expand).addClass(this.accordionState.heading.collapse);
								ui.newHeader.parent().find('.ui-accordion-header-icon').removeClass(this.accordionState.icon.expand).addClass(this.accordionState.icon.collapse);
								ui.newHeader.parent().find('.ui-accordion-content').slideUp().removeClass(this.accordionState.content.expand).addClass(this.accordionState.content.collapse);

								// Open clicked accordion
								ui.newHeader.removeClass(this.accordionState.heading.collapse).addClass(this.accordionState.heading.expand);
								ui.newHeader.children('.ui-accordion-header-icon').removeClass(this.accordionState.icon.collapse).addClass(this.accordionState.icon.expand);
								ui.newPanel.slideDown({
									complete: function() {
										// Manually trigger activate event
										$(event.target).data('uiAccordion')._trigger('activate', event, ui);
									}
								}).removeClass(this.accordionState.content.collapse).addClass(this.accordionState.content.expand);
							} else {
								// Closing
								ui.newHeader.removeClass(this.accordionState.heading.expand).addClass(this.accordionState.heading.collapse);
								ui.newHeader.children('.ui-accordion-header-icon').removeClass(this.accordionState.icon.expand).addClass(this.accordionState.icon.collapse);
								ui.newPanel.slideUp().removeClass(this.accordionState.content.expand).addClass(this.accordionState.content.collapse);
							}

							return false;
						}
					}, this),
					activate: function(event, ui) {
						ui.newPanel.find('.it-form-field-column-settings > ul').each(function(i, e) {
							var it_column_settings = $(e).data('it_column_settings');
			 				if (it_column_settings) it_column_settings.init();
						});
					}
				});
			}

			// Get form's sections and tabs
			this.sections = section.find('.it-form-sections-tabs');
			this.tabs = section.find('.it-form-tabs');

			if (this.params.tabs && (this.sections.length || this.tabs.length)) {
				// Init tabs inside form sections
				this.tabs.tabs({
					activate: function(event, ui) {
						ui.newPanel.find('.it-form-field-column-settings > ul').each(function(i, e) {
							var it_column_settings = $(e).data('it_column_settings');
			 				if (it_column_settings) it_column_settings.init();
						});
					}
				});

				// Init tabs for form sections
				this.sections.tabs({
					beforeActivate: $.proxy(function(event, ui) {
						if (this.params.ajax) {
							if (ui.newPanel.html() < 10 && $.trim(ui.newPanel.html()) == '') {
								// Load content for form section
								var	link = window.location.href.replace(/\?section=[0-9a-zA-Z\-_]+/, '').replace('&ajax=1', ''),
									section = ui.newTab.children('a').attr('href').replace('#it-form-section-', '');

								// Set loading state for tab panel
								ui.newPanel.addClass('it-loading');

								// Get content for new panel
								$.ajax({
									url: link + '?section=' + section + '&ajax=1',
									context: this,
									complete: function(jqXHR, textStatus) {
										if (textStatus == 'success') {
											var content = jqXHR.responseText.split(new RegExp('<div id="it-form-section-' + section + '"[^>]*>'));

											// Finalize content then append to the newly created panel
											if (content.length > 1) {
												var sess = Math.random();

												// Prepare content
												content = content[1].replace(/<\/div>[\s\t\r\n]*$/, '');
												content = content.replace(/\$\(document\)\.ready\(/g, '$(document).on("it-document-ready-' + sess + '", ');
												content = content.replace(/\$\(window\)\.load\(/g, '$(window).on("it-window-load-' + sess + '", ');

												ui.newPanel.removeClass('it-loading').html(content);
												delete content;

												// Trigger necessary events
												$(document).trigger('it-document-ready-' + sess);
												$(window).trigger('it-window-load-' + sess);
											}

											// Re-initialize form
											this.init(null, ui.newPanel);

											// Re-trigger tab activate event
											$(event.target).data('uiTabs')._trigger('activate', event, ui);
										} else {
											// Re-load the page using link to specified section
											window.location.href = link + '?section=' + section;

											window.location.reload();
										}
									}
								});
							}
						}
					}, this),
					activate: function(event, ui) {
						ui.newPanel.find('.it-form-field-column-settings > ul').each(function(i, e) {
							var it_column_settings = $(e).data('it_column_settings');
			 				if (it_column_settings) it_column_settings.init();
						});
					}
				});

				if (this.form.hasClass('form-vertical')) {
					// Align tabs inside form sections vertically
					this.tabs.addClass('ui-tabs-vertical ui-helper-clearfix')
						.children('ul').children('li').removeClass('ui-corner-top').addClass('ui-corner-left');

					// Align form sections tabs vertically
					this.sections.addClass('ui-tabs-vertical ui-helper-clearfix')
						.children('ul').children('li').removeClass('ui-corner-top').addClass('ui-corner-left');
				}
			}

			// Check if form contains any form/fieldset state switcher?
			section.find('.it-form-state-switcher, .it-form-fieldset-state-switcher').each($.proxy(function(i, e) {
				$(e).children('.turn-on').unbind('click').bind('click', $.proxy(function(event) {
					var fieldset = $(event.target).parent().hasClass('it-form-fieldset-state-switcher') ? $(event.target).closest('fieldset') : section;

					event.preventDefault();

					this.toggle_state(fieldset, $(event.target));
				}, this));

				$(e).children('.turn-off').unbind('click').bind('click', $.proxy(function(event) {
					var fieldset = $(event.target).parent().hasClass('it-form-fieldset-state-switcher') ? $(event.target).closest('fieldset') : section;

					event.preventDefault();

					this.toggle_state(fieldset, $(event.target));
				}, this));

				$(e).children('.disabled, .hide, .hidden').trigger('click');
			}, this));

			// Store form control object instance to form element
			if (section == this.form) {
				section.data('it_form_control', this);
			}
		},

		toggle_accordion: function(accordion, expand) {
			expand = expand || false;

			if (expand) {
				accordion.children('.ui-accordion-header').removeClass(this.accordionState.heading.collapse).addClass(this.accordionState.heading.expand);
				accordion.find('.ui-accordion-header-icon').removeClass(this.accordionState.icon.collapse).addClass(this.accordionState.icon.expand);
				accordion.children('.ui-accordion-content').each($.proxy(function(i, e) {
					$(e).slideDown({
						complete: function() {
							// Manually trigger activate event
							ui = {newHeader: $(e).prev(), newPanel: $(e)};

							accordion.data('uiAccordion')._trigger('activate', null, ui);
						}
					}).removeClass(this.accordionState.content.collapse).addClass(this.accordionState.content.expand);
				}, this));
			} else {
				accordion.children('.ui-accordion-header').removeClass(this.accordionState.heading.expand).addClass(this.accordionState.heading.collapse);
				accordion.find('.ui-accordion-header-icon').removeClass(this.accordionState.icon.expand).addClass(this.accordionState.icon.collapse);
				accordion.children('.ui-accordion-content').slideUp().removeClass(this.accordionState.content.expand).addClass(this.accordionState.content.collapse);
			}
		},

		toggle_state: function(fieldset, clicked_element) {
			var enable = clicked_element.hasClass('turn-on');

			if (enable) {
				// Enable all fields belong to this fieldset
				fieldset.find('input[class!="it-form-state"], select, textarea, button').each(function(i, e) {
					$(e).removeAttr('disabled');

					if ($(e).hasClass('chosen-box')) {
						$(e).trigger("liszt:updated");
					}
				});

				// Enable all button links
				fieldset.find('a.btn').each(function(i, e) {
					if (
						!$(e).parent().hasClass('it-form-state-switcher')
						&&
						!$(e).parent().hasClass('it-form-fieldset-state-switcher')
						&&
						!$(e).parent().hasClass('it-form-fieldset-accordion-toggler')
					) {
						$(e).removeClass('disabled');
					}
				});

				// Toggle button state
				if (clicked_element.next().hasClass('disabled')) {
					clicked_element.addClass('btn-success disabled').next().removeClass('btn-danger disabled');
				} else if (clicked_element.next().hasClass('hide hidden')) {
					clicked_element.addClass('btn-success hide hidden').next().removeClass('btn-danger hide hidden');
				}

				// Remove mask elements
				fieldset.find(this.params.mask_required).css('position', '').children('.it-form-disabled-mask').remove();
			} else {
				// Disable all fields belong to this fieldset
				fieldset.find('input[class!="it-form-state"], select, textarea, button').each(function(i, e) {
					$(e).attr('disabled', 'disabled');

					if ($(e).hasClass('chosen-box')) {
						$(e).trigger("liszt:updated");
					}
				});

				// Disable all button links
				fieldset.find('a.btn').each(function(i, e) {
					if (
						!$(e).parent().hasClass('it-form-state-switcher')
						&&
						!$(e).parent().hasClass('it-form-fieldset-state-switcher')
						&&
						!$(e).parent().hasClass('it-form-fieldset-accordion-toggler')
					) {
						$(e).addClass('disabled');
					}
				});

				// Toggle button state
				if (clicked_element.prev().hasClass('disabled')) {
					clicked_element.addClass('btn-danger disabled').prev().removeClass('btn-success disabled');
				} else if (clicked_element.prev().hasClass('hide hidden')) {
					clicked_element.addClass('btn-danger hide hidden').prev().removeClass('btn-success hide hidden');
				}

				// Append mask elements
				fieldset.find(this.params.mask_required).css('position', 'relative').append($('<div class="it-form-disabled-mask" />'));
			}

			if (clicked_element.parent().hasClass('it-form-fieldset-state-switcher')) {
				// Update element contains fieldset state
				fieldset.find('input.it-form-state').val(enable ? 1 : 0).trigger('change');
			} else {
				// Update element contains form state
				clicked_element.parent().prev().val(enable ? 1 : 0).trigger('change');
			}
		},
	};
})(jQuery);
