var startX,startY,endX,endY;
var selectionTop,selectionLeft,selectionBottom,selectionRight;
var ErrMsg = "The warehouse doesn't have sufficient stock to fulfill this request of items below. Please reduce your quantity:\n\n";
var NewErrMsg = '';
function checkRange(point,smallLimit,largeLimit){
	var returnValue = false;
	if (point >= smallLimit && point <= largeLimit){
		returnValue = true;
	}
	return returnValue;
}

function addSelection(obj){
	$(obj).addClass("selected");
}

function clearSelection(){
	$(".selectable").removeClass("selected");
}

function setSelection(){
	selectionTop = Math.min(startY,endY);
	selectionLeft = Math.min(startX,endX);
	selectionBottom = Math.max(startY,endY);
	selectionRight = Math.max(startX,endX);
	//Debug
	//appendOutput("output","selection:\ntop:" + selectionTop + "\nleft:" + selectionLeft + "\nbottom:" + selectionBottom + "\nright:" + selectionRight);
}

function checkSelection(){
	var localTop = $(this).offset().top;
	var localLeft = $(this).offset().left;
	var localBottom = $(this).offset().top + $(this).height();
	var localRight = $(this).offset().left + $(this).width();
	//Debug
	//appendOutput("output","local(" + this.id + "):\ntop:" + localTop + "\nleft:" + localLeft + "\nbottom:" + localBottom + "\nright:" + localRight);
	//Fully selected case
	if (localTop >= selectionTop && localLeft >= selectionLeft && localBottom <= selectionBottom && localRight <= selectionRight) {
		addSelection(this);
		return;
	}
	//Corner cases
	if ((checkRange(selectionTop,localTop,localBottom) || checkRange(selectionBottom,localTop,localBottom))
		&& (checkRange(selectionLeft,localLeft,localRight) || checkRange(selectionRight,localLeft,localRight))) {
		addSelection(this);
		return;
	}
	//Vertical border cases
	if ((checkRange(selectionLeft,localLeft,localRight) || checkRange(selectionRight,localLeft,localRight))
		&& selectionTop <= localTop && selectionBottom >= localBottom) {
		addSelection(this);
		return;
	}
	//Horizontal border cases
	if ((checkRange(selectionTop,localTop,localBottom) || checkRange(selectionBottom,localTop,localBottom))
		&& selectionLeft <= localLeft && selectionRight >= localRight) {
		addSelection(this);
		return;
	}
}

//Place selection rectangle
function placeSelectionRectangle(startX,startY){
	var obj = document.getElementById("selectionCanvas");
	$(obj).css("display","block").css("left",startX).css("top",startY).height(0).width(0);
}

//Size selection rectangle
function sizeSelectionRectangle(posX,posY){
	if (startX && startY) {
		var obj = document.getElementById("selectionCanvas");
		var selectionTop = Math.min(startY,posY);
		var selectionLeft = Math.min(startX,posX);
		var selectionHeight = Math.abs(startY-posY);
		var selectionWidth = Math.abs(startX-posX);
		//appendOutput("output","T : " + selectionTop + " L : " + selectionLeft + " H : " + selectionHeight + " W : " + selectionWidth);
		$(obj).css("top",selectionTop).css("left",selectionLeft).height(selectionHeight).width(selectionWidth);
	}
}

//Remove selection rectangle
function removeSelectionRectangle(){
	var obj = document.getElementById("selectionCanvas");
	$(obj).css("display","none").css("left",0).css("top",0).height(0).width(0);
}

function initialiseSelectionGrid(){
    //Null start and end points
    startX = null;
    startY = null;
    endX = null;
    endY = null;		
	//Disable selection on the container
	$("#selectcontainer").bind('selectstart', function(e){
        return false;
    });
	
	//Drag select start event
	$("#selectcontainer").bind("mousedown",function(e){
		clearSelection();
		if (e.button > 1) {return false};
		startX = e.pageX;
		startY = e.pageY;
		placeSelectionRectangle(startX,startY);
	});
	
	//Drag select end event
	$("#selectcontainer").add("#selectionCanvas").bind("mouseup",function(e){
		if (e.button > 1) {return false};
		endX = e.pageX;
		endY = e.pageY;
		removeSelectionRectangle();
		setSelection();
		$(".selectable").each(checkSelection);
	});
	
	$("#selectcontainer").bind("click",function(e){
		removeSelectionRectangle();
	});
	
	//Track mouse position
	$("#selectcontainer").bind("mousemove",function(e){
		var posX = e.pageX;
		var posY = e.pageY;
		sizeSelectionRectangle(posX,posY);
		//Debug
		//writeOutput("mousepos","X : " + posX + " Y : " + posY);
	});
	
	//Check for key presses
	$(".selectable").bind("keydown",function(e){
		//<ESC> key exit
		if(e.keyCode == 27){
			clearSelection();
		}
		//<ENTER> key save
		if(e.keyCode == 13){
			updateSelectionValues(this);
			clearSelection();
		}
		//<TAB> key save
		if(e.keyCode == 9){
			updateSelectionValues(this);
			clearSelection();
		}		
	});
	
	//Check for blur event save
	$(".selectable").bind("blur",function(e){
		//Debug
		//appendOutput("output","Blur Saving (Current Object Only)");
		saveSelectionValue(this,this.value)
		clearSelection();
	});
}

var QtyMsg = false;

//Wrapping function for <ENTER> key save
function updateSelectionValues(obj){
	NewErrMsg = '';
	QtyMsg = '';
	if ($(".selected").size() > 0){
		//Debug
		//appendOutput("output","Enter Saving (All Selected Objects)");
		$(".selected").each(function(){
			saveSelectionValue(this,obj.value);
		});
	}
	else {
		//Debug
		//appendOutput("output","Enter Saving (Current Object Only)");
		saveSelectionValue(obj,obj.value);
	}
	if(NewErrMsg != '')
	{
		alert(ErrMsg + NewErrMsg);	
	}

	if(QtyMsg == true)
	{
		document.getElementById('ErrMsg').innerHTML = "<font color=#ff0000>Your order Item(s) quantity exceeds the allowed limit as per your student number, please reduce quantities on any levels or if you still require those quantities, please proceed for order approval.</font>";
		alert('Your order Item(s) quantity exceeds the allowed limit as per your student number. Please reduce quantities on any levels or if you still require those quantities, please proceed for order approval.');		
	}
}

//The save function for individual selectable boxes
function saveSelectionValue(obj,value){
	//Debug
	//appendOutput("output","Saved: " + obj.id + " (" + value + ")");
	obj.value = value;
	var ObjID = obj.id;
	var ArrObjID = ObjID.split('_');
	var r = ArrObjID[1];
	var RC = ArrObjID[1] + '_' + ArrObjID[2];
	var OrderType = document.getElementById('txtOrderType').value;
	var StockID = document.getElementById('StockID_'+RC).value;
	var StockCount = document.getElementById('StockCount_'+RC).value;
	var StockDesc = document.getElementById('StockDesc_' + RC).value;
	var StockETADate = document.getElementById('StockETADate_' + RC).value;
	
	StockCount = eval(StockCount);
	
	//alert(obj.value);
	var Qty = 0;
	var EqQty = 0;
	
	if(obj.value == '')
	{
		obj.value = 0	
	}
	
	if (eval(obj.value) > StockCount) {

	    NewErrMsg = NewErrMsg + StockDesc;
	obj.value = '';
		
	    if (StockETADate.length > 0) {
	        NewErrMsg = NewErrMsg + " (ETA@KDC: " + StockETADate + ")";
	    }

	    NewErrMsg = NewErrMsg + '\n'
	    
//		obj.value = 0;
	}
	if(obj.value != '')
	{
		if (eval(obj.value) < StockCount)
		{
			var ColCount = document.getElementById("txtCol_"+r).value;
			var eqname = 'txtOrderItemQtyTotal_' + r + '_' + ColCount;
			var eq = document.getElementById(eqname);
			for (var k=1;k<ColCount;k++)
			{
				Qty = document.getElementById("txtOrderItemQty_" + r + '_' + k).value;
				if(Qty == '')
				{
					Qty = 0;	
				}
				EqQty = eval(EqQty) + eval(Qty);
			}
			
			var RowCount = document.getElementById('txtRow').value;
			var TotalValue = 0;
			var QtyAllowed = document.getElementById('txtAllowedQty').value;
			
			//alert(RowCount)
			for(var p=1;p<RowCount;p++)
			{
				for (var k=1;k<ColCount;k++)
				{
					if(document.getElementById("txtOrderItemQty_" + p + '_' + k) != null)
					{
						Qty = document.getElementById("txtOrderItemQty_" + p + '_' + k).value;
						if(Qty == '')
						{
							Qty = 0;	
						}
						TotalValue = eval(TotalValue) + eval(Qty);
					}
				}
			}
			
			//alert(TotalValue + " : " +  QtyAllowed);
			
			if (TotalValue > QtyAllowed)
			{
				QtyMsg = true;
				document.getElementById('GrandTotal').innerHTML = '<font color=#ff0000>' + TotalValue + '</font>';
				eq.value = EqQty; 
				SaveOrder(obj, StockID, OrderType, 0);
			}
			else
			{
				QtyMsg = false;
				document.getElementById('GrandTotal').innerHTML = TotalValue;
				eq.value = EqQty; 
				SaveOrder(obj, StockID, OrderType, 0);
			}
		}
	}
}