/**
 * @author HP
 */
jQuery( function($) { // In here $ is jQuery

bbSortPages = {
	handleText: 'drag',
	handle: '',
	sortCfg: {
		accept: 'page-item',
		opacity: .8,
		handle: 'strong.sort-handle',
		helperclass: 'helper',
		onStop: function() {
			bbSortPages.place = null;
			bbSortPages.recolor();
			bbSortPages.nextPage.update();
			bbSortPages.previousPage.update();
		}
	},
	editText: 'Edit Page Order »',
	saveText: 'Save Page Order »',
	cancelText: 'Cancel Page Order',
	place: null,  // The item it's currently hovering after
	placed: null, // The item it's been made a child of
	rtl: false,
	//rtl: 'rtl' == $('html').attr( 'dir' ),

	recolor: function() {
		$('#page-list-root li').css( 'background-color', '' ).filter(':even').removeClass('alt').end().filter(':odd').addClass('alt');
	},
	previousPage: {
		text: 'Items above this will appear in the previous page.',
		update: function() {
			if (!this.elm) {
				this.elm = $("<div class='page-list-previous-page-warn clear-element'>" + bbSortPages.previousPage.text + "</div>");
			}
			$('#page-list-root div.list-block:first').after(this.elm);
		},
		remove: function() {
			$('div.page-list-previous-page-warn').remove();
		}
	},
	nextPage: {
		text: 'Items bellow this will appear in the next page.',
		update: function() {
			if (!this.elm) {
				this.elm = $("<div class='page-list-next-page-warn clear-element'>" + bbSortPages.nextPage.text + "</div>");
			}
			$('#page-list-root div.list-block:last').before(this.elm);
		},
		remove: function() {
			$('div.page-list-next-page-warn').remove();
		}
	},

	checkHover: function(el, doit) {
		bbSortPages.nextPage.update();
		bbSortPages.previousPage.update();
		if ( this.place == el && doit )
			return;

		if ( !doit ) {
			this.place = null;
			return;
		}

		this.place = el;
		if ( $(this.place).children('ul[li:visible]').size() ) // Don't shift over if there's already a UL with stuff in it
			return;
		var id = this.place.id.split('-')[1];
		var newUl = "<ul id='page-root-" + id + "' class='page-list'></ul>";
		$(this.place).not('[ul]').append(newUl).end().children('ul').append(jQuery.iSort.helper.get(0)); // Place in shifted box
		this.placed = el;
	},

	serialize: function () {
		h = '';
		$('#page-list-root, #page-list-root ul').each( function() {
			var i = this.id;
			$('#' + i + '> .page-item').each( function () {
				if (h.length > 0)
					h += '&';
				var root = 'page-list-root' == i ? 0 : i.split('-')[2];
				h += 'root[' + root + '][]=' + this.id.split('-')[1];
			} );
		} );
		return h;
	},
	
	buildList: function (json) {
		var listToJoin = [];
		listToJoin[listToJoin.length] = "<div id='page-list-wrap' class='page-list-wrap'>";
		listToJoin[listToJoin.length] = "<h3>Ordering view...</h3>";
		if(json.columns) {
			listToJoin[listToJoin.length] = "<ul id='page-list-header' class='page-list'><li class='page-item'><div class='list-block'>";
			listToJoin[listToJoin.length] = this.printInfo(json.columns);
			listToJoin[listToJoin.length] = "</div></li></ul>";
		}
		if(json.items) {
			listToJoin[listToJoin.length] = this.printItemList(json.items);
		}
		listToJoin[listToJoin.length] = "</div>";
		return listToJoin.join("");
	},
	
	printItem: function (item) {
		var listToJoin = [];
		listToJoin[listToJoin.length] = "<li class='page-draggable alt clear-element page-item'><div class='list-block'>";
		listToJoin[listToJoin.length] = this.printInfo(item.info);
		listToJoin[listToJoin.length] = "</div>";
		if(item.children) listToJoin[listToJoin.length] = this.printItemList(item.children, item.id);
		listToJoin[listToJoin.length] = "</li>";
		return listToJoin.join("");
	},
	
	printItemList: function (itemListArray, parentID) {
		var listToJoin = [];
		listToJoin[listToJoin.length] = "<ul id='page-list-root" + ((parentID) ? "-" + parentID : "") + "' class='page-list'>";
		for(var i = 0; i < itemListArray.length ; i++){
			listToJoin[listToJoin.length] = this.printItem(itemListArray[i]);
		}
		listToJoin[listToJoin.length] = "</ul>";
		return listToJoin.join("");
	},
	
	printInfo: function (columnsArray) {
		var listToJoin = [];
		for(var i = columnsArray.length - 1; i >= 0; i--){
			listToJoin[listToJoin.length] = "<div class='page-list-col page-list-col-"+ i +"'>"+ columnsArray[i] +"</div>";
		}
		return listToJoin.join("");
	},

	init: function() {
		this.handle = "<strong class='sort-handle'>[" + this.handleText + "]&nbsp;</strong>";
		var editButtoms = "<p class='submit'><input type='button' class='page-order-edit' value='" + this.editText + "' /></p>";
		$('#ajax-response').after(editButtoms);
		$('.widefat').before(editButtoms);
		var div = document.createElement('div'); div.innerHTML = this.saveText; // Save the raquo!
		this.saveText = div.childNodes[0].nodeValue;
		div = null;
		$('.page-order-edit').toggle(
		function() {
			$.getJSON(
				"list_demo_json.js?" + Math.random(), 
				function(json) {
					$('.page-order-edit')
						.before("<input type='button' class='page-order-save' value='" + bbSortPages.saveText + "'/>")
						.val(bbSortPages.cancelText);
					$('.widefat').hide();
					$('#ajax-response').html(bbSortPages.buildList(json));
					Fat.fade_element("page-list-wrap");
					bbSortPages.recolor();
					$('#page-list-root li div.page-list-col-0').prepend(bbSortPages.handle);
					$('#page-list-root').Sortable( bbSortPages.sortCfg );
					bbSortPages.nextPage.update();
					bbSortPages.previousPage.update();
			});
		}, function() {
			$('.page-order-save').remove();
			$('.page-order-edit').val(bbSortPages.editText);
			$('#ajax-response').html('');
			$('.widefat').show();
		} );
	}
}

// overwrite with more advanced function
jQuery.iSort.checkhover = function(e,o) {
	if (!jQuery.iDrag.dragged)
		return;

	if ( e.dropCfg.el.size() > 0 ) {
		var bottom = jQuery.grep(e.dropCfg.el, function(i) { // All the list items whose bottom edges are inside the draggable
			var x = bbSortPages.rtl ? i.pos.x + i.pos.wb > jQuery.iDrag.dragged.dragCfg.nx + jQuery.iDrag.dragged.dragCfg.oC.wb : i.pos.x < jQuery.iDrag.dragged.dragCfg.nx;
			return i.pos.y + i.pos.hb > jQuery.iDrag.dragged.dragCfg.ny && i.pos.y + i.pos.hb < jQuery.iDrag.dragged.dragCfg.ny + 30 && x;
		} );

		if ( bottom.length > 0 ) { // Use the lowest one one the totem pole
			var x = bbSortPages.rtl ? bottom[bottom.length-1].pos.x + bottom[bottom.length-1].pos.wb - 30 > jQuery.iDrag.dragged.dragCfg.nx + jQuery.iDrag.dragged.dragCfg.oC.wb : bottom[bottom.length-1].pos.x + 30 < jQuery.iDrag.dragged.dragCfg.nx;
			if ( bbSortPages.placed != bottom[bottom.length-1] || !x ) { // Testing to see if still placed in shifted box
				bbSortPages.placed = null;
				jQuery(bottom[bottom.length-1]).after(jQuery.iSort.helper.get(0));
			}
			bbSortPages.checkHover(bottom[bottom.length-1], x); // If far enough right, shift it over
			return;
		}

		// Didn't find anything by checking bottems.  Look at tops
		var top = jQuery.grep(e.dropCfg.el, function(i) { // All the list items whose top edges are inside the draggable
			var x = bbSortPages.rtl ? i.pos.x + i.pos.wb > jQuery.iDrag.dragged.dragCfg.nx : i.pos.x < jQuery.iDrag.dragged.dragCfg.nx;
			return i.pos.y > jQuery.iDrag.dragged.dragCfg.ny && i.pos.y < jQuery.iDrag.dragged.dragCfg.ny + 30 && x;
		} );

		if ( top.length ) { // Use the highest one (should be only one)
			jQuery(top[0]).before(jQuery.iSort.helper.get(0));
			bbSortPages.checkHover(top[0], false);
			return;
		}
	}
	jQuery.iSort.helper.get(0).style.display = 'block';
}

if ( 'undefined' != typeof bbSortPagesL10n )
	$.extend( bbSortPages, bbSortPagesL10n );

bbSortPages.init();

var ret = bbSortPages.buildList(
{
	"columns":["Title(ID)", "Owner", "Updated"],
	"items": [
		{
			"id":1, 
			"info":["My Title(1)", "My Owner", "My Date"],
			"children": 
				[
					{
						"id":2, 
						"info":["My Title(2)", "My Owner", "My Date"],
					},
					{
						"id":3, 
						"info":["My Title(3)", "My Owner", "My Date"],
					}
				]
		},
	]
});

var ret2 = ret;

} );
