var drawingBoardWidth = 50;
var drawingBoardHeight = 100;
var planEditLoading = false;
var global_plan_id = 0;
var global_event_id = 0;

var fSelection = null;
var sSelection = null;

var fvector = null;
var svector = null;
var farb = null;

$(document).ready(function() {
	
	if(planEditLoading == false) {
		planEditLoading = true;
		
		global_plan_id = $('#plan_id').val();
		global_event_id = $('#event_id').val();
		
		if(doesElementExist('#plan')) {
			
			// load the dimensions
			drawingBoardWidth = $('#plan_width').val();
			drawingBoardHeight = $('#plan_height').val();
						
			// build the plan
			fireboxPlanEdit_init();
			
			// populate the areas
			getAreaList();
			
			// populate the tickets
			//getTicketList();
			
			// populate the options
			//getOptionList();
		}
		
		if(doesElementExist('#places')) {
					
			// list places
			getPlacesList();
			
			// populate the options
			getOptionList();
		}		
		
		plan_edit_area_add_form();
		plan_edit_ticket_add_form();
		
		if(doesElementExist('form#form-plan-label')) {
			
			// ajax and popup this form
			$('form#form-plan-label').dialog({
				modal: true, 
				title: 'Label',
				autoOpen: false,
				width: 576,
				height: 350,
				buttons: {
					"Save": function() {
					    // bind form using 'ajaxForm' 
						var options = { 
							success: formPlanLabel_Submited 
					    };
				    	$('form#form-plan-label').ajaxForm(options);
						$('form#form-plan-label').submit();
						$(this).dialog( "close" );
					},
					Cancel: function() {
						$(this).dialog( "close" );
					}
				}
			});
			
			// add the colour pickers
			farb = $.farbtastic('#label-colour-picker');
			farb.linkTo($('#label-fg-colour'));
			$('#label-fg-colour').focus(formPlanLabel_colour_focus);
			$('#label-bg-colour').focus(formPlanLabel_colour_focus);
		}
		
		if(doesElementExist('form#form-plan-option')) {
			planOptionInit();
		}
	}
});
		
function plan_edit_area_add_form() {
	
	if(doesElementExist('form#form-area-add')) {
		
	    // bind form using 'ajaxForm' 
		var options = { 
	        target: 'form#form-area-add',
			success: formAreaAdd_Submitted 
	    };
    	$('form#form-area-add').ajaxForm(options);
	}
}

function plan_edit_ticket_add_form() {
	
	if(doesElementExist('form#form-ticket-add')) {
		
	    // bind form using 'ajaxForm' 
		var options = { 
	        target: 'form#form-ticket-add',
			success: formTicketAdd_Submited, 
	    };
    	$('form#form-ticket-add').ajaxForm(options);
	}
}

function formPlanLabel_colour_focus() {
	
	// make the current colour picker
	farb.linkTo(this);
}

function formPlanLabel_Submited() {
	
	
	
	//$('form#form-plan-label').dialog( "open" );
	fireboxPlanEdit_init();
	fireboxPlanEdit_init();
}
	
function areaPlacesAlter_Click(area_id, direction) {

	// get the amount
	var amount = parseInt($('input#txtAmount_' + area_id.toString()).val());
	
	// validate
	if (amount > 0) {
		
		// create a path to ajax
		var ajax_path = u("/ajax/admin_places/alter/" + global_plan_id.toString() + "/"+ area_id.toString() + '/' + direction.toString() + '/' + amount.toString());
			
		// fire the ajax request
		$.ajax({
			type: 'POST',
			url: ajax_path,
			success: function(data) {
				getPlacesList();
			}
		});
	} else {
		alert('Please enter a positive number.');
	}
	
	return false;
}

function getSelectedTickets(addField) {
	
	var selection = '';
	
	// get all the items in the selection
	$('td.plan-edit-selection').each(function(index, value) {	
		selection += ' ' + $(value).attr('id');
	});
	
	// if no items are selected
	if(selection == '') {
		
		// could there be a single selection
		if(doesElementExist('td.plan-edit-selection-f')) {
		
			// yes add it to the selection
			var single = $('td.plan-edit-selection-f');
			single.addClass('plan-edit-selection');
			single.removeClass('plan-edit-selection-f');
			
			// run the function again
			return getSelectedTickets(addField);
		}
	}
	
	// add the field name
	if(addField == undefined) {
		selection = 'selection=' + selection;
	}
	
	return selection;
}

function applyAreas(area_id) {
	
	// grab all the selected elements
	var selection = getSelectedTickets();
	
	// create a path to ajax
	var ajax_path = u("/ajax/admin_area/apply/" + global_plan_id.toString() + "/"+ area_id.toString());
	
	// fire the ajax request
	$.ajax({
		type: 'POST',
		url: ajax_path,
		data: selection,
		success: function(data) {
			if(parseInt(data) !== NaN) {
				fireboxPlanEdit_init();
			}
			else {
				alert('error');
			}
		}
	});
	
	return false;
}

function applyTickets(ticket_id) {
	
	// grab all the selected elements
	var selection = getSelectedTickets();
	
	// create a path to ajax
	var ajax_path = u("/ajax/admin_ticket/apply/" + global_plan_id.toString() + "/"+ ticket_id.toString());
	
	// fire the ajax request
	$.ajax({
		type: 'POST',
		url: ajax_path,
		data: selection,
		success: function(data) {
			if(parseInt(data) !== NaN) {
				fireboxPlanEdit_init();
			}
			else {
				alert('error');
			}
		}
	});
	
	return false;
}

function getSelectedNodeString() {
	
	var selection = '';
	
	$('td.plan-edit-selection').each(function(index, value){
		
		if(selection != '') {
			selection += ' ';
		}
		
		selection += $(value).attr('id').split('_');
	});
	
	return selection;
}

function linkLabel_click() {

	// get the selected nodes
	num_selection = getSelectedNodeString();
	
	// validate
	if(num_selection.length == 0) {
		alert('Please select some seats.');
	}
	else {
		$('#label-nodes').val(num_selection);
				
		// open the form
		$('form#form-plan-label').dialog( "open" );
	}
}

function linkClear_click() {
	
	// grab all the selected elements
	var selection = getSelectedTickets();
		
	// create a path to ajax
	var ajax_path = u("/ajax/admin_plan/clear/" + global_plan_id.toString());
	
	// fire the ajax request
	$.ajax({
		type: 'POST',
		url: ajax_path,
		data: selection,
		success: function(data) {						
			// change the styles
			//$('.plan-edit-selection').removeClass('seat');
			//$('.plan-edit-selection').css('background-color', '#ffffff');
			
			fireboxPlanEdit_init();
		}
	});
}

function linkDelete_click() {

	var agree = confirm("Are you sure you want to delete?");
	if(agree) {
		return true ;
	} else {
		return false ;
	}
}

function formTicketAdd_Submited() {

	if(doesElementExist('#places')) {
		getPlacesList();
	}
	else {
		getTicketList();
	}
}

function getAreaList() {
	
	// create a path to ajax
	var ajax_path = u("/ajax/admin_area/getlist/" + global_event_id.toString());
	
	// prepear the target
	var elementName = '#areas';
	var target = $(elementName);
	target.empty();
	target.addClass('ajax-loading');
	
	// fire the ajax request
	$.ajax({
		url: ajax_path,
		success: function(data) {
			target.html(data);
			target.removeClass('ajax-loading');
			plan_edit_area_add_form();
		}
	});
	
	return false;
}

function getPlacesList() {

	// create a path to ajax
	var ajax_path = u("/ajax/admin_places/getlist/" + global_plan_id.toString());
	
	// prepear the target
	var elementName = '#places-list';
	var target = $(elementName);
	target.empty();
	target.addClass('ajax-loading');
	
	// fire the ajax request
	$.ajax({
		url: ajax_path,
		success: function(data) {
			target.html(data);
			target.removeClass('ajax-loading');
			plan_edit_ticket_add_form();
		}
	});
	
	return false;
}

/* refesh the ticket list */
function getTicketList() {
	
	// create a path to ajax
	var ajax_path = u("/ajax/admin_ticket/getlist/" + global_plan_id.toString());
	
	// prepear the target
	var elementName = '#tickets';
	var target = $(elementName);
	target.empty();
	target.addClass('ajax-loading');
	
	// fire the ajax request
	$.ajax({
		url: ajax_path,
		success: function(data) {
			target.html(data);
			target.removeClass('ajax-loading');
			
			// repopulate the option multi select
			planEditGetTickets();
			plan_edit_ticket_add_form();
		}
	});
		
	return false;
}

/* initialises the plan and builds the grid */
function fireboxPlanEdit_init() {
	
	var inject = '';
	
	element = $('#plan');
	//element.append('<table class="drawing-board" cellspacing="1px"></table');
	
	// create a path to ajax
	var ajax_path = u("/ajax/admin_plan/render/" + global_plan_id.toString());
	
	// clear the plan
	element.html('<img class="admin-plan-loader" src="/themes/admin/images/ajax-loader.gif"/>');

	// fire the ajax request
	$.ajax({
		type: 'POST',
		url: ajax_path,
		success: function(data) {
			if(parseInt(data) !== NaN) {
			
				element.empty();
			
				// render the drawing board
				element.append(data);
				
				// add the controls
				element.append('<div class="plan-edit-selector"></div>');
				
				// connect events 
				connectPlanEvents();
				
				// fix the width and make scrollable
				enhanceGrid();
				
				// set the width of the html because css is rubbish
				//var width = 16 * x;
				//$('.drawing-board').css('width', width + 'px');
			}
			else {
				alert('error');
			}
		}
	});
}

function connectPlanEvents() {
	
	$('.drawing-board td').bind('click', fireboxPlanEditSeat_click);
	$('.drawing-board td').bind('mouseover', seat_item_mouseover);
}

/* handler for seat hover */
function seat_item_mouseover() {
	
	var html = $(this).html();
	$('#node-indi-info').html(html);	
}

/* handler for seat clicking */
function fireboxPlanEditSeat_click(e) {
	
	if(sSelection != null) {
		fSelection = null;
		sSelection = null;
		
		$('.drawing-board td').removeClass('plan-edit-selection-f');
		$('.drawing-board td').removeClass('plan-edit-selection-s');
	}
	
	if(fSelection == null) {
		$('.drawing-board td').removeClass('plan-edit-selection');
		fSelection = e.currentTarget.id;
	}
	else {
		sSelection = e.currentTarget.id;
	}
	
	$("#" + fSelection).addClass('plan-edit-selection-f');
	$("#" + sSelection).addClass('plan-edit-selection-s');

	fireboxPlanEdit_hightlight();
} 

/* add a new area */
function planEditAddArea() {
	
	$('form#form-area-add').submit();
	
	return false;
}

/* add a new ticket type */
function planEditAddTicket() {
	
	$('form#form-ticket-add').submit();
	
	return false;
}

function formAreaAdd_Submitted() {
	
	if(doesElementExist('#places')) {
		getPlacesList();
	}
	else {
		getAreaList();
	}
}

/* highlights the selected seats */
function fireboxPlanEdit_hightlight() {
	
	if(sSelection && fSelection) {
		
		var svec = sSelection.split('_');
		var fvec = fSelection.split('_');
		
		svec[0] = parseInt(svec[0]);
		svec[1] = parseInt(svec[1]);
		fvec[0] = parseInt(fvec[0]);
		fvec[1] = parseInt(fvec[1]);
		
		var tlvec = [];
		var brvec = [];
		
		// create a top left vector
		if(fvec[0] < svec[0]) {
			tlvec[0] = fvec[0];
		} else {
			tlvec[0] = svec[0];
		}
		if(fvec[1] < svec[1]) {
			tlvec[1] = fvec[1];
		} else {
			tlvec[1] = svec[1];	
		}
		
		// create a bottom right vector
		if(fvec[0] > svec[0]) {
			brvec[0] = fvec[0];
		} else {
			brvec[0] = svec[0];
		}
		if(fvec[1] > svec[1]) {
			brvec[1] = fvec[1];
		} else {
			brvec[1] = svec[1];	
		}
		
		$('.plan-edit-selection').removeClass('plan-edit-selection');
		
		// make the selection
		for (x=tlvec[0]; x<=brvec[0]; x++) {
			for (y=tlvec[1]; y<=brvec[1]; y++) {
				$('#' + x + '_' + y).addClass('plan-edit-selection');
			}
		}
	}
	
}


