jQuery(document).ready(function() {
    jQuery('#addmore').click(function() { addRow(); });
    jQuery(':text[id^="item-"]').bind('blur', getTitle);
    jQuery('#tosubmit').click(function() { toSubmit(); });
    jQuery('#parentsubmit').click(function() { pSubmit(); });
	jQuery(':text[id^="item-"]').bind('keypress', digits);
});

function addRow() {
	var numRows = jQuery('#tb')[0].rows.length;
	
	jQuery('#tb tr:last').after(
		'<tr><td><select name="type-' + numRows + '" id="type-' + numRows + '">' +
		'<option value="1">Post/Page/Attachment</option><option value="2">Pbox</option>' +
		'</select></td><td><input type="text" name="item-' + numRows + '" id="item-' +
		numRows + '" /></td><td><div id="title-' + numRows + '"></div></td></tr>'
	);

	jQuery('#total').val(numRows);
	jQuery(':text[id^="item-"]').bind('blur', getTitle);
	jQuery(':text[id^="item-"]').bind('keypress', digits);
}

function digits(e) {
	if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) {
		//display error message
		jQuery('#result').html('<font color="red">Digits Only!</font>')
			.show().animate({opacity: 1.0}, 1000).fadeOut('slow'); 
	    return false;
    }	
}

function getTitle(e) {
	var idText = e.target;
	if (!idText.value) return;
	var patt = /item-(\d+)/;
	var id = idText.id;
	var rs = patt.exec(id)
	var type = jQuery('#type-' + rs[1]).val();
	//type: 1, page/post; 2, pbox
	var data = {
		'action': 'wp2wpGetTitle',
		'type':   type,
		'id':     idText.value
	};
	jQuery('#title-' + rs[1]).load(ajaxurl, data);
}

function toSubmit() {
	var allEmpty = true;
	jQuery(':text[id^="item-"]').each(function(){	
		if (this.value) {			
			allEmpty = false;
			return false;
		}
	});
	if (allEmpty) return;
	if (confirm("You are about to export all the items specified.\n'Cancel' to stop, 'OK' to export.")) {
		jQuery('body').css('cursor', 'wait');
		dataString = jQuery("#exportIP").serialize();
		dataString += '&action=wp2wpExportIP';
		jQuery('#result').html('');	
		jQuery.post(ajaxurl, dataString, function(response){
			jQuery('#result').html(response);
			jQuery('body').css('cursor', 'default');
		});

	}
}

function pSubmit() {
	if (!jQuery(':text[id="item-1"]').val()) return;
	if (confirm("You are about to export all the data associated with this Parent Id.\n'Cancel' to stop, 'OK' to export.")) {
		jQuery('body').css('cursor', 'wait');
		dataString = jQuery("#parent").serialize();
		dataString += '&action=wp2wpExportXML';
		jQuery('#result').html('');
		jQuery.post(ajaxurl, dataString, function(response){
			jQuery('#result').html(response);
			jQuery('body').css('cursor', 'default');
		});
	}
}

