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

		// Initialize parameters
		self.params = $.extend({
			lang: {
				SELECT_MEDIA: 'Select Media',
				SELECT: 'Select'
			}
		}, params);

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

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

			// Get necessary elements
			self.modal = $('#it-form-field-media-selector-modal');

			// Init button to select media
			$('.it-form-field-media-selector > span.input-group-btn > a.btn').unbind('click').bind('click', function(event) {
				event.preventDefault();

				if ($(event.target).hasClass('disabled')) {
					return;
				}

				// Store field being edited and current modal
				$.IT_MediaSelector.editing = $(this).parent().prev();

				// Show media selector
				$.it_media_selector.open();
			});

			// Setup media selector
			$.it_media_selector = wp.media({
				title: self.params.lang.SELECT_MEDIA,
				library: {type: 'image'},
				button: {
					text: self.params.lang.SELECT
				}
			});

			$.it_media_selector.on('select', function() {
				// Get the selected media
				var selected = $.it_media_selector.state().get('selection').first();

				// Update field value with the selected media
				$.IT_MediaSelector.update(selected.attributes.url);
			});
		}
	};

	$.IT_MediaSelector.update = function(selected) {
		$.it_media_selector.close();

		if ($.IT_MediaSelector.editing) {
			$.IT_MediaSelector.editing.val(selected);

			// Trigger change event on updated field
			$.IT_MediaSelector.editing.trigger('change');
		}
	};
})(jQuery);
