/**
 * @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_ = window._IT_ || {};

	// Define toggle utils
	_IT_.TogglePageLayout = function(elm, isFullWidth) {
		isFullWidth = isFullWidth || false;

		if (isFullWidth) {
			$(elm).parent().parent().parent().parent().next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none');
		} else {
			$(elm).parent().parent().parent().parent().next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '');

			// Toggle background type
			var bgType = $(elm).parent().parent().parent().parent().next().next().find('select');

			_IT_.ToggleBackgroundType(bgType, bgType.val());
		}

		_IT_.InitThemeAdmin(true);
	};

	_IT_.ToggleBackgroundType = function(elm, type) {
		switch (type) {
			case 'none':
				$(elm).parent().next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none');
			break;

			case 'solid_color':
				$(elm).parent().next().css('display', '').next().css('display', '').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none');
			break;

			case 'gradient_color':
				$(elm).parent().next().css('display', 'none').next().css('display', 'none').next().css('display', '').next().css('display', '').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none');
			break;

			case 'pattern':
				$(elm).parent().next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none');
			break;

			case 'image':
				$(elm).parent().next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '');
			break;
		}

		_IT_.InitThemeAdmin(true);
	};

	_IT_.ToggleMenuAttributes = function(elm, type) {
		switch (type) {
			case 'top_menu':
				if ($(elm).val() == '') {
					$(elm).parent().next().css('display', 'none').next().css('display', 'none');
				} else {
					$(elm).parent().next().css('display', '').next().css('display', '');
				}
			break;

			case 'main_menu':
				if ($(elm).val() == '') {
					$(elm).parent().addClass('last-child').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none').next().css('display', 'none');
				} else {
					$(elm).parent().removeClass('last-child').next().css('display', '').next().css('display', '').next().css('display', '').next().css('display', '');
				}
			break;
		}

		_IT_.InitThemeAdmin(true);
	};

	_IT_.ToggleNextSibling = function(elm, show) {
		show = show || false;

		if (show) {
			$(elm).parent().parent().next().css('display', '').next().css('display', '');
		} else {
			$(elm).parent().parent().next().css('display', 'none').next().css('display', 'none');
		}

		_IT_.InitThemeAdmin(true);
	};

	_IT_.SwitchPromoContent = function(elm, type) {
		switch (type) {
			case 'page_title':
				$(elm).parent().next().show().next().show().next().show().next().show().next().show().next().show().next().hide().next().hide().next().hide().next().hide();
				$(elm).parent().next().next().next().next().find('input:checked').trigger('click');
			break;

			case 'sidebars':
				$(elm).parent().next().hide().next().hide().next().hide().next().hide().next().hide().next().hide().next().show().next().show().next().show().next().show();
				$(elm).parent().next().next().next().next().next().next().next().next().children('select').trigger('change');
			break;
		}

		_IT_.InitThemeAdmin(true);
	};

	_IT_.ResetColumns = function(elm, type) {
		var target = $(elm).parent().next().next().children('ul'), it_column_settings = target.data('it_column_settings');

		if (it_column_settings) {
			// Re-sort columns
			it_column_settings.setColumns(type);

			// Trigger change event on associated field
			$(target).find('*[data-customize-setting-link]').trigger('change');
		}
	};

	_IT_.HidePickers = function() {
		$('#customize-preview iframe').each(function(i, e) {
			if (!e.contentDocument.IT_HidePickers_Registered) {
				$(e.contentDocument).click($.proxy(function() {
					// Hide all visible Color Picker
					var color_picker = $(this.contentWindow.parent.document).find('.it-form-field-color-picker > a.btn, .it-form-field-gradient-picker .point-color');

					if (color_picker.length) {
						color_picker.ColorPickerHide();
					}

					// Hide all visible Gradient Picker
					var gradient_picker = $(this.contentWindow.parent.document).find('.it-form-field-gradient-picker > .classy-gradient-box > .ClassyGradient > .info');

					if (gradient_picker.length) {
						gradient_picker.hide('fast');
					}
				}, e));
			}
		});
	};

	// Handle theme option changes
	_IT_.GetLinkedValue = function(name) {
		var value;

		$('input[name^="' + name + '"], select[name^="' + name + '"], textarea[name^="' + name + '"]').each(function(i, e) {
			var key = e.name.match(new RegExp(name + '\\[([^\\]]*)\\]'))[1], subvalue;

			if (e.type && e.type.match(/^(checkbox|radio)$/) && e.checked) {
				var has_child = e.name.match(new RegExp('(' + name + '\\[[^\\]]+\\])\\[[^\\]]*\\]'));

				if (has_child) {
					subvalue = _IT_.GetLinkedValue(has_child[1]);
				} else {
					subvalue = $(e).val();
				}
			} else if (!e.type || !e.type.match(/^(checkbox|radio)$/)) {
				subvalue = $(e).val();
			}

			if (subvalue) {
				if (key == '') {
					if (value) {
						value.push(subvalue);
					} else {
						value = [subvalue]
					}
				} else {
					if (!value) {
						value = {};
					}

					value[key] = subvalue;
				}
			} else {
				if (key == '' && !value) {
					value = [];
				} else if (key != '' && !value) {
					value = {};
					value[key] = '';
				}
			}
		});

		return value;
	};

	// Do remaining initialization after window completely loaded
	_IT_.InitThemeAdmin = function(event, ui) {
		reset_accordion = (typeof event == 'boolean' && event == true);

		// Get active tab
		var active = (event && ui && ui.newPanel) ? ui.newPanel : $('#customize-controls #it-theme-options .ui-tabs-panel[aria-expanded="true"]');

		if (!reset_accordion) {
			// Toggle options
			active.find('.it-form-field-select select').each(function(i, e) {
				if ($(e).attr('onchange')) {
					$(e).trigger('change');
				}
			});

			// Init tool tips
			$('#customize-controls #it-theme-options .it-form-sections-tabs > ul > li .has-tips').each(function(i, e) {
				if (!e.IT_InitThemeAdmin) {
					$(e).tipsy({
						gravity: 'nw',
						fade: true
					});

					e.IT_InitThemeAdmin = true;
				}
			});

			active.find('label > .has-tips').each(function(i, e) {
				if (!e.IT_InitThemeAdmin) {
					$(e).tipsy({
						gravity: 'ne',
						fade: true
					});

					e.IT_InitThemeAdmin = true;
				}
			});

			// Check if target frontend element exists
			if ( event && ui && ui.newPanel ) {
				var	target = ui.newPanel.attr('target'),
					iframe = $('#customize-preview iframe'),
					jq = iframe.length ? iframe[0].contentWindow.jQuery : null,
					frontend_element = jq ? jq('#' + target) : [];

				if (target && frontend_element.length) {
					// Check if element is within current view
					var top = jq(window).scrollTop(), height = jq(window).height(), position = frontend_element.offset();

					if (top + height < position.top) {
						// Scroll to front-end element
						jq('html, body').animate({
							scrollTop: position.top
						}, 500);
					}

					// Generate flashing element
					var flashing_element = $('<div class="flashing-element" />').css({
						position: 'absolute',
						top: 0,
						right: 0,
						bottom: 0,
						left: 0,
						border: '2px solid #F5AF5D'
					});

					frontend_element.css('position', 'relative').append(flashing_element);

					setTimeout(function() {
						flashing_element.fadeOut('slow', function() {
							flashing_element.remove();
							frontend_element.css('position', '');
						});
					}, 1000);
				}
			}

			// Track sortable fields
			active.find('.it-sortable-list > .ui-sortable').each(function(i, e) {
				if (!e.IT_InitThemeAdmin) {
					$(e).on('sortupdate', function(event, ui) {
						// Trigger change event on associated field
						$(ui.item).find('input[data-customize-setting-link]').trigger('change');
						wp.customize.trigger('change');

						// Handle hiding color/gradient picker from live preview iframe
						setTimeout(_IT_.HidePickers, 3000);
					});

					e.IT_InitThemeAdmin = true;
				}
			});

			// Track standard fields
			active.find('input[data-customize-setting-link], select[data-customize-setting-link], textarea[data-customize-setting-link]').each(function(i, e) {
				if (!e.IT_InitThemeAdmin) {
					$(e).change(function() {
						// Store new value to settings object
						var id = $(this).attr('data-customize-setting-link'), value = $(this).val(), changed = false;

						// Skip empty id and profile field
						if (!id || id == 'profile') {
							return;
						}

						// Check if this option has multiple field
						if (this.name.match(/\]$/)) {
							value = _IT_.GetLinkedValue(id);
						}

						wp.customize.each(function(obj, key) {
							if (id == key && $.toJSON(obj.get()) != $.toJSON(value)) {
								obj.set(value);
								changed = true;
							}
						});

						if (changed) {
							// Toggle loading state
							$(this).closest('div[class^="it-form-field-"]').prev('label').children('.it-form-field-help').addClass('it-loading');

							// Trigger change event
							wp.customize.trigger('change');
						}

						// Handle hiding color/gradient picker from live preview iframe
						setTimeout(_IT_.HidePickers, 3000);
					});

					e.IT_InitThemeAdmin = true;
				}
			});

			// Support option profile
			active.find('#it-form-field-profile img').each(function(i, e) {
				if (!e.IT_InitThemeAdmin) {
					$(e).click(function(event) {
						// Get new profile value
						var	newProfile = $(this).prev().find('input').val(),
							newOptions = $('<div id="customize-controls-' + newProfile + '" style="display:none" />').appendTo(document.body);

						// Toggle loading state
						$(this).closest('div[class^="it-form-field-"]').prev('label').children('.it-form-field-help').addClass('it-loading');

						// Silently reload theme options
						var link = window.location.href.replace(/(\?|&)it-profile=[a-zA-Z0-9]+/, '').replace('#', '');
						link += (link.indexOf('?') > -1 ? '&' : '?') + 'it-profile=' + newProfile;

						$.ajax({
							url: link,
							complete: function(data, status) {
								if (status == 'success') {
									var content, sess = Math.random(); ;

									content = data.responseText.split('<form ');
									content = content[1].substr(content[1].indexOf('>') + 1).split('</form>');
									content = content[0].replace(/\$\(document\)\.ready\(/g, '$(document).on("it-document-ready-' + sess + '", ');
									content = content.replace(/\$\(window\)\.load\(/g, '$(window).on("it-window-load-' + sess + '", ');

									// Switch profile
									newOptions.html(content);
									delete content;

									newOptions.find('div[class^="it-form-field-"]').each(function(i, e) {
										var source;

										if ($(e).attr('id')) {
											source = $('#customize-controls #it-theme-options #' + $(e).attr('id'));
										} else {
											var elm = $(e).find('*[id^="it-form-field-"]');

											if (elm.length) {
												source = $('#customize-controls #it-theme-options #' + $(elm).attr('id')).closest('div[class^="it-form-field-"]');
											}
										}

										if (source && source.length) {
											source.html($(e).html());
										}

										$(e).remove();
									});

									newOptions.remove();
									delete newOptions;

									// Clean junk elements
									$('body > .jsn-master.ui-dialog, body > .colorpicker, body > .ui-datepicker').remove();

									// Re-init theme options
									$(document).trigger('it-document-ready-' + sess);
									$(window).trigger('it-window-load-' + sess);
									_IT_.InitThemeAdmin();

									// Set new profile
									wp.customize.each(function(obj, key) {
										if (key == 'profile') {
											obj.set(newProfile);
										}
									});

									wp.customize.trigger('change');
								}
							}
						});
					});

					e.IT_InitThemeAdmin = true;
				}
			});

			// Set correct height for tab panel
			var	container = $('#customize-controls.wp-full-overlay-sidebar > .wp-full-overlay-sidebar-content'),
				tab_nav = $('#customize-controls #it-theme-options > .it-form-sections-tabs > .ui-tabs-nav'),
				fieldset = active.children('fieldset');

			if (!fieldset.length) {
				fieldset = active;
			}

			var	legend = fieldset.children('legend'),
				accordion = fieldset.children('.it-form-accordion'),
				spacing = 0;

			if (!accordion.length) {
				accordion = legend.next();
			}

			// Get fieldset's outer spacing
			for (var i in {'margin':'', 'border':'', 'padding':''}) {
				for (var j in {'top':'', 'bottom':''}) {
					var prop = i + '-' + j + (i == 'border' ? '-width' : '');
					spacing += parseInt(fieldset.css(prop));

					accordion[0] == fieldset[0] || (spacing += parseInt($(accordion).css(prop)));
				}
			}

			// Set correct height for accordion container
			accordion.css(
				'height',
				(container.height() - tab_nav.height() - legend.height() - spacing) + 'px'
			);
		}

		// Set correct height for accordion
		active.find('div[id^="it-form-accordion-"]').each(function(i, e) {
			if ($(e).css('display') != 'none') {
				// Calculate height
				var height = 0;

				$(e).children().each(function(i, child) {
					if ($(child).css('display') != 'none') {
						height += $(child).outerHeight(true);
					}
				});

				// Set correct height for accordion
				$(e).css({
					overflow: 'visible'
				});
			}
		});
	};

	$(window).load(function() {
		if (!_IT_.initialized) {
			// Handle window resize event
			$(window).resize(function(event) {
				if (event.target == window) {
					_IT_.InitThemeAdmin.timer && clearTimeout(_IT_.InitThemeAdmin.timer);
					_IT_.InitThemeAdmin.timer = setTimeout(_IT_.InitThemeAdmin, 500);
				}
			}).trigger('resize');

			// Handle global Ajax complete event
			$(document).ajaxComplete(function(event, XMLHttpRequest, ajaxOptions) {
				if (ajaxOptions.url.indexOf('/wp-admin/') < 0) {
					$('.it-form-field-help.it-loading').removeClass('it-loading');
				}
			});

			$('.it-form-sections-tabs').on('tabsactivate', _IT_.InitThemeAdmin);

			// Handle hiding color/gradient picker from live preview iframe
			setTimeout(_IT_.HidePickers, 3000);

			_IT_.initialized = true;
		}
	});
})(jQuery);
