/******************************************************
*
*	MegaMenu
*
******************************************************/
function update_megamenu(){
	jQuery('.menu-item-depth-0 .pix-megamenu-item').each(function(){
		var c = jQuery(this),
			li = c.closest('li'),
			p = jQuery('> dl .item-type',li),
			megaEq = li.index('.menu-item-depth-0'),
			megaNext = jQuery('.menu-item-depth-0').eq(megaEq+1),
			startEq = li.index('.menu-item'),
			endEq = megaNext.length ? megaNext.index('.menu-item') : jQuery('.menu-item').length;
		if(!jQuery('> dl .custom-type',li).length){
			p.after('<span class="custom-type" />');
		}
		var te = jQuery('> dl .custom-type',li);
		if(c.is(':checked')){
			te.html('<span class="pixmegamenu-label">PixMegaMenu</span>').show();
			//p.hide();
			li.addClass('pix-megamenu-parent');
			li.nextUntil('.menu-item-depth-0').addClass('in-a-megamenu');
		} else {
			//te.hide();
			//p.show();
			li.removeClass('pix-megamenu-parent');
			li.nextUntil('.menu-item-depth-0').removeClass('in-a-megamenu');
		}
		var update_children = function() {
			jQuery('.in-a-megamenu').each(function(){
				var subs = jQuery(this).attr('class').indexOf('menu-item-depth-'),
					depth = parseFloat(jQuery(this).attr('class').substring(subs+16,subs+17));
				if ( depth > 2 ) {
					jQuery(this).addClass('menu-item-alert');
					if ( !jQuery('#pix_builder_cant').length ) {
						jQuery('body').append('<div id="pix_builder_cant" /></div>');
					}
					jQuery('#pix_builder_cant').html('<p>PixMegaMenu can\'t have more than two levels, please check</p>')
						.dialog({
							height: 'auto',
							width: 250,
							modal: true,
							dialogClass: 'wp-dialog',
							zIndex: 50,
							close: function(){
								jQuery('#pix_builder_cant').remove();
							}
						});
				} else {
					jQuery(this).removeClass('menu-item-alert');
				}
			});
		};
		c.bind('click',function(){
			if(c.is(':checked')){
				te.html('<span class="pixmegamenu-label">PixMegaMenu</span>').show();
				//p.hide();
				li.addClass('pix-megamenu-parent');
				li.nextUntil('.menu-item-depth-0').addClass('in-a-megamenu');
			} else {
				//te.hide();
				//p.show();
				li.removeClass('pix-megamenu-parent');
				li.nextUntil('.menu-item-depth-0').removeClass('in-a-megamenu');
			}
			update_children();
		});
		update_children();
	});
	jQuery('.menu-item-depth-1 .pix-column-item').each(function(){
		var c = jQuery(this),
			v = jQuery('option:selected',c).val(),
			li = c.closest('li'),
			p = jQuery('> dl .item-type',li);
		if(!jQuery('> dl .custom-type',li).length){
			p.after('<span class="custom-type" />');
		}
		var te = jQuery('> dl .custom-type',li);
		if(v == 'column'){
			c.parents('li').eq(0).addClass('menu-item-column');
			te.html('<span class="pixmegamenu-column">'+pixmenu_column+'</span>');
			//p.hide();
			jQuery('.pix_url-item, .field-link-target, field-css-classes, .field-xfn, .field-description, .pix_image-item, .pix_sidebar-item',li).hide();
			jQuery('.pix_width-item',li).show();
		} else if(v == 'row'){
			c.parents('li').eq(0).addClass('menu-item-row');
			te.html('<span class="pixmegamenu-row">'+pixmenu_row+'</span>');
			//p.hide();
			jQuery('.pix_url-item, .field-link-target, field-css-classes, .field-xfn, .field-description, .pix_image-item, .pix_sidebar-item',li).hide();
			jQuery('.pix_width-item',li).hide();
		} else {
			//te.hide();
			//p.show();
			jQuery('.pix_url-item, .field-link-target, field-css-classes, .field-xfn, .field-description, .pix_image-item, .pix_sidebar-item',li).show();
			jQuery('.pix_width-item',li).hide();
		}
		c.change(function(){
			v = jQuery('option:selected',c).val();
			if(v == 'column'){
				c.parents('li').eq(0).removeClass('menu-item-row').addClass('menu-item-column');
				te.html('<span class="pixmegamenu-column">'+pixmenu_column+'</span>');
				//p.hide();
				jQuery('.pix_url-item, .field-link-target, field-css-classes, .field-xfn, .field-description, .pix_image-item, .pix_sidebar-item',li).slideUp();
				jQuery('.pix_width-item',li).slideDown();
			} else if(v == 'row'){
				c.parents('li').eq(0).removeClass('menu-item-column').addClass('menu-item-row');
				te.html('<span class="pixmegamenu-row">'+pixmenu_row+'</span>');
				//p.hide();
				jQuery('.pix_url-item, .field-link-target, field-css-classes, .field-xfn, .field-description, .pix_image-item, .pix_sidebar-item',li).slideUp();
				jQuery('.pix_width-item',li).slideUp();
			} else {
				c.parents('li').eq(0).removeClass('menu-item-row').removeClass('menu-item-column');
				//te.hide();
				//p.show();
				jQuery('.pix_url-item, .field-link-target, field-css-classes, .field-xfn, .field-description, .pix_image-item, .pix_sidebar-item',li).slideDown();
				jQuery('.pix_width-item',li).slideUp();
			}
		});
	});
}

/********************************
*
*   Get thumbnail from the server
*
********************************/
function getThumbnailUrl($id, $field, $altbg){
	var data = {
		action: 'pixmenu_get_thumb',
		security: pixmenu_nonce,
		content: $id
	};
	jQuery.post(ajaxurl, data)
		.success(function(html){
			$field.css({backgroundImage: $altbg + 'url('+html+')'}).addClass('filled');
		});
}

/********************************
*
*   Upload media
*
********************************/
function uploadSlidesForSlideshow(){

	jQuery('.pix_upload').each(function(){
		var t = jQuery(this),
			pix_media_frame,
			formlabel = 0,
			id = jQuery('input.pix-image-id',this).val();
		if ( id!=='' && typeof id != 'undefined' ) {
			getThumbnailUrl(id, jQuery('.img_preview',this), '');
		}

		t.off('click','.add-descriptive-thumb');
		t.on('click','.add-descriptive-thumb', function( e ){
			e.preventDefault();
			var button = jQuery(this),
				wrap = button.parents('.pix_upload').eq(0);

			if ( pix_media_frame ) {
				pix_media_frame.open();
				return;
			}

			pix_media_frame = wp.media.frames.pix_media_frame = wp.media({

				className: 'media-frame pix-media-frame',
				frame: 'post',
				multiple: false,
				library: {
					type: 'image'
				}
			});

			pix_media_frame.on('insert', function(){
				var media_attachments = pix_media_frame.state().get('selection').toJSON(),
					thumbSize = jQuery('.attachment-display-settings select.size option:selected').val(),
					thumbUrl;

				jQuery.each(media_attachments, function(index, el) {
					//console.log(JSON.stringify(media_attachments));
					var url = this.url,
						id = this.id,
						size = typeof thumbSize!=='undefined' ? thumbSize : '';

					if ( size !== '' ) {
						size = this.sizes[size];
						url = size.url;
					}

					if ( typeof this.sizes != 'undefined' && typeof this.sizes.thumbnail != 'undefined' ) {
						previewUrl = this.sizes.thumbnail.url;
					} else {
						previewUrl = url;
					}
					wrap
						.find('input.pix-image-item').val(url).end()
						.find('input.pix-image-id').val(id).end()
						.find('input.pix-image-size').val(size);
					getThumbnailUrl(id, wrap.find('.img_preview'), '');
				});

			});

			pix_media_frame.open();
			jQuery('.media-menu a').eq(1).hide();
			jQuery('.media-toolbar-secondary').hide();
		});

		t.off('click','.remove-descriptive-thumb');
		t.on('click','.remove-descriptive-thumb', function( e ){
			e.preventDefault();
			var button = jQuery(this),
				wrap = button.parents('.pix_upload').eq(0);
			wrap
				.find('input.pix-image-item').val('').end()
				.find('input.pix-image-id').val('').end()
				.find('input.pix-image-size').val('').end()
				.find('.img_preview').css({background:'none'}).removeClass('filled');
		});
	});
	
}

/********************************
*
*   Select
*
********************************/
function getSelValue($selector){
	if (typeof $selector == 'undefined' || $selector === '') {
		$selector = jQuery('#pix_content_loaded');
	}
    jQuery('select', $selector).each(function(){
		jQuery(this).bind('change',function(){
			var tx = jQuery('option:selected',this).text();
			if ( !jQuery(this).parents('span').eq(0).find('.appended').length ) {
				jQuery(this).parents('span').eq(0).prepend('<span class="appended" />');
			}
			var elm = jQuery(this).siblings('.appended');
			jQuery(elm).text(tx);
	    }).triggerHandler('change');
	});
}

/********************************
*
*   Ajax loaders
*
********************************/
function ajaxLoaders($start){
	if ( $start===true ) {
		var spinclone = jQuery('#spinner2').clone().attr('id','spinnerclone');
		jQuery('.ui-dialog-content:visible > *').animate({ opacity : 0.25}, 250).parents('.ui-dialog-content').eq(0).append(spinclone.animate({opacity:1}, 250));
	} else {
		jQuery('.ui-dialog-content #spinnerclone').animate({opacity:0}, 250, function(){
			jQuery(this).remove();
		});
		jQuery('.ui-dialog-content > *').animate({ opacity : 1}, 250);
	}
}

/******************************************************
*
*	Select font set
*
******************************************************/
//function selectFontSet($tdial,$id,$textarea){
function selectFontSet(){
	jQuery('#shortcodelic_fonticons_generator_cloned .select_font_set').off('change');
	jQuery('#shortcodelic_fonticons_generator_cloned .select_font_set').on('change',function(){
		var val = jQuery('option:selected',this).val();
		ajaxLoaders(true);
		jQuery.ajax({
            url: pix_theme_dir + '/font/scicon-' + val + '.php',
            cache: false,
            success: function(loadeddata) {
				jQuery('#shortcodelic_fonticons_generator_cloned .shortcodelic_font_list_wrap input').val('');
				var html = jQuery("<div/>").append(loadeddata.replace(/<script(.|\s)*?\/script>/g, "")).html();
				jQuery('#shortcodelic_fonticons_generator_cloned .shortcodelic_font_list').html(html);
				hideByTyping();
				jQuery('#shortcodelic_fonticons_generator_cloned input[type="text"]').triggerHandler('keyup');
				//insertSCicons($tdial,$id,$textarea);
				ajaxLoaders();
            }
		});
	});
}

/******************************************************
*
*	Find icon on the list
*
******************************************************/
function hideByTyping(){
	jQuery('#shortcodelic_fonticons_generator_cloned input[type="text"]').keyup(function(){
		var val = jQuery(this).val();
		if ( val != '' ) {
			jQuery('#shortcodelic_fonticons_generator_cloned .the-icons').not('[data-search*="'+val+'"]').hide();
			jQuery('#shortcodelic_fonticons_generator_cloned .the-icons[data-search*="'+val+'"]').show();
		} else {
			jQuery('#shortcodelic_fonticons_generator_cloned .the-icons').show();
		}
	});
}

/********************************
*
*   Font icons
*
********************************/
function menuFontIcons(){
	jQuery(document).off('click','.icon-preview, .icon-preview-edit');
	jQuery(document).on('click','.icon-preview, .icon-preview-edit',function(e){
		e.preventDefault();
		var h = jQuery(window).height(),
			w = (typeof jQuery(this).attr('data-width') != 'undefined') ? jQuery(this).attr('data-width') : 400,
			dial = jQuery(this).parents('li.menu-item').eq(0);
			dial.hide();
		var iconSel = jQuery('#shortcodelic_fonticons_generator').clone(),
			iconTitle = iconSel.attr('data-title'),
			searchTitle = iconSel.attr('data-search');

		iconSel.attr('id','shortcodelic_fonticons_generator_cloned').dialog({
			height: (h*0.8),
			width: '80%',
			modal: false,
			dialogClass: 'wp-dialog pix-dialog pix-dialog-info pix-dialog-input',
			position: { my: "center", at: "center", of: window },
			title: iconTitle,
			zIndex: 51,
			create: function(){
		        jQuery('body').addClass('overflowHidden');        
				jQuery('body').append('<div id="pix-modal-overlay" />');
				getSelValue(jQuery('#shortcodelic_fonticons_generator_cloned'));
				jQuery(this).find('label').text(searchTitle);
				hideByTyping();
				selectFontSet();
				iconSel.off('click','.the-icons');
				iconSel.on('click','.the-icons',function(){
					var classIcon = jQuery('i',this).attr('class');
					dial.find('.icon-preview i').attr('class',classIcon);
					dial.find('.pix-icon-item').val(classIcon);
					iconSel.dialog('close');
				});
			},
			close: function(){
				dial.show();
				jQuery('#pix-modal-overlay').remove();
				iconSel.remove();
				jQuery('body').removeClass('overflowHidden'); 
				jQuery(window).unbind('resize');  
			}
		});
		jQuery(window).bind('resize',function() {
			h = jQuery(window).height();
			iconSel.dialog('option',{'position':{ my: "center", at: "center", of: window },'height':(h*0.8)});
		});
	});

	jQuery(document).off('click','.icon-remove');
	jQuery(document).on('click','.icon-remove',function(e){
		e.preventDefault();
		var dial = jQuery(this).parents('li.menu-item').eq(0);
		dial.find('.icon-preview i').attr('class','');
		dial.find('.pix-icon-item').val('');
	});
}


jQuery(function(){
	if(pagenow=='nav-menus') {

		update_megamenu();
		uploadSlidesForSlideshow();
		menuFontIcons();

		jQuery('body').ajaxSuccess(function() {
			var set = setTimeout('update_megamenu()',1);
		});
		
		jQuery('#menu-to-edit').bind( "sortstop", function(event, ui) {
			var set = setTimeout('update_megamenu()',1);
		});
		
	}
});

