/****************************************************************************
*	DRAG AND DROP JAVASCRIPT
*
*	Michael McMullen
* michael.mcmullen@tutelagesystems.com
****************************************************************************/
var	drag_timeout	= 500;
var drag_counter	= 0;			// Helps us with reverting the CSS if the drag and drop is cancelled
var drag_dragging	= false;	// Are we still dragging?
var drag_timer		= setTimeout("dragCheckEvent()", drag_timeout);
var drag_dropzone = document.getElementById("drop_zone");

// Initialize Handlers
drag_dropzone.addEventListener("dragenter", drag_EnterEvent, false);
drag_dropzone.addEventListener("dragexit", drag_ExitEvent, false);
drag_dropzone.addEventListener("dragover", drag_OverEvent, false);
drag_dropzone.addEventListener("drop", drag_dropEvent, false)

function drag_EnterEvent(evt){
	$("#drop-overlay").fadeIn();	// Show Overlay
	drag_nullHandler(evt);				// Perform no more actions with the event
}

function drag_ExitEvent(evt){		
	drag_nullHandler(evt);				// Perform no more actions with the event
}

function drag_OverEvent(evt){
	drag_counter	= 2;			// Set a counter to see if we are actually dragging
	drag_dragging		= true;		// Tell our JavaScript that we are dragging
	drag_nullHandler(evt);	// Perform no more actions with the event
}

function dragCheckEvent(){
	drag_timer = setTimeout("dragCheckEvent()", drag_timeout);	//Ensure we fire again
	
	// Check to see if we are dragging
	if(! drag_dragging){
		// We still are, so just escape the function
		return;
	}
	
	drag_counter --;	// Count down the dragging counter
	if(drag_counter <= 0) {
		drag_dragging = false;	// We are no longer dragging
		$("#drop-overlay").fadeOut();
	}
}

//	Null the events on the Drag and Drop we do not want
function drag_nullHandler(evt){
  evt.stopPropagation();
  evt.preventDefault();
}

function drag_dropEvent(evt){
	var files = evt.dataTransfer.files;
	
	if(typeof files == "undefined" || files.length == 0){
		return;
	}
	
	show_ajax();
	
	// Read the file
	var reader = new FileReader();
	
	reader.onload = function(evt){
		if(this.readyState != 2){
			return false;
		}
		
		var data = evt.target.result;
		var base64StartIndex = data.indexOf(',') + 1;
					
		$.ajax({
			type: "POST",
			url: makeUrl({module: 'photo', action: 'save_photo_string'}),
			dataType: "text",
			data: {photo_stream: data.substring(base64StartIndex), photo_name: files[0].name},
			success: function(data, textStatus, jqXHR){
				if(data != 1){
					data = data.split("|");
											
					window.location = SGL_JS_WEBROOT + '/index.php/photo/photo/action/admin/p/' + data[0] + '/a/' + data[1];
				} else {
					window.location = SGL_JS_WEBROOT;
				}
			},
			error: function(jqXHR, textStatus, errorThrown){
				window.location = SGL_JS_WEBROOT;
			}
		});
	}
	
	
	reader.readAsDataURL(files[0]);
}
