
/**
 *	Replacement window.resize function, to allow us to set a size for Thickbox, without media-upload.js interferring.
 **/
function wordy_window_resize() {
	if (jQuery('#TB_window').hasClass('wordy'))
		wordy_tbiframe_resize();
	else
		tb_position();
}

/**
 * Resizes the Thickbox window for Wordy. Called on window.resize when Wordy has a Thickbox open.
 **/
function wordy_tbiframe_resize() {
	var WordyPaymentWidth	= 1000;
	var TB_newWidth			= jQuery(window).width() < (WordyPaymentWidth + 40) ? jQuery(window).width() - 40 : WordyPaymentWidth;
	var TB_newHeight		= jQuery(window).height() - 70;
	var TB_newMargin		= (jQuery(window).width() - WordyPaymentWidth) / 2;
	
	jQuery('#TB_window').css({'marginLeft': -(TB_newWidth / 2)})
	jQuery('#TB_window, #TB_iframeContent').width(TB_newWidth).height(TB_newHeight)
}


/**
 * Checks the first found a.thickbox element to see if Thickbox has attached a click event. If it has, run wordy_tbshow()
 * DEPRECATED: Doesn't work with WP30.
 **/
function wordy_checktb() {
	// Step through click events in the click object of the first a.thickbox element
	jQuery.each( jQuery('a#add_image').data('events')['click'], function(i, event) {
		console.log( i );
		var thisEvent	= event.toString().replace(/\n/g, '').replace(/\t/g, '').split(' ').join('');
		var TBEvent		= 'function(){vart=this.title||this.name||null;vara=this.href||this.alt;varg=this.rel||false;tb_show(t,a,g);this.blur();returnfalse;}';

	    if (thisEvent == TBEvent) {
	    	console.log( 'Hurray!' );
	    	//clearTimeout(forcePayment);
	    	clearInterval(checkThickboxInit);
			wordy_tbshow();
			return;
	    }
	})
}

/**
 *	Get Thickbox to open the Wordy Payment page in an iframe.
 **/
function wordy_tbshow() {
	tb_show('Wordy Payment', wordyPluginURL + '/iframe.html?TB_iframe=true');
}


/**
 * Attaches window.resize event logic and opens the iframe in Thickbox when possible.
 **/
function wordy_init_payment( e ) {
	wordyPluginURL = e;

	// The WP media manager tries to control ThickBox's size in the most obnoxious and horribly implemented way imaginable. But we can't let that happen, because we need to be able to set the size. So we disable it and recajigger a new window.resize event that doesn't fuck up Wordy's Thickbox.
	jQuery.each( jQuery(window).data('events')['resize'], function(i, event) {
		var thisEvent		= event.toString().replace(/\n/g, '').replace(/\t/g, '').split(' ').join('');
		var expectedEvent	= 'function(){tb_position()}';

	    if (thisEvent == expectedEvent) {
			delete jQuery(window).data('events')['resize'][i];
			jQuery(window).bind('resize.wordy', wordy_window_resize)
    	}
	})

	// Load the payment page using Thickbox (bundled w. WP).
	// We have to detect when Thickbox is initialized because it doesn't tell us,
	// So every 50ms we check the first a.thickbox (the media manager icons as it were)
	// to see if they have Thickbox's event attached to them. If they do, TB is active,
	// And we can show Wordy's payment.
	// As a safety, we try to force it after 2s (in case there is no a.thickbox for instance).
	checkThickboxInit	= setTimeout(wordy_tbshow, 1000);

/* 	forcePayment		= setTimeout(function() { clearInterval(checkThickboxInit); wordy_tbshow(); }, 2000);}) */
}




/**
 * Format the cost, and return at least €3
 *
 * @param {pAmount} int  
 * @return Corrected integer.
 **/
function wordyMoneyFormat(pAmount) {
	pAmount = Math.round(pAmount * 100) / 100;
	var minAmount = 3;
	
	vZeroFill = pAmount.toString();

    if ( vZeroFill.indexOf('.') + 2 == vZeroFill.length )
		vZeroFill = vZeroFill + '0';
    else if ( vZeroFill.indexOf('.') == -1 )
		vZeroFill = vZeroFill + '.00';

	vZeroFill = parseInt(vZeroFill);

	// Return at least minAmount.
	vZeroFill = (vZeroFill > minAmount) ? vZeroFill : minAmount;

    return vZeroFill;
}


/**
 * Strip text of words and HTML, and count it.
 *
 * @param {text} string The text to do a word count on. 
 **/
function wordyCountWords(text) {
	var count = 0;

	cleantext = text.replace(/\s/g,' ').replace(/(&lt;([^&gt;]+)&gt;)/ig,"").replace(/(<([^>]+)>)/ig,"").split(' ');

	for (var i = 0; i < cleantext.length; i++) {
		if ( cleantext[i].length > 0 ) count++;
	}
	
	return count;
}


/**
 * Calculate the cost of the contents on-the-fly.
 *
 * @param {wordprice} int The cost in Euro, per word.
 **/
function wordyCountCost(wordprice) {

	if ( jQuery('#wp-word-count').html() != '' ) {

		// Insert <span> for cost
		if ( jQuery('#wp-word-count-cost').length <= 0 ) jQuery('#wp-word-count').append('<span id="wp-word-count-cost"></span>')

		// Get the post content and do a word count.
		var richEditor = (typeof tinyMCE != "undefined") && !tinyMCE.activeEditor.isHidden();

		var wordCount = richEditor ? wordyCountWords( tinyMCE.activeEditor.getContent() ) : wordyCountWords( jQuery('textarea#content').val() );

		// Add excerpt word count.
		try			{ wordCount = wordCount + wordyCountWords( jQuery('#excerpt').val() ); }
		catch(e)	{ }

		// Insert the word count		
		jQuery('#word-count').html(wordCount);

		// If we have a price, insert that as well.
		if (wordprice > 0)
			jQuery('#wp-word-count-cost').html(' / &asymp;&nbsp;&euro;' + wordyMoneyFormat( wordCount * wordprice ));
	}
}


/**
 * Insert necessary markup and initialize the word counter/word cost calculator
 *
 * @param {wordprice} int The cost in Euro, per word.
 **/
function wordyInitCountCost(wordprice) {
	// Count the words
	setInterval(function() { wordyCountCost(wordprice) }, 500);
}