var booths;

var filteredBooths;

var randomImagePath;

var randomLogoPath;

var innerXCoordinate;
var innerYCoordinate;

var lastDraggedBoothIndex;

var currentPlan;

var boothsB4Change;
var tabs;


jQuery().ready(function(){
	
	$.ajaxSetup({
		cache:false
	});

	if($.query.get('admin')==1){
		showLoginModal();
	}
	else{	
		loadDefaultPlan();
	}
	
	$('#loginButton').click(function(){
		$.get('webservices/user.php', {
			action: 'login',
			userid: $('#loginIdTextBox').val(),
			password: $('#passwordTextBox').val()
		}, function(result) {
			if(result=='0'){
				alert('Wrong user id or password was entered');
			}
			else{
				hideLoginModal();
				
				$('#menu').css('visibility','visible');
				
				loadDefaultPlan();
			}
		});		
	});
	
	tabs = $("#tabs").tabs({ selected: 2 });
	
	//hide the edit booths menu item initially
	hideEdit();
	
	initTimeSelect();

	booths = new Array();

	$("#planDateTextBox").date_input();

	//Enable accordion functionality for the toolbar
	$("#navigation").accordion({ header: ".head",collapsible:true });

	 if ($.browser.msie) { 
	  $('li').css('zoom', '1'); 
	  $('a').css('zoom','1'); 
	 } 		
	
	//New Plan onclick event handler
	$('#newPlanMenuItem').click(function (e) {
		e.preventDefault();
		//Show New Plan Pop Up
		showNewPlanModal();
	});

	//Add Booth onclick event handler
	$('#addBoothMenuItem').click(function (e) {
		e.preventDefault();
		//Show New Plan Pop Up
		showAddBoothModal();
	});
	
	//Add Booth onclick event handler
	$('#editCategoryMenuItem').click(function (e) {
		e.preventDefault();
		//Show New Plan Pop Up
		showUpdateCategoryModal();
	});	
	
	//Remove Plan onclick event handler
	$('#deletePlanMenuItem').click(function (e) {
		e.preventDefault();
		
		if(confirm('The current plan will be removed. Do you wish to proceed?')){
			//Show New Plan Pop Up
			$.get('webservices/floor.php',{
				action:'remove',
				plan_id:currentPlan.plan_id
			},function(){
				alert("The Plan has been removed");
				
				currentPlan = null;
				
				hideEdit();
					
				restore();			
			});	
		}
	});		

	$('#newPlanSaveButton').click(function(){
		
		if(validateNewPlan()){
			$.getJSON('webservices/floor.php', {
				action: 'add',
				plan_url:randomImagePath,
				plan_description:$('#newPlanNameTextBox').val(),
				plan_date:$('#planDateTextBox').val(),
				start_time:$('#startTimeDropDownList').val(),
				end_time:$('#endTimeDropDownList').val()
			}, function(data) {
				currentPlan = data;
				
				// close the dialog
				hideNewPlanModal();

				showEdit();
				
				refreshMainWorkArea();

				loadNavigation();				
			});			
		}
	});

	$('#addBoothSaveButton').click(function(){
//		$.get('webservices/booth.php', {
//			action: 'backup',
//			plan_id:currentPlan.plan_id
//		}, function() {		
//			$.get('webservices/booth.php', {
//				action: 'remove',
//				plan_id:currentPlan.plan_id
//			}, function() {
//				refreshMainWorkArea();		
//		
//				loadNavigation();
//									
//				if(booths.length>0){
//					//saveBoothsToDB(0);
//					
//					
//				}
//			});
//
//			hideAddBoothModal();
//		});

		$.post('webservices/booth.php', {
			action: 'save',
			plan_id:currentPlan.plan_id,
			booths:$.toJSON(booths)
		}, function(data) {
			
			if(data!=''){
				alert(data);
			}
			else{
				refreshMainWorkArea();		
		
				loadNavigation();
				
				hideAddBoothModal();				
			}
		});
	});


	$('#addBoothDetailsSaveButton').click(function(){
		
		if(validateAddBooth()){
			
			boothsB4Change = null;
			
			var booth = booths[lastDraggedBoothIndex];
	
			booth.available = $('#addBoothAvailabilityDropDownList').val();
			
			booth.width = $('#addBoothWidthTextBox').val();
			booth.height = $('#addBoothHeightTextBox').val();
			booth.angle = $('#addBoothAngleTextBox').val();		
			booth.boothNo = $('#addBoothNumberTextBox').val();
			if(booth.available!="1"){			
				
				booth.businessName = $('#addBoothBusinessNameTextBox').val();
				if($('#addBoothWebAddressTextBox').val() != 'Website Address'){
					booth.web = $('#addBoothWebAddressTextBox').val();
				}
	
				if($('#addBoothAddressTextBox').val() != 'Address'){
					booth.address = $('#addBoothAddressTextBox').val();
				}
				
				if($('#addBoothProfileTextBox').val() != 'Profile'){
					booth.profile = $('#addBoothProfileTextBox').val();
				}
				
				if($('#addBoothPhoneTextBox').val() != 'Phone'){
					booth.phone = $('#addBoothPhoneTextBox').val();
				}
	
				if($('#addBoothFaxTextBox').val() != 'Fax'){
					booth.fax = $('#addBoothFaxTextBox').val();
				}
				
				if($('#addBoothEmailTextBox').val() != 'Email'){
					booth.email = $('#addBoothEmailTextBox').val();
				}
	
				booth.logo = randomLogoPath;
				
				var categories = new Array();
				
				$("#existingCategoriesSelectBox option").each(function () {
					
					var category = {
						category_id : $(this).val(),
						category_description : $(this).text()
					};
					
					categories.push(category);
			    });	
				
				booth.categories = categories;
								
			}
	
			booths[lastDraggedBoothIndex] = booth;		
			
			hideAddBoothDetailsModal();
	
			refreshAddBoothModal();
	
			enableDragDrop();
			
		}
	});
	
	$('#addBoothDetailsRemoveButton').click(function(){
		booths.splice(lastDraggedBoothIndex,1);		
			
		hideAddBoothDetailsModal();
	
		refreshAddBoothModal();
	
		enableDragDrop();		
	});	

	$('#addBoothAvailabilityDropDownList').change(function(){
		if($('#addBoothAvailabilityDropDownList').val()=="1"){
			switchAvailable();
		}
		else{
			switchOccupied();
		}
	});
	
	$('#updateCategoryCloseButton').click(function(){	
		hideUpdateCategoryModal();
	});
	
	$('#newPlanCloseButton').click(function(){	
		hideNewPlanModal();
	});	
	
	$('#loadPlanCloseButton').click(function(){	
		hideLoadPlanModal();
	});		
	
	$('#addBoothCloseButton').click(function(){	
		hideAddBoothModal();
	});			

	$('#addBoothDetailsCloseButton').click(function(){	
		hideAddBoothDetailsModal();
		
		loadBooths();
	});	
			
	
	$('#deleteCategoryButton').click(function(){
		if($('#updateCategoryDropDownList').val()=='Select Category'){
			alert('Category is required');
		}
		else{
			$.get('webservices/category.php', {
				action: 'remove',
				category_id:$('#updateCategoryDropDownList').val()
			}, function(data) {
				if(data!="cannot"){
					alert("Category removed");
				
					loadCategories();
				}
				else{
					alert("Category cannot be removed because of dependencies");
				}
			});			
		}
	});	
	

	$('#saveNewCategoryButton').click(function(){
		if($('#categoryNameTextBox').val()==''){
			alert('Category Name is required');
		}
		else{
			$.get('webservices/category.php', {
				action: 'add',
				category_name:$('#categoryNameTextBox').val()
			}, function() {
				alert("Category added");
				
				loadCategories();
			});			
		}
	});	

	$('#loadPlanMenuItem').click(function(){
		showLoadPlanModal();
		
		loadPlans();
	});	
	
	$('#loadPlanButton').click(function(){
		if($('#loadPlanDropDownList').val()=='Select Plan'){
			alert('Plan is required');
		}
		else{
			$.getJSON('webservices/floor.php', {
				action:'get',
				plan_id:$('#loadPlanDropDownList').val()
			}, function(data) {
				currentPlan = data;
				
				hideLoadPlanModal();
				
				refreshMainWorkArea();
				
				showEdit();
				
				loadNavigation();
			});			
		}
	});	
	
	$('#availableIcon').mousedown(function (e) {
		innerXCoordinate = e.pageX - $('#availableIcon').offset().left;
		innerYCoordinate = e.pageY - $('#availableIcon').offset().top;
	});

	$('#occupiedIcon').mousedown(function (e) {
		innerXCoordinate = e.pageX - $('#occupiedIcon').offset().left;
		innerYCoordinate = e.pageY - $('#occupiedIcon').offset().top;
	});	
	


});

function saveBoothsToDB(i){
	var booth = booths[i];	
	if(booth.available!="1"){		
		$.get('webservices/booth.php', {
			action: 'add',
			x:booth.x,
			y:booth.y,
			width:booth.width,
			height:booth.height,
			angle:booth.angle,
			available:'0',
			booth_no:booth.boothNo,
			company_name:booth.businessName,
			address:booth.address,
			phone:booth.phone,
			fax:booth.fax,
			email:booth.email,
			web:booth.web,
			profile:booth.profile,
			logo:booth.logo,			
			plan_id:currentPlan.plan_id
		}, function(data) {			
			
			if (data == "error") {
				$.get('webservices/booth.php', {
					action: 'restore',
					plan_id: currentPlan.plan_id
				}, function(){
					refreshMainWorkArea();
					
					loadNavigation();
					
					return;
				});
			}
			else {
				//save booth first
				//then categories
				$.get('webservices/category.php', {
					action: 'removeBoothCategory',
					booth_id: data
				}, function(){
					if (booth.categories) {
						for (var j = 0; j < booth.categories.length; j++) {
							$.get('webservices/category.php', {
								action: 'addBoothCategory',
								booth_id: data,
								category_id: booth.categories[j].category_id
							}, function(){
								
								if(j==booth.categories.length&&i==booths.length-1){
									refreshMainWorkArea();		
													
									loadNavigation();									
								}
											
							});
						}
					}
					
					
				});
				
			}

															
			if((i+1)<booths.length){
				saveBoothsToDB(i+1);
			}
			else{				
				refreshMainWorkArea();		
								
				loadNavigation();																
			}
										
							
		});
	}
	else{
		$.get('webservices/booth.php', {
			action: 'add',
			x:booth.x,
			y:booth.y,
			width:booth.width,
			height:booth.height,
			angle:booth.angle,
			available:"1",
			booth_no:booth.boothNo,
			plan_id:currentPlan.plan_id
		}, function() {
			if((i+1)<booths.length){
				saveBoothsToDB(i+1);
			}
			else{
				refreshMainWorkArea();		
	
				loadNavigation();								
			}
		});

	}

}

function restore(){
	booths = null;
	
	$('#workingArea').attr('src','images/blank.jpg');
	
	$('#boothOverlay').html('');
	
	$('.planDetails').css('display','none');
}

function loadDefaultPlan(){
	if($.query.get('plan')!=null&&$.query.get('plan')!=''){			
			$.getJSON('webservices/floor.php', {
				action:'get',
				plan_name:$.query.get('plan')
			}, function(data) {
				currentPlan = data;								
				
				hideLoadPlanModal();
				
				refreshMainWorkArea();
				
				showEdit();
				
				loadNavigation();
			});			
	}	
}

//show image upload popup
function showNewPlanModal() {
	initUpload();

	$("#newPlanNameTextBox").Watermark("Plan Name");
	$("#planDateTextBox").Watermark("Plan Date");

	$('#newPlanModal').center();
	$('#newPlanModal').css('display','block');
}

//hide image upload popup
function hideNewPlanModal() {
	$('#newPlanModal').css('display','none');
}

//show image upload popup
function showLoginModal() {
	$('#loginModal').center();
	$('#loginModal').css('display','block');
}

//hide image upload popup
function hideLoginModal() {
	$('#loginModal').css('display','none');
}

function validateNewPlan(){
	var isValid = true;

	if($('#newPlanNameTextBox').val()=='Plan Name'){
		alert('Plan name is required');

		isValid = false;
	}
	else if($('#uploadImageTextBox').val()==''){
		alert('A map is required');

		isValid = false;
	}
	else if($('#planDateTextBox').val()=='Plan Date'){
		alert('Plan Date is required');

		isValid = false;
	}
	else if($('#startTimeDropDownList').val()=='Start Date'){
		alert('Start Time is required');

		isValid = false;
	}
	else if($('#endTimeDropDownList').val()=='End Date'){
		alert('End Time is required');

		isValid = false;
	}

	return isValid;
}

function validateAddBooth(){	
	if($('#addBoothWidthTextBox').val()==''){
		alert('Width is required');

		return false;
	}
	else if($('#addBoothHeightTextBox').val()==''){
		alert('Height is required');

		return false;
	}
	else if($('#addBoothAngleTextBox').val()==''){
		alert('Angle is required');

		return false;
	}
	else if($('#addBoothNumberTextBox').val()=='Booth Number'){
		alert('Booth number is required');
	
		return false;
	}	
	
	if($("#addBoothAvailabilityDropDownList").val()=='0'){

		if($('#addBoothBusinessNameTextBox').val()=='Business Name'){
			alert('Business name is required');
	
			return false;
		}
	}
	return true;
}

//show add booth popup
function showAddBoothModal() {
	booths = new Array();

	enableDragDrop();

	$('#addBoothModal').center();
	$('#addBoothModal').css('display','block');

	$('#addBoothWorkArea').attr('src','uploads/'+currentPlan.plan_url);

	loadBooths();
}

//hide add booth popup
function hideAddBoothModal(){
	$('#addBoothModal').css('display','none');

	$('#addBoothOverlay').html('');
}

function refreshAddBoothModal(){
	var imgHtml = '';
	var boothNoHtml = '';
	
	for(var i=0;i<booths.length;i++){
		var booth = booths[i];

		var imgPath = 'webservices/image.php?';
			
		if(booth.hilight){
			imgPath += 'type=hilight';
		}
		else if(booth.available=="1"){
			imgPath += 'type=available';
		}
		else{
			imgPath += 'type=occupied';
		}
			
		imgPath += '&width='+booth.width;
		imgPath += '&height='+booth.height;
		imgPath += '&angle='+booth.angle;
		
		if(booth.boothNo){
			imgPath += '&booth_no='+booth.boothNo;
		}		
		
		imgHtml += '<img tag="'+i+'" class="booth" src=\"' + imgPath + '\" style=\"left:'+(parseInt(booth.x) + $('#addBoothWorkArea').offset().left)+'px;top:'+(parseInt(booth.y)+$('#addBoothWorkArea').offset().top)+'px;\"/>';
		
		if(booth.boothNo!=null){
			boothNoHtml += '<div tag=\"'+i+'\" class=\"addBoothBoothNo\">' + booth.boothNo + '</div>';
		}
	}
	
	$('#addBoothOverlay').html(imgHtml);	
		
	$('.booth').bind("mousedown", function (e) {
		innerXCoordinate = e.pageX - $(this).offset().left;		
		innerYCoordinate = e.pageY - $(this).offset().top;

	});	

	$('.booth').bind("mouseup", function (e) {
		lastDraggedBoothIndex = parseInt($(this).attr('tag'));		
		showAddBoothDetailsModal(booths[lastDraggedBoothIndex]);
	});		
}

//show add booth popup
function showAddBoothDetailsModal(booth) {					
	
	if(booth==null){
		
		randomLogoPath = null;
		
		$("#addBoothWidthTextBox").val('30');
		$("#addBoothHeightTextBox").val('24');
		$("#addBoothAngleTextBox").val('0');			
		$("#addBoothBusinessNameTextBox").val('');
		$("#addBoothWebAddressTextBox").val('');
		$("#addBoothAddressTextBox").val('');
		$("#addBoothPhoneTextBox").val('');
		$("#addBoothFaxTextBox").val('');
		$("#addBoothEmailTextBox").val('');
		$("#addBoothProfileTextBox").val('');		
		
	}
	else{
		
		randomLogoPath = booth.logo;
		
		$("#addBoothWidthTextBox").val(booth.width);
		$("#addBoothHeightTextBox").val(booth.height);
		$("#addBoothAngleTextBox").val(booth.angle);			
		$("#addBoothNumberTextBox").val(booth.boothNo);
		$("#addBoothBusinessNameTextBox").val(booth.businessName);
		
		if(booth.web){
			$("#addBoothWebAddressTextBox").val(booth.web);
		}
		else{
			$("#addBoothWebAddressTextBox").val('');
		}
		if(booth.address){
			$("#addBoothAddressTextBox").val(booth.address);
		}
		else{
			$("#addBoothAddressTextBox").val('');
		}
		if(booth.phone){
			$("#addBoothPhoneTextBox").val(booth.phone);
		}
		else{
			$("#addBoothPhoneTextBox").val('');
		}
		if(booth.fax){
			$("#addBoothFaxTextBox").val(booth.fax);
		}
		else{
			$("#addBoothFaxTextBox").val('');
		}
		if(booth.email){
			$("#addBoothEmailTextBox").val(booth.email);
		}
		else{
			$("#addBoothEmailTextBox").val('');
		}
		if(booth.profile){
			$("#addBoothProfileTextBox").val(booth.profile);		
		}
		else{
			$("#addBoothProfileTextBox").val('');		
		}

		$("#addBoothAvailabilityDropDownList").val(booth.available)	;
		
		if(booth.available=="1"){
			switchAvailable();				
		}
		else{
			switchOccupied();																	
		}				
	}
	
			
	//watermask textboxes
	$("#addBoothNumberTextBox").Watermark("Booth Number");
	$("#addBoothBusinessNameTextBox").Watermark("Business Name");
	$("#addBoothWebAddressTextBox").Watermark("Website Address");
	$("#addBoothAddressTextBox").Watermark("Address");
	$("#addBoothPhoneTextBox").Watermark("Phone");
	$("#addBoothFaxTextBox").Watermark("Fax");
	$("#addBoothEmailTextBox").Watermark("Email");
	$("#addBoothProfileTextBox").Watermark("Profile");
	$("#addBoothLogoUploadTextBox").Watermark("Logo");

	$('#addBoothDetailsModal').center();
	$('#addBoothDetailsModal').css('display','block');											
	
	loadCategorySelectBoxes(booth);
	
	$('#addCategoryButton').click(function (e){
		$("#existingCategoriesSelectBox option:selected").each(function () {
			$(this).remove().appendTo("#availableCategoriesSelectBox");
        });								
	});

	$('#removeCategoryButton').click(function (e){
		$("#availableCategoriesSelectBox option:selected").each(function () {
			$(this).remove().appendTo("#existingCategoriesSelectBox");
        });				
	});	
}

function hideAddBoothDetailsModal(){
	$('#addBoothDetailsModal').css('display','none');
}

function showUpdateCategoryModal(){
	loadCategories();
	
	$('#updateCategoryModal').center();
	$('#updateCategoryModal').css('display','block');
}

function loadCategorySelectBoxes(booth){
	if (booth != null) {

		var categories = booth.categories;
		
		var html = '';
		
		if (categories) {	
							
			for (var i = 0; i < categories.length; i++) {

				html += '<option value=\"' + categories[i].category_id + '\">' + categories[i].category_description + '</option>';

			}						
		}
		$('#existingCategoriesSelectBox').html(html);
	}
	else{
		$('#existingCategoriesSelectBox').html('');
	}
			
	$.getJSON('webservices/category.php', {
		action:'get'
	}, function(data) {	
		var categories = data;
	
		var html = '';
	
		for(var i=0;i<categories.length;i++){
			var isFound = false;			
			
			if (booth) {
				if (booth.categories) {
					for (var j = 0; j < booth.categories.length; j++) {
						if (categories[i].category_id == booth.categories[j].category_id) {
							isFound = true;
							break;
						}
					}
				}
			}
			
			if (!isFound) {			
				html += '<option value=\"'+categories[i].category_id+'\">'+categories[i].category_description+'</option>';			
			}			
		}
		
		$('#availableCategoriesSelectBox').html(html);
	});		
}

function hideUpdateCategoryModal(){
	$('#updateCategoryModal').css('display','none');
}

function initTimeSelect(){
	for(var hour=0;hour<24;hour++){
		for(var minute=0;minute<60;minute+=30){
			var entry = '<option>'+hour + ':' + (minute==0?'00':minute)+'</option>';
			$('#startTimeDropDownList').html($('#startTimeDropDownList').html()+entry);

			$('#endTimeDropDownList').html($('#endTimeDropDownList').html()+entry);
		}
	}
}

function initUpload(){
	//Upload button onclick event handler in "new plan" popup
	new Ajax_upload('#uploadImageButton', {
		action: 'upload.php',
		name: 'userfile',
		autoSubmit: true,
		onComplete : function(file,response){
			randomImagePath = response;
			
			$('#preview').html('<img src=\"uploads/'+randomImagePath+'\"></img>');
		},
		onSubmit : function(file , ext){
			if (! (ext && /^(jpg|png|jpeg)$/.test(ext))){
				alert('invalid file type');
				// cancel upload
				return false;
			}

			$('#uploadImageTextBox').val(file);
		}
	});
}

function initBoothLogoUpload(){
	
	new Ajax_upload('#addBoothLogoUploadButton', {
		action: 'upload.php',
		name: 'userfile',
		autoSubmit: true,
		onComplete : function(file,response){
			randomLogoPath = response;
			
			$('#addBoothDetailsSaveButton').attr("disabled", false);
			
			alert("upload complete") ;
		},
		onSubmit : function(file , ext){
			if (! (ext && /^(jpg|png|jpeg)$/.test(ext))){
				alert('invalid file type');
				// cancel upload
				return false;
			}
			
			$('#addBoothDetailsSaveButton').attr("disabled", true); 
		}
	});
}

function switchAvailable(){
	$('#addBoothAvailabilityDropDownList').val('1');

	$("#addBoothBusinessNameTextBox").attr({disabled:true});
	$("#addBoothWebAddressTextBox").attr({disabled:true});
	$("#addBoothAddressTextBox").attr({disabled:true});
	$("#addBoothPhoneTextBox").attr({disabled:true});
	$("#addBoothFaxTextBox").attr({disabled:true});
	$("#addBoothEmailTextBox").attr({disabled:true});
	$("#addBoothProfileTextBox").attr({disabled:true});
	$("#addCategoryButton").attr({disabled:true});
	$("#removeCategoryButton").attr({disabled:true});	
	
	
	
	
	
	$("#addBoothBusinessNameTextBox").val('');
	$("#addBoothWebAddressTextBox").val('');
	$("#addBoothAddressTextBox").val('');
	$("#addBoothPhoneTextBox").val('');
	$("#addBoothFaxTextBox").val('');
	$("#addBoothEmailTextBox").val('');
	$("#addBoothProfileTextBox").val('');

	$("#addBoothNumberTextBox").Watermark("Booth Number");
	$("#addBoothBusinessNameTextBox").Watermark("Business Name");
	$("#addBoothWebAddressTextBox").Watermark("Website Address");
	$("#addBoothAddressTextBox").Watermark("Address");
	$("#addBoothPhoneTextBox").Watermark("Phone");
	$("#addBoothFaxTextBox").Watermark("Fax");
	$("#addBoothEmailTextBox").Watermark("Email");
	$("#addBoothProfileTextBox").Watermark("Profile");
	
	$("#addBoothLogoUploadButton").css("display","none");
}

function switchOccupied(){
	$('#addBoothAvailabilityDropDownList').val('0');

	$("#addBoothBusinessNameTextBox").attr({disabled:false});
	$("#addBoothWebAddressTextBox").attr({disabled:false});
	$("#addBoothAddressTextBox").attr({disabled:false});
	$("#addBoothPhoneTextBox").attr({disabled:false});
	$("#addBoothFaxTextBox").attr({disabled:false});
	$("#addBoothEmailTextBox").attr({disabled:false});
	$("#addBoothProfileTextBox").attr({disabled:false});
	$("#addCategoryButton").attr({disabled:false});
	$("#removeCategoryButton").attr({disabled:false});		
	
	
	$("#addBoothLogoUploadButton").css("display","block");
	
	initBoothLogoUpload();
}

function loadBoothCategories(){
		$.getJSON('webservices/category.php', {
			action: 'getExisting'				
		}, function(data){																																
			var categories = data;
			
			for(var i=0;i<booths.length;i++){
				for(var j=0;j<categories.length;j++){
					if(categories[j].booth_id == booths[i].booth_id){						
						if(!booths[i].categories){
							booths[i].categories = new Array();
						}
						booths[i].categories.push({category_id:categories[j].category_id,
									 		  category_description:categories[j].category_description});
					}
				}				
			}
				
			refreshAddBoothModal();
					
			enableDragDrop();																													
		});			
}

function loadBooths(){	
	if (boothsB4Change) {		
		
		booths = cloneObj(boothsB4Change);
			
		boothsB4Change = null;
		
		refreshAddBoothModal();
					
		enableDragDrop();	
	}
	else {
		$.getJSON('webservices/booth.php', {
			action: 'get',
			plan_id: currentPlan.plan_id
		}, function(data){
			booths = data;
			
			loadBoothCategories();
		});
	}	
}

function loadCategories(){
	$.getJSON('webservices/category.php', {
		action:'get'
	}, function(data) {
		
		var categories = data;
		
		var html = '<option>Select Category</option>';
		
		for(var i=0;i<categories.length;i++){
			html += '<option value=\"'+categories[i].category_id+'\">'+categories[i].category_description+'</option>';
		}
		
		$('#updateCategoryDropDownList').html(html);		
	});		
}


function loadPlans(){
	$.getJSON('webservices/floor.php', {
		action:'get'
	}, function(data) {
		
		var plans = data;
		
		var html = '<option>Select Plan</option>';
		
		for(var i=0;i<plans.length;i++){
			html += '<option value=\"'+plans[i].plan_id+'\">'+plans[i].plan_description+'</option>';
		}
		
		$('#loadPlanDropDownList').html(html);		
	});		
}

function enableDragDrop(){
	$('#availableIcon').draggable({helper: 'clone'});	
	$('#occupiedIcon').draggable({helper: 'clone'});
	$('.booth').draggable();
	$("#addBoothWorkArea").droppable({
		accept: "*",
		drop: function(ev, ui) {
				
								
			
			var x = ev.pageX - $('#addBoothWorkArea').offset().left - innerXCoordinate;
			var y = ev.pageY - $('#addBoothWorkArea').offset().top - innerYCoordinate;
			if(ui.draggable.attr('id')=='availableIcon'
			||ui.draggable.attr('id')=='occupiedIcon'){
				
				boothsB4Change = cloneObj(booths);		
								
				booths.push({
					x:x,
					y:y,
					width:30,
					height:24,
					angle:0,
					available:(ui.draggable.attr('id')=='availableIcon'?"1":"0")
				});
					
				
					
				lastDraggedBoothIndex = booths.length-1;

				refreshAddBoothModal();

				if(ui.draggable.attr('id')=='availableIcon'){
					switchAvailable();
				}
				else{
					switchOccupied();
				}

				showAddBoothDetailsModal(null);
			}
			else{
				
				boothsB4Change = cloneObj(booths);	
			
				lastDraggedBoothIndex = parseInt(ui.draggable.attr('tag'));				
				
				booths[lastDraggedBoothIndex].x = x;
				booths[lastDraggedBoothIndex].y = y;
				
				refreshAddBoothModal();
				
				showAddBoothDetailsModal(booths[lastDraggedBoothIndex]);
			}
		}
	});
}

function hideEdit(){
	$('#editBoothsWrap').css('display','none');
	$('#deletePlanWrap').css('display','none');	
	$('#navigation').css('display','none');
}

function showEdit(){
	$('#editBoothsWrap').css('display','block');
	$('#deletePlanWrap').css('display','block');
	
	$('#navigation').css('display','');	
	$('#navigation ul').css('height','200px');
}

function showLoadPlanModal(){			
	$('#loadPlanModal').center();
	$('#loadPlanModal').css('display','block');	
}

function hideLoadPlanModal(){
	$('#loadPlanModal').css('display','none');
}

function showViewBoothDetailsModal(){			
	$('#viewBoothDetails').center();
	$('#viewBoothDetails').css('display','block');	
	
	tabs.tabs('select', 2); 
}

function hideViewBoothDetailsModal(){
	$('#viewBoothDetails').css('display','none');
}

function refreshMainWorkArea(){	
	$('#workingArea').attr({src:'uploads/'+currentPlan.plan_url});
	if($.browser.msie){
		$('.planDetails').css('display','block');
	}
	else{
		$('.planDetails').css('display','table');
	}
	
	$('#descWrap').html('Floor Plan: '+currentPlan.plan_description);
	$('#timeWrap').html('Time: ' + currentPlan.start_time + ' ' + currentPlan.end_time);
	$('#dateWrap').html('Date: ' + currentPlan.plan_date);
	
	var mainBooths;
	
	$.getJSON('webservices/booth.php', {
		action:'get',
		plan_id:currentPlan.plan_id
	}, function(data) {
		mainBooths = data;

		$.getJSON('webservices/category.php', {
			action: 'getExisting'				
		}, function(data){																																
			var categories = data;
			
			for(var i=0;i<mainBooths.length;i++){
				for(var j=0;j<categories.length;j++){
					if(categories[j].booth_id == mainBooths[i].booth_id){						
						if(mainBooths[i].categories==null){
							mainBooths[i].categories = new Array();
						}
						mainBooths[i].categories.push({category_id:categories[j].category_id,
									 		  category_description:categories[j].category_description});
					}
				}				
			}
		});
	
		var imgHtml = '';
		
		var boothNoHtml = '';
		
		if(filteredBooths){			
			for(var i=0;i<mainBooths.length;i++){
				for(var j=0;j<filteredBooths.length;j++){
					if(mainBooths[i].booth_id == filteredBooths[j].booth_id){
						mainBooths[i].hilight = true;							
					}
				}
			}
		}
		
		

		for(var i=0;i<mainBooths.length;i++){
			var booth = mainBooths[i];				
			
			var imgPath = 'webservices/image.php?';
			
			if(booth.hilight){
				imgPath += 'type=hilight';
			}
			else if(booth.available=="1"){
				imgPath += 'type=available';
			}
			else{
				imgPath += 'type=occupied';
			}
			
			imgPath += '&width='+booth.width;
			imgPath += '&height='+booth.height;
			imgPath += '&angle='+booth.angle;
			
			if (booth.boothNo) {
				imgPath += '&booth_no=' + booth.boothNo;
			}
			
			imgHtml += '<img tag=\"'+i+'\" title="' + booth.boothNo + ' - ' + (booth.businessName?booth.businessName:'') + '" class=\"nondraggable' + '\" src=\"' + imgPath + '\"/>';
			
			boothNoHtml += '<div tag=\"'+i+'\" title="' + booth.boothNo + ' - ' + (booth.businessName?booth.businessName:'') + '" class=\"mainBoothNos\">' + booth.boothNo + '</div>';
		}
		
		
	
		$('#boothOverlay').html(imgHtml);			

		
		$('.nondraggable').each(function(){
			var index = $(this).attr('tag');
			
			var booth = mainBooths[index];
			
			$(this).css('left',(parseInt(booth.x) + $('#workingArea').offset().left)+'px');
			$(this).css('top',(parseInt(booth.y)  +$('#workingArea').offset().top)+'px');

		});
		
		$(".nondraggable").tooltip({
			track: true,
			delay: 0,
			showURL: false,
			fixPNG: true,
			showBody: " - ",
			extraClass: "pretty fancy",
			top: -75,
			left: -40
		});
		
		$(".mainBoothNos").tooltip({
			track: true,
			delay: 0,
			showURL: false,
			fixPNG: true,
			showBody: " - ",
			extraClass: "pretty fancy",
			top: -75,
			left: -40
		});		
		
		$(".nondraggable,.mainBoothNos").click(function (e) {
			var booth = mainBooths[$(this).attr("tag")];
		
			filteredBooths= new Array();
			
			filteredBooths.push(booth);
			
			refreshMainWorkArea();			
							
			bindViewBooth(booth);
		});
		
		$("#viewBoothDetailsCloseBtn").click(function (e) {
			hideViewBoothDetailsModal();
			
			
		});
	});	
}

function bindViewBooth(booth){
	if (booth.available != "1") {
		showViewBoothDetailsModal();				if (booth.businessName != null) {			$('#viewBoothDetailsName').html(booth.businessName);			$('#viewBoothDetailsTitle').html(booth.businessName);		
		} else {
			$('#viewBoothDetailsName').html('');			$('#viewBoothDetailsTitle').html('');
		}						
		if(booth.address != null){
			$('#viewBoothDetailsAddress').html(booth.address);
		}
		else {
			$('#viewBoothDetailsAddress').html('');
		}
				
		if (booth.phone != null) {
			$('#viewBoothDetailsPhone').html("P: " + booth.phone);
		}
		else {
			$('#viewBoothDetailsPhone').html("");
		}
		
		if (booth.fax != null) {
			$('#viewBoothDetailsFax').html("F: "+booth.fax);
		}
		else {
			$('#viewBoothDetailsFax').html("");
		}
		
		if (booth.email != null) {
			$('#viewBoothDetailsEmail').html("<a href=\"mailto:" + booth.email + "\">" + booth.email + "</a>");
		}
		else {
			$('#viewBoothDetailsEmail').html("");
		}
		
		if (booth.web != null) {
			$('#viewBoothDetailsWeb').html("<a href=\"http://" + booth.web + "\" target=\"_blank\">" + booth.web + "</a>");
		}
		else {
			$('#viewBoothDetailsWeb').html("");
		}
		
		if (booth.profile != null) {			
			$('#viewBoothDetailsProfile').html(booth.profile.replace(/\n/g, "<br />"));
			
		}
		else {
			$('#viewBoothDetailsProfile').html("");
		}
		
		if (booth.logo != null) {
			$('#viewBoothDetailsLogo').html('<img src=\"uploads/' + booth.logo + '\"></img>');
		}
		else {
			$('#viewBoothDetailsLogo').html("");
		}				
		
		var html='';
		
		if (booth.categories) {
			for (var i = 0; i < booth.categories.length; i++) {
				html += '<li>' + booth.categories[i].category_description + '</li>';
			}
		}
		
		$('#boothCategories').html(html);
	}
}

function loadNavigation(){
	$('#searchTextBox').Watermark('Type an Exhibitor Name');				
	
	$.getJSON('webservices/booth.php', {
		action:'getCompanies',
		plan_id:currentPlan.plan_id
	}, function(data) {		
		var exhibitors = data;
		var html="";
		
		for(var i=0;i<exhibitors.length;i++){
			html+="<li>"+exhibitors[i].company_name+"</li>";
		}
		
		$('#exhibitorListWrap').html(html);
		
		$("#exhibitorListWrap li").mouseover(function() {
			
			//filter by business name
			$.getJSON('webservices/booth.php', {
				action:'search',
				plan_id:currentPlan.plan_id,
				businessName:$(this).text()
			}, function(data) {			    
				filteredBooths = data;
				
				refreshMainWorkArea();
			});	
		});		
	});

	$.getJSON('webservices/booth.php', {
		action:'getAvailable',
		plan_id:currentPlan.plan_id
	}, function(data) {		
		var availableBooths = data;
		var html="";
		
		for(var i=0;i<availableBooths.length;i++){
			html+="<li>"+availableBooths[i].boothNo+"</li>";
		}
		
		$('#availableBoothsWrap').html(html);
		
		$("#availableBoothsWrap li").mouseover(function() {
			//filter by booth no
			$.getJSON('webservices/booth.php', {
				action:'search',
				plan_id:currentPlan.plan_id,
				boothNo:$(this).html()
			}, function(data) {			    
				filteredBooths = data;
				
				refreshMainWorkArea();
			});	
		});				
	});
	
	$.getJSON('webservices/booth.php', {
		action:'get',
		plan_id:currentPlan.plan_id
	}, function(data) {		
		var allBooths = data;
		var html="";
			
		for(var i=0;i<allBooths.length;i++){
			var txt = allBooths[i].boothNo;
			
			if(allBooths[i].available=="0"){
				txt += " - " + allBooths[i].businessName;
			}
			
			html+="<li tag=\"" + allBooths[i].boothNo + "\">"+txt+"</li>";
		}
			
		$('#boothNumberListWrap').html(html);	
		
		$("#boothNumberListWrap li").mouseover(function() {
			//filter by booth no
			$.getJSON('webservices/booth.php', {
				action:'search',
				plan_id:currentPlan.plan_id,
				boothNo:$(this).attr("tag")
			}, function(data) {			    
				filteredBooths = data;
				
				refreshMainWorkArea();
			});	
		});				
	});	
	
	$.getJSON('webservices/category.php', {
		action:'getAllocated',
		plan_id:currentPlan.plan_id
	}, function(data) {
			
		var categories = data;
		
		$.getJSON('webservices/booth.php', {
			action:'get',
			plan_id:currentPlan.plan_id
		}, function(data) {			
			var allBooths = data;
			
			$.getJSON('webservices/category.php', {
				action: 'getExisting'				
			}, function(data){																																
				var boothCategories = data;				
				
				for(var i=0;i<allBooths.length;i++){
					for(var j=0;j<boothCategories.length;j++){
						if(boothCategories[j].booth_id == allBooths[i].booth_id){						
							if(!allBooths[i].categories){
								allBooths[i].categories = new Array();
							}
							allBooths[i].categories.push({category_id:boothCategories[j].category_id,
										 		  		  category_description:boothCategories[j].category_description});
							
						}
					}				
				}
				

				var html='<li>'+
							'<ul id="submenu">';
		
				for(var i=0;i<categories.length;i++){
					html+='<li>'+
						     '<a class="submenu" href="">' + categories[i].category_description + '</a>'+
							 	'<ul>';
					
									for(var j=0;j<allBooths.length;j++){						
										if(allBooths[j].categories){							
											for(var k=0;k<allBooths[j].categories.length;k++){																
												if(allBooths[j].categories[k].category_id == categories[i].category_id){
														
													var txt = allBooths[j].boothNo;
													
													if(allBooths[j].available=="0"){
														txt += " - " + allBooths[j].businessName;
													}
													
													html+="<li class=\"booth-menu-item\" tag=\"" + allBooths[j].boothNo + "\">"+txt+"</li>";																						
												}
											}
										}
									}
																		
					html+=		'</ul>'+
						  '</li>';
				}		
							
				html+=		'</ul>'+
						'</li>';	
						
				$('#categoryListWrap').html(html);
				
				$("#submenu").accordion({header: ".submenu", collapsible:true, alwaysOpen:false});
				
				$(".booth-menu-item").click(function(){					
					
					var booth;
					
					for(var i=0;i<allBooths.length;i++){
						if(allBooths[i].boothNo==$(this).attr("tag")){
							var booth = allBooths[i];		
						}
					}
					
					filteredBooths= new Array();
					
					filteredBooths.push(booth);
					
					refreshMainWorkArea();						
					
					bindViewBooth(booth);
				});	
				
				$(".submenu").mouseover(function(){					
					
					filteredBooths= new Array();
					
					for(var i=0;i<allBooths.length;i++){
						if(allBooths[i].categories){
							for(var j=0;j<allBooths[i].categories.length;j++){
								if(allBooths[i].categories[j].category_description == $(this).text()){
									filteredBooths.push(allBooths[i]);
								}
							}
						}						
					}
					
					refreshMainWorkArea();						
				});
				
				$(".booth-menu-item").mouseover(function(){					
					
					var booth;
					
					for(var i=0;i<allBooths.length;i++){
						if(allBooths[i].boothNo==$(this).attr("tag")){
							var booth = allBooths[i];		
						}
					}
					
					filteredBooths= new Array();
					
					filteredBooths.push(booth);
					
					refreshMainWorkArea();						
				});							
																											
			});						
		});
				
		$("#categoryListWrap li").mouseover(function() {
			//filter by category
			$.getJSON('webservices/booth.php', {
				action:'search',
				plan_id:currentPlan.plan_id,
				category:$(this).html()
			}, function(data) {
										    
				filteredBooths = data;
				
				refreshMainWorkArea();
			});	
		});

		hookSearch();
		
		$('#navigation ul').css('overflow','auto');				
	});			
}

function hookSearch(){
	$("#searchBtn").click(function() {
		
		//filter by approx business name
		$.getJSON('webservices/booth.php', {
			action:'search',
			plan_id:currentPlan.plan_id,
			approxName:$('#searchTextBox').val()
		}, function(data) {
			
			var html = 
				'<table>'+
					'<tr>'+
						'<td>'+
							'<img src="images/search_icon.jpg"/>'+
						'</td>'+
						'<td>'+
							'<div class="searchBox">'+
								'<input type="text" id="searchTextBox"/>'+
							'</div>'+
						'</td>'+
					'</tr>'+
					'<tr>'+
						'<td colspan="2" style="text-align:right;padding-right:3px;">'+
							'<img id="searchBtn" src="images/search_btn.jpg"/>'+
						'</td>'+
					'</tr>'+						
				'</table>';						
				
			for(var i=0;i<data.length;i++){
				var text = data[i].boothNo;
				
				if(data[i].available=="0"){
					text += ' - ' + data[i].businessName;
				}
				
				html+='<li tag=\"' + data[i].boothNo + '\">' + text + '</li>';
			}						
			
			$('#SearchWrap').html(html);
			
			hookSearch();				
						    
			filteredBooths = data;
			
			refreshMainWorkArea();
			
			$("#SearchWrap li").mouseover(function() {
				//filter by booth no
				$.getJSON('webservices/booth.php', {
					action:'search',
					plan_id:currentPlan.plan_id,
					boothNo:$(this).attr("tag")
				}, function(data) {			    
					filteredBooths = data;
					
					refreshMainWorkArea();
				});	
			});				
		});	
	});		
}

function cloneObj(obj){
    if(obj == null || typeof(obj) != 'object')
        return obj;

    var temp = new obj.constructor(); // changed (twice)
    for(var key in obj)
        temp[key] = cloneObj(obj[key]);

    return temp;
}

