
jQuery( document ).ready(function( $ ) {

	// Meta boxes dependencies
	$('.shrk-input').on( 'change', function () {
		$('.op_depents_on').shrk_meta_dependencies();
	});
	$('.op_depents_on').shrk_meta_dependencies();

	// Sortable page sections selector
	$( "#section-sortable1, #section-sortable2" ).sortable({
		connectWith: ".connectedSortable",
		placeholder: "ui-state-highlight",
		forcePlaceholderSize: true,
		update: function () {
			sp_update_sortable();
		}
	}).disableSelection();
	
	// Bind the update event
	$( "#section-sortable1, #section-sortable2" ).on('sortupdate', function( event, ui ) {

	});

	//Set disabled attr to fields
	$( 'input.of-input.disabled' ).attr( 'disabled', 'disabled' );
	
	function sp_update_sortable() {
		var key_arr = [];
					
		$( '#section-sortable2' ).children().each( function () {
			var section_id = $(this).attr('id').split('-')[1];
			key_arr.push( section_id );
		});
		
		$( '#' + $( '#section-sortable2' ).attr('rel') ).val( key_arr.join(',') );
	}

	// Color picker
	if ( typeof( $.fn.wpColorPicker ) === 'function' ) {
	  	$('.of-color').wpColorPicker();
	}

	// RGBA Color picker
	if ( typeof( $.fn.spectrum ) === 'function' ) {
		$('.of-color-alpha').spectrum({
			showAlpha:           true,
			showInput:           true,
			allowEmpty:          true,
			clickoutFiresChange: true,
			preferredFormat:     'rgb'
		});
	}
	
	$('.sectionpicker .shrk-new-section-button').on('click', function (e) {

		e.preventDefault();
		var posttitle = prompt("Enter a name to identify your new section");

		if ( posttitle != null )
		{
			var ajax_data = {
				action : 'shrk_new_section',
				_ajax_nonce: shrk.ajax.nonce,
				post_title : posttitle
			};

			$('#sectionpicker .spinner').show();

			$.post(ajaxurl, ajax_data, function(response) {
				if ( response.result == 'OK' ) { 
					var li_html = '<li id="section-' + response.postid + '" class="ui-state-default newitem">' + response.post_title + ' <div class="iconlinks"><a target="_blank" title="Edit Section" class="shrk-admin-edit shrk-edit-new-section" href="' + response.post_edit_link + '"><i class="el el-icon-pencil"></i></a></div><div class="helper-text"><a target="_blank" title="Edit Section" class="shrk-admin-edit shrk-edit-new-section" href="' + response.post_edit_link + '">Click the pencil to add some content!</a></div></li>';
					$( '#section-sortable2' ).append(li_html);
					sp_update_sortable();
				} else {
					alert ( 'Error creating new section. Please try again' );
				}
				$('#sectionpicker .spinner').hide();
			});

		}
	});

	$('#sectionpicker').on('click', 'a.shrk-edit-new-section', function () {
		$(this).parent().parent().removeClass('newitem');
	});


	/**
	  * Media Uploader
	  * Dependencies 	 : jquery, wp media uploader
	  * Feature added by : Smartik - http://smartik.ws/
	  * Date 			 : 05.28.2013
	  */
	function optionsframework_add_file(event, selector) {
	
		var upload = jQuery(".uploaded-file"), frame;
		var $el = jQuery(this);

		event.preventDefault();

		// If the media frame already exists, reopen it.
		if ( frame ) {
			frame.open();
			return;
		}

		// Create the media frame.
		frame = wp.media({
			// Set the title of the modal.
			title: $el.data('choose'),

			// Customize the submit button.
			button: {
				// Set the text of the button.
				text: $el.data('update'),
				// Tell the button not to close the modal, since we're
				// going to refresh the page when the image is selected.
				close: false
			}
		});

		// When an image is selected, run a callback.
		frame.on( 'select', function() {
			// Grab the selected attachment.
			var attachment = frame.state().get('selection').first();
			frame.close();
			
			var input_el = selector.find('.upload');
			
			if ( input_el.hasClass('allowed_only') ) {
				if ( !input_el.hasClass('allow_'+attachment.attributes.subtype) ) {
					var elem_classes = input_el.shrk_get_classes();
					var allowed_types = [];
					for (var i=0; i < elem_classes.length; i++) {
						if ( elem_classes[i].split('_')[0] == 'allow' ) {
							allowed_types.push(elem_classes[i].split('_')[1]);
						}
					}
					alert ( 'Allowed filetypes for this field are: ' + allowed_types.join(', ') + '. You selected a file with filetype: '+ attachment.attributes.subtype + '. Please select another file.' );
					return false;
				}
			}
			
			selector.find('.upload').val(attachment.attributes.id);
			if ( attachment.attributes.type == 'image' ) {
				selector.find('.screenshot').empty().hide().append('<img class="of-option-image" src="' + attachment.attributes.url + '">').slideDown('fast');
			} else if ( attachment.attributes.type == 'video' ) {
				var video_attr = {};
				video_attr['attachid'] = attachment.attributes.id;
				video_attr['width'] = attachment.attributes.width;
				video_attr['height'] = attachment.attributes.height;
				video_attr['subtype'] = attachment.attributes.subtype;
				
				jQuery('#section_video_attributes').val(JSON.stringify(video_attr));

				var ajax_data = {
					action:      'get_video_shortcode',
					_ajax_nonce: shrk.ajax.nonce,
					attach_id:   attachment.attributes.id
				};

				jQuery.post(ajaxurl, ajax_data, function(response) {
					selector.find('.video_preview').empty().hide().append(response).slideDown('fast');
				}); 
				
			}
			selector.find('.media_upload_button').unbind();
			selector.find('.remove-image').removeClass('hidden');//show "Remove" button
			selector.find('.of-background-properties').slideDown();
			optionsframework_file_bindings();
		});

		// Finally, open the modal.
		frame.open();
	}
    
	function optionsframework_remove_file(selector) {
		selector.find('.remove-image').addClass('hidden');//hide "Remove" button
		selector.find('.upload').val('');
		selector.find('.of-background-properties').hide();
		selector.find('.screenshot').slideUp();
		selector.find('.video_preview').slideUp();
		selector.find('.remove-file').unbind();
		// We don't display the upload button if .upload-notice is present
		// This means the user doesn't have the WordPress 3.5 Media Library Support
		if ( jQuery('.op-upload-wrap .upload-notice').length > 0 ) {
			jQuery('.media_upload_button').remove();
		}
		optionsframework_file_bindings();
	}
	
	function optionsframework_file_bindings() {
		jQuery('.remove-image, .remove-file').on('click', function() {
			optionsframework_remove_file( jQuery(this).parents('.op-upload-wrap, .section-upload, .section-media, .slide_body') );
        });
        
        jQuery('.media_upload_button').unbind('click').click( function( event ) {
        	optionsframework_add_file(event, jQuery(this).parents('.op-upload-wrap, .section-upload, .section-media, .slide_body'));
        });
    }
    
    optionsframework_file_bindings();	

	$('.range-input-container .range_value').on('change', function () {
		$(this).next('.range_preview').val( $(this).val() );
	});

	// Temp fix. VC params classes are ignored.
	// TODO remove when VC is fixed
	jQuery('#wpwrap').on('vcPanel.shown', '.vc_ui-panel', function () {
		jQuery('.vc_shortcode-param').each( function() { jQuery(this).find('.edit_form_line').children().addClass( jQuery(this).data('param_settings').class ); });
	});
	
});

(function($) {
	
	$.fn.shrk_get_classes = function() {
		classes = [];
		$($(this).attr('class').split(' ')).each(function() { 
			if (this !== '') {
				classes.push(this);
			}    
		});
		
		return classes;
	};
	
})( jQuery );


(function($) {
	
	$.fn.shrk_meta_dependencies = function() {

		$(this).each( function() {
			deps = [];
			deps = ( $(this).attr('data-depend').split('|') );
			thisVisible = false;

			for (var i = deps.length - 1; i >= 0; i--) {
				deps_elem = deps[i].split(':')[0];
				deps_value = deps[i].split(':')[1];
				
				if ( $('#'+deps_elem).val() == deps_value ) {
					thisVisible = true;
					break;
				}

				if ( $('input[name='+deps_elem+']').attr('type') == 'radio' ) {
					if ( $('input[name='+deps_elem+']:checked').val() == deps_value ) {
						thisVisible = true;
						break;
					}
				}

			}

			if ( thisVisible === true ) {
				$(this).fadeIn();
			} else {
				$(this).fadeOut();
			}


		});

		return this;
	};
	
})( jQuery );

shrk_getKeyByValue = function( obj, value ) {
    for( var prop in obj ) {
        if( obj.hasOwnProperty( prop ) ) {
             if( obj[ prop ] === value )
                 return prop;
        }
    }
}
