
var maxAdminPro;
//var maxadmin;

jQuery(document).ready(function($) {
	maxAdminPro = function ()
	{
 		this.pack_loader_process = 0; 
 		this.uploader = null; 
	}

if (typeof(maxAdmin) !== 'undefined')	
	maxAdminPro.prototype = new maxAdmin();
 

maxAdminPro.prototype.init = function () { 
 	maxAdmin.prototype.init.call(this);
 	
 	this.attachMediaUploader('icon_url'); 
 
	this.font_awesome_icon(); // init

	$('input[id="use_fa_icon"]').on('change', $.proxy( this.font_awesome_icon, this) );  
	
	// Should go to own function
	$(document).on('click','.font-awesome ul li', $.proxy(function(e) 
	{
		e.preventDefault();
 		var target = $(e.target); 
 		
 		if (typeof target.data('mbicon') == 'undefined') 
 			target = $(target).children('i'); 
 		
 		var icon = $(target).data('mbicon'); 

		$('#fa_icon_value').val(icon); 
  
 		 window.maxFoundry.maxmodal.close(); // handy 
 		 this.updateIcon();

	} ,this)); 
	
	$(document).on('click', '.font-awesome-preview .remove_fa_icon', $.proxy(this.removeIcon, this));
	
	// packs tabs and handling
	$('#packs_tab a').on('click', this.togglePacksTabs); 
	$(document).on('get-free-packs', $.proxy(this.loadFreePacks, this) ); 
	$(document).on('click','.load_pack_preview', $.proxy(this.loadPackPreview, this) ); 
 
 	// license interface
 	$(document).on('click','#license_form #update_license', $.proxy(this.activateLicenseFields, this)); 
	$(document).on('click','#license_form #activate_button', $.proxy(this.activateLicense, this));
	
	// export form error handling
	$('#export-form').on('submit', $.proxy(this.checkExportForm, this));

	// new buttons to check fonts for. 
	$(document).on('mb_media_put_results', function () 
	{
		window.maxFoundry.maxfonts.checkFonts();
	}); 

	// button importer from packs 
 	$(document).on('change', '.pack-list input[type="checkbox"]', $.proxy(this.togglePackButton, this) ); 
 	$(document).on('click', '.pack-list-header button[name="import_button"]', $.proxy(this.importPackButtons, this) );
 	$(document).on('click', '.pack-list .shortcode-container a', function (e) { 
 		e.preventDefault();
 		$(e.target).parents('label').trigger('click');  // fix for not being able to click on the button itself to select button
 	}); 
 	this.togglePackButton();
 }


maxAdminPro.prototype.update_color = function(event, ui, color) 
{
	var target = $(event.target);
	var id = $(target).attr('id'); 
	$('#' + id).val(color); 
	
	if(id.indexOf('icon') !== -1)
			this.updateIcon(target);
	else
		maxAdmin.prototype.update_color.call(this,event,ui, color);

}

maxAdminPro.prototype.togglePackButton = function ()
{
	if ( $('.pack-list').length == 0)
		return;  // el not defined
	
	var number = $('.pack-list input[type="checkbox"]:checked').length;

	$('.pack-list-header .count').text(number); 
	
	if (number == 0) 
		$('.pack-list-header button').prop('disabled', true);
	else
		$('.pack-list-header button').prop('disabled', false);
	
}

maxAdminPro.prototype.importPackButtons = function (e) 
{
	console.log('import pack buttons'); 
	var number_imported = 0; 
	var ajax_actions = 0;
	
	var buttons = $('.pack-list input[type="checkbox"]:checked'); 
	ajax_actions = buttons.length; 
	var self = this; 
	
	buttons.each( function (index)
	{
		var id = $(this).val(); 
		var data = $('.pack-list div[data-button="' + id + '"]').text();

		data = { 
			action: 'import_button', 
			data: data,
		}
		
		$.post({
			url: mb_ajax.ajaxurl, 
			data: data,
			success: $.proxy( function(response) {
				number_imported++;

				this.importPackButtonDone(response, ajax_actions, number_imported);
			}, self), 	
		});
	});

}

maxAdminPro.prototype.importPackButtonDone = function (response, total, number_done ) 
{
	var data = JSON.parse(response);
	if (typeof data.button == 'undefined' || data.button <= 0)
	{
	} 
	
	// all done. 
	if (total == number_done) 
	{
			
		$('input[name="import_modal"]').trigger('click'); // badly trigger import done modal

		$('.pack-list input[type="checkbox"]:checked').prop('checked', false);
		this.togglePackButton();
		
	}

}

maxAdminPro.prototype.font_awesome_icon = function()
	{
		var checked = $('input[id="use_fa_icon"]').is(':checked'); 
		if (checked) 
		{
			$(".non-fa").hide(); 
			$(".fa-only").show();
			$('.font-awesome').addClass('checked');
		}
		else
		{
			$(".fa-only").hide();
			$(".non-fa").show(); 
			$('.font-awesome').removeClass('checked');

		}
		this.updateIcon();
	}
 
maxAdminPro.prototype.updateFontAwesomeIcon = function()
	{
		var icon_value = $('#fa_icon_value').val();
		var position = $('#icon_position').val(); 
				
		if (icon_value == '') 
		{
			$('.output .result a .mb-icon').css('padding', ''); // remove the padding since it's false.
			return; // no icon 
		}
		$('.mb-icon i, .font-awesome-preview i').removeClass().addClass('fa ' + icon_value); 

		var icon_size = $('#fa_icon_size').val(); 
		var icon_color = $('#icon_color').val(); 
		var icon_color_hover = $('#icon_color_hover').val();

		if (position == 'background') 
		{
			$('.output .result a .mb-icon').css('position', 'absolute');
			$('.output .result a .mb-icon').css('box-sizing', 'border-box');				
			$('.output .result a .mb-icon').css('width', '100%');
			$('.output .result a .mb-icon').css('height', '100%');			
		}
		
		
		
		$('.mb-icon, .font-awesome-preview').css('fontSize', icon_size + 'px'); 
		
		$('a.normal .mb-icon ').css('color', icon_color); 
		$('a.hover .mb-icon ').css('color', icon_color_hover);

		$('.font-awesome-preview .remove_fa_icon').show(); 
}
	
maxAdminPro.prototype.updateIcon = function (target)
	{
		target = target || ''; 
		
		var checked = $('input[id="use_fa_icon"]').is(':checked'); 
		var ptop = parseInt($('#icon_padding_top').val()); 
		var pright = parseInt($('#icon_padding_right').val());
		var pbottom = parseInt($('#icon_padding_bottom').val());
		var pleft = parseInt($('#icon_padding_left').val());
		
		if (isNaN(ptop) || ptop < 0) ptop = 0; 
		if (isNaN(pright) || pright < 0) pright = 0; 
		if (isNaN(pbottom) || pbottom < 0) pbottom = 0; 
		if (isNaN(pleft) || pleft < 0) pleft = 0; 				
		
		var padding = ptop + 'px ' + pright + 'px ' + pbottom + 'px ' + pleft + 'px'; 
		var icon_url = $('#icon_url').val();

		var position = $('#icon_position').val(); 
		
		$('.output .result').find('.mb-icon').remove();
		
		var anchorhtml = $('.output .result a.normal').html(); 
		var anchorhtml_hover = $('.output .result a.hover').html();
		 
		if (! checked && icon_url == '') 
			return;
		
		if (position == 'bottom')		
		{
			$('.output .result a.normal').html(anchorhtml  + "<span class='mb-icon'  ><i class='fa'></i></span>" ); 
			$('.output .result a.hover').html(anchorhtml_hover + "<span class='mb-icon'  ><i class='fa'></i></span>" ); 

		}
		else
		{
			$('.output .result a.normal').html("<span class='mb-icon'  ><i class='fa'></i></span>" + anchorhtml ); 
			$('.output .result a.hover').html("<span class='mb-icon'  ><i class='fa'></i></span>" + anchorhtml_hover ); 

		}

		$('.output .result a .mb-icon').css('padding', padding);
	 	// with update important statements are removed: 
	 	$('.output .result a .mb-icon').css('display', 'block');
		$('.output .result a .mb-icon').css('lineHeight', '0px');
 	
	 	
	 	switch(position) 
	 	{
	 		case "left": 
	 			$('.output .result a .mb-icon').css('float', 'left');
	 		break;
	 		case "right":
	 			$('.output .result a .mb-icon').css('float', 'right');
	 		break;
	 		case "top":
	 		case "bottom":
		 		$('.output .result a .mb-icon').css('textAlign', 'center'); 
	 		break;
	 	}	
	 
		if (checked) 
		{	
			this.updateFontAwesomeIcon();
		}
		else
			this.updateImageIcon();
	}
	
maxAdminPro.prototype.updateImageIcon = function()
	{
		var url = $('#icon_url').val();
		var alt = $('#icon_alt').val(); 
		
		if (url == '') return; 
		
		var position = $('#icon_position').val(); 
		
		var pleft = parseInt($('#icon_padding_left').val());
		var ptop = parseInt($('#icon_padding_top').val()); 
				
		if (position == 'background') 
		{
			$('.output .result a .mb-icon').css('position', 'absolute');
			$('.output .result a .mb-icon').css('box-sizing', 'border-box');		
			$('.output .result a .mb-icon').css('backgroundImage','url(' + url + ')');
			$('.output .result a .mb-icon').css('backgroundRepeat', 'no-repeat');
			$('.output .result a .mb-icon').css('backgroundPosition', pleft + 'px ' + ptop + 'px');
			$('.output .result a .mb-icon').css('padding', '0');
			
			$('.output .result a .mb-icon').css('width', '100%');
			$('.output .result a .mb-icon').css('height', '100%');
			$('.output .result a .mb-icon').children().remove(); 	
		}	
		else			
			$('.output .result').find('.mb-icon').html('<img src="' + url + '" alt="' + alt + '" >'); 
		
	}

maxAdminPro.prototype.updateAnchorText = function (target)
{
	 
	var text = $('#text').val(); 
	var text2 = $('#text2').val(); 
	

 	var button_id = this.button_id; 
 
		
	$(".mb-text").text(text);
	$(".mb-text2").text(text2);
	if (text2 == '') 
		$('.mb-text2').hide(); 
	else
	{
		$('.mb-text2').show(); 
		$('.mb-text2').css('display','block');
	}
		
}

maxAdminPro.prototype.updateFont = function (target)
{
	window.maxFoundry.maxfonts.checkFonts();
}	
 

maxAdminPro.prototype.togglePacksTabs = function(e) {
	e.preventDefault(); 
	var active = $('#packs_tab a.nav-tab-active'); 
	var clicked = $(e.target);
	
	$(active).removeClass('nav-tab-active'); 
	$(clicked).addClass('nav-tab-active'); 
	
	var active_screen = $(active).data('screen'); 
	var clicked_screen = $(clicked).data('screen'); 
	
	$('#' + active_screen).hide(); 
	$('#' + clicked_screen).show();
	
	if (clicked_screen == 'free_packs_screen')
	{
		$(document).trigger('get-free-packs');
 
	}		
}

maxAdminPro.prototype.loadFreePacks = function () { 
 
		if (this.pack_loader_process !== 0)
		{ return false; }
		
		this.pack_loader_process = 1; // loading
 		var nonce = $('#free-pack-nonce').text(); 
		var data = { 'remote_action': 'get_free_overview', 
					 'action': 'pack_request',
					 'nonce': nonce, 
				   };
		$.ajax({
			url: ajaxurl,
			type: 'GET',
			dataType: "html",
			data: data,
			success: $.proxy(this.updateFreePacksScreen, this)		
		});
};

maxAdminPro.prototype.updateFreePacksScreen = function(results, status)
{
	this.pack_loader_process = 0; 

 	$('.free_packs .pack_container').html(results);
 	$('.free_packs .loading').hide(); 
 	$(".free_preview").hide();
 	$(".free_packs").show();
 	
	$(document).off("click", ".free_packs .use"); 
	$(document).on("click",".free_packs .use", $.proxy(this.getFreePackDownloadLink, this) ); 	
 	
}

maxAdminPro.prototype.loadPackPreview = function(e)
{
	e.preventDefault();
  	var pack_url = $(e.target).closest('[data-pack]').data("pack"); 
  	var pack_id = $(e.target).closest('[data-pack]').data('packname');
  	//if (typeof pack
 
	this.pack_loader_process = 2; // loading pack
  	var nonce = $('#free-pack-nonce').text(); 
  	
		var data = { 'remote_action': 'get_free_pack_preview', 
					 'action': 'pack_request',
					 'pack_url': pack_url,
					 'pack': pack_id, 
					 'nonce': nonce, 
				   };
		$.ajax({
			url: ajaxurl,
			type: 'GET',
			dataType: "html",
			data: data,
			success: $.proxy(this.showPackPreview, this, pack_id)		
		});
}

maxAdminPro.prototype.showPackPreview = function (pack_id, results, status)
{
	this.pack_loader_process = 0; 
	$(".free_preview .results").html(results);
	
	
	// for now hide the use this button button
	//$(".free_preview .results .use-pack-button").hide();
	 	
 	$(".free_packs").fadeOut();
 	$(".free_preview").fadeIn();
 	
 	// load custom fonts 
 	window.maxFoundry.maxfonts.checkFonts();
 	
 	$(".free_preview .use").data("pack", pack_id); 

	// this prevents binding too much events ( every load ) to this. 
 	$(document).off("click", ".free_preview .use"); 
 	$(document).off("click",".free_preview .close");
 	
 	$(document).on("click",".free_preview .close", function () {
	 	$(".free_packs").fadeIn();
	 	$(".free_preview").fadeOut();
 	}); 
 	$(document).on("click",".free_preview .use", $.proxy(this.getFreePackDownloadLink, this) );
 	
}

maxAdminPro.prototype.getFreePackDownloadLink = function (e)
{
	if ($(e.target).hasClass('disabled'))
		return false; 

	
	var pack_id = $(e.target).data("pack");
	this.pack_loader_process = 3; // download
 
  	var nonce = $('#free-pack-nonce').text(); 
	var data = { 'remote_action': 'get_free_download_link', 
				 'action': 'pack_request',
				 'pack': pack_id, 
				 'nonce': nonce, 
			   };
				   	
	$.ajax({
			url: ajaxurl,
			type: 'GET',
			dataType: "html",
			data: data,
			success: $.proxy(this.packDownload, this, pack_id)		
		});	
}

maxAdminPro.prototype.packDownload = function (pack_id, results) 
{
	try	{
		results = JSON.parse(results);
	} catch (e) { }	
  
	if (typeof results.status !== 'undefined')
	{
		alert('An error occured: ' + results.error_message); return;
	}
	var port = ''; 
	if (window.location.port !== '' && typeof window.location.port !== 'undefined') 
		var port = ':' + window.port; 
 
	var url = window.location.protocol + '//'  +  window.location.host + port  + window.location.pathname; 
  	
  	window.location.href = url + '?page=maxbuttons-controller&action=pack&id=' + pack_id; 
	
}

maxAdminPro.prototype.deletePack = function (modal)
{
	var target = modal.target; 
	var href = $(modal.target).attr('href'); 
	$(modal.currentModal).find('.yes').attr('href', href); 
	
}

maxAdminPro.prototype.checkExportForm = function(e)
{
	//e.preventDefault();
	if ( $('input[name="pack_name"]').val() == '')
	{
		 $('input[name="pack_name"]').css("border","1px solid #ff0000");
		 return false;
	}
	return true;
}

maxAdminPro.prototype.activateLicenseFields = function(e)
{
	e.preventDefault(); 
	
	$('#license_key').prop('disabled', false); 
	$('#license_email').show();
	$('#update_license_field').hide();
	$('#activate_license_field').show();

}

maxAdminPro.prototype.activateLicense = function(e)
{
	e.preventDefault();
	$("#activation_progress").show();
	$("#activation_success").hide();
	$("#activation_error").hide();
	$("#activation_need_fields").hide();

	var key = $('#license_key').val(); 
	var nonce = $('#activate-license').val(); 
	
	var validate = true; 
 
	if (key == '')
	{ 
		validate = false; 
		$('#license_key').css('border','1px solid #ff0000'); 
	}
	

	if (! validate)
	{
		$('#activation_need_fields').show();
		$('#activation_progress').hide();
		return;	
	} 
	 
	var data = {  license_key: key, 
				 'activate_license': nonce,
				 action: 'mbpro_activate_license',
				};
				
	jQuery.ajax({
		type: "POST",
		url: ajaxurl ,
		data: data,
		success: function(result) {
			jQuery("#activation_progress").hide();


			if (result != "") {
				if (result.status == "error") {
					
					$("#activation_error").show();
					var msg = result.additional_info;
					$("#activation_error h4").text(msg);
				}
				
				if (result.status == "success") {
					$("#activation_success").show();
					window.setTimeout(function() {
						//window.location.reload();
					}, 2000);
				}
			}
		}
	});
	
	return false;	

}

maxAdminPro.prototype.attachMediaUploader = function (key) {
	
	jQuery('#' + key + '_button').on('click', { key: key }, function(event) {
		event.preventDefault();

		var uploader = this.uploader; 
		
		// If the media frame already exists, reopen it.
		if ( typeof uploader !== 'undefined' ) {
			 uploader.open();
			return;
		}
		
		// Create the media frame.
		uploader = wp.media.frames.file_frame = wp.media({
			title: jQuery( this ).data( 'uploader_title' ),
			button: {
			text: jQuery( this ).data( 'uploader_button_text' ),
			},
			multiple: false // Set to true to allow multiple files to be selected
		});
		
		// When an image is selected, run a callback.
		uploader.on( 'select', function() {
		// We set multiple to false so only get one image from the uploader
 
		
		attachment = uploader.state().get('selection').first().toJSON();
 		$('#' + key ).val(attachment.url); 
 	
 		//var html = $('#' + key + '_preview').html();
 		$('.icon_preview').find('img').remove();
 		
 		$('#' + key + '_preview').prepend('<img src="' + attachment.url + '">');

 		$('#icon_id').val(attachment.id); 

 		$('#' + key).trigger('keyup');
		$('#' + key + '_preview .remove_icon').show(); 
		
		$('.icon_data .alt').text(attachment.alt);
		$('.icon_data .atttitle').text(attachment.title);
		$('.icon_data .filename').text(attachment.filename);

		//$(document).off('click','#' + key + '_preview .remove_icon');
		//$(document).on('click','#' + key + '_preview .remove_icon', $.proxy(this.removeImage, this) );
				
		// Do something with attachment.id and/or attachment.url until here
		});
		
		// Finally, open the modal
		uploader.open(); 		
		
	} );

	// Image remove
	$(document).on('click','#' + key + '_preview .remove_icon', $.proxy(this.removeImage, this) );


	if (! parseInt($('#icon_id').val()) > 0 )
	{
		$('#' + key + '_preview .remove_icon').hide();
	}	
}

maxAdminPro.prototype.removeImage = function(e) 
{
	$('#icon_id').val('');
	$('#icon_url').val('');
	$('#icon_url').trigger('keyup');
	$('.icon_preview').find('img').remove();
	$('.icon_preview .remove_icon').hide();
	$('.icon_data span').text('');
	
}

maxAdminPro.prototype.removeIcon = function (e) 
{
	var val = $('#fa_icon_value').val(); 
	$('.font-awesome-preview i').removeClass(val); 
	$('#fa_icon_value').val(''); 
	$('.font-awesome-preview .remove_fa_icon').hide(); 
	this.updateIcon();
}

maxAdminPro.prototype.export_button = function(modal, button_id)
{

	

}

 	
}); /* END OF JQUERY */
 	

