var allowedKeys;
var myKeyOptions;
var usedOptions = new Array();
var dateOptions = new Array('Date created', 'Date due', 'Date completed', 'Post Date', 'Entry Date');
var personOptions = new Array('Person Name', 'Post Author', 'Completed by', 'Entered by');

function rep_wiz_init(){	
	
	$('.date-picker').datepicker({
    showOn: 'button',
    buttonImage: 'images/calendar.gif',
    buttonImageOnly: true    
	});

	$.getJSON("index.php/user/getAllowedKeys", function(data) {
		allowedKeys = data;	
	});

//	$('input[name=emails]').keyup(email_suggest);

	$(".color_disp#color0").addClass("color_disp_selected");

	$(".color_disp").click(function() {
		$(".color_disp").removeClass("color_disp_selected");
		$(this).addClass("color_disp_selected");
		var id = $(this).attr("id");
		var code = id.replace(/color/, '');
		$("input[name=color_code]").val(code);
	});

	
	$("input[name=project_name]").autocomplete({ source: projects});
	$("input[name=person_name]").autocomplete({ source: persons});
	$("input[name=client_name]").autocomplete({ source: clients});
	//$("input[name=emails]").autocomplete({ source: getEmailids});
	
	function split(val) {
		return val.split(/,\s*/);
	}
	function extractLast(term) {
		return split(term).pop();
	}
	
	$("input[name=emails]").autocomplete({
		minLength: 0,
		source: function(request, response) {
			// delegate back to autocomplete, but extract the last term
			response($.ui.autocomplete.filter(getEmailids, extractLast(request.term)));
		},
		focus: function() {
			// prevent value inserted on focus
			return false;
		},
		select: function(event, ui) {
			var terms = split( this.value );
			
			// remove the current input
			terms.pop();
			// add the selected item
			terms.push( ui.item.value );
			// add placeholder to get the comma-and-space at the end
			terms.push("");
			this.value = terms.join(", ");
			addRecipient(ui.item.value);
			return false;
		}
	});
	//var mailid=$("input[name=emails]").val();
	//alert(mailid);
	//email_suggest(mailid);
	/*$(".button").hover(
		function() {
			$(this).addClass("button_hover");
		},
		function() {
			$(this).removeClass("button_hover");
		}
	);*/
	
	// add button effect
	$(".button").button();
	$("#rep-wiz-submit span").attr("id","submit-span");
	$("#cancel span").attr("id","cancel-span");
	
	//on change handler for report type select
	$("select[name=report_type]").change(init_keys);
	
	//on change handler for key selects
	$("select[name=key_1], select[name=key_2], select[name=key_3]").change(show_value_selector, this); 	

	var report_id = $('input[name=report_id]').val();	
	if (report_id) {
		$('.key_selectors, .value_selectors, .expansions, #colors').hide();			
		$('#heading').text("Edit Report");
		$('#cancel').show();

		var mySelection = $('select[name=report_type]').val();	
		usedOptions = new Array();
		myKeyOptions = allowedKeys[mySelection];	
		
		var key1 = $('input[name=report_key1]').val();
		var key2 = $('input[name=report_key2]').val();
		var key3 = $('input[name=report_key3]').val();

		//assign key values
		if (key1) {
			show_key_selector('key_1');
			$('select[name=key_1]').val(key1);
		}
		if (key2) {
			show_key_selector('key_2');
			$('select[name=key_2]').val(key2);
		}
		if (key3) {
			show_key_selector('key_3');
			$('select[name=key_3]').val(key3);
		}
				
		resetUsedOptions();		

		//
		$('select[name=key_1], select[name=key_2], select[name=key_3]')
		.filter(function() {
			return $(this).val() != 'Select:';
		})		
		.each(show_value_selector);
			

		$('#rep_saviour').show();
		var dispatch = $('input[name=report_dispatch]').val();
		if (dispatch != 0)
			$('#pref_saviour').show();	
		else
			$('#pref_saviour').hide();
		var color_code = $('input[name=color_code]').val();				
		if (color_code != 0) {
			$('#colors').show();
			$('input[name=set_color]').attr('checked', true);
			$(".color_disp").removeClass("color_disp_selected");
			$(".color_disp#color" + color_code).addClass("color_disp_selected");	
		}	
		else
			$('#colors').hide();		
	}
	else {
		$('.key_selectors, .value_selectors, .expansions, #colors, #cancel').hide();
		$('.show_filter').attr('disabled', true);
	}

	$('.show_filter').click(function() {
		if ($(this).attr('checked') == true) {
			mySelectName = $(this).parents('.opener:first').nextAll('.wrapper:first').find('select:first').attr('name');
			show_key_selector(mySelectName);
			$(this).parents('.opener:first').nextAll('div.wrapper:first').children('div.key_selectors:first').show();
		}
		else {
			//reset the values inside the div so that they would not be used, also hide them
			mySelect = $(this).parents('.opener:first').nextAll('.wrapper:first').find('select:first');
			mySelect.val('Select:');
			cleanupSelections(mySelect);
			$(this).parents('.opener:first').nextAll('div.wrapper:first').children('div.key_selectors:first').hide();

		}
		correctShadows();			
	});

	$(".chkbox").not('.show_filter').click(function() {
		if ($(this).attr('checked') == true) 
			$(this).parents('.opener:first').nextAll('div.expansions:first').show();
		else 
			$(this).parents('.opener:first').nextAll('div.expansions:first').hide();
			
		// cascaded action on save report element 	
		if ($(this).is('[name=set_dispatch]')) {			
			if($(this).attr('checked') == true) {
			  $('[name=save_rep]').attr('checked','checked'); 
				$('#rep_saviour').parents('.expansions').show();
			}	
			else {
			  $('[name=save_rep]').removeAttr('checked');
				$('#rep_saviour').parents('.expansions').hide();
			}	
		}
		correctShadows();

	});

	correctShadows();		
}
	
function init_keys() {
	var mySelection = $('select[name=report_type]').val();	
	usedOptions = new Array();
	myKeyOptions = allowedKeys[mySelection];
		
	if (myKeyOptions) {		
		if (myKeyOptions.length > 1) {//there are many filters/keys for the report type
			show_key_selector('key_1');
			$('.show_filter').removeAttr('disabled');			
			$('.value_selectors').hide();
		}				
		else { ////there is only one filter/key for this report type
			var myKey = allowedKeys[mySelection][0];				
			if (myKey == 'Project Name') {
				$('.value_selectors').hide();
				$('#proj_selector').show();	
			}	
			else if (myKey == 'Person Name') {
				$('.value_selectors').hide();
				$('#person_selector').show();	
			}
			else if (myKey == 'Client Name') {
				$('.value_selectors').hide();
				$('#client_selector').show();
			}
			else if (exists_in_array(['Date created', 'Date due', 'Date completed'], myKey)) {
				$('.value_selectors').hide();
				$('#date_selector').show();
			}
		}
	}	
	else {
		$('.key_selectors, .value_selectors').hide();
		$('.show_filter').attr('disabled', true);
	}

	
	//resetting all selects, checkboxes and textboxes
	$('select').not('[name=report_type]').children('option:first-child').each(function() {
		$(this).attr('selected', true);
	});
	
	$(':checkbox').each(function() {
		$(this).attr('checked', false);
	});

	$(':text').each(function() {
		$(this).val('');
	});	

	//hiding spl prefs, since this is the beginning
		$('.expansions, #colors').hide();

	correctShadows();
}

function show_key_selector(keyName) {
	key_select = $('[name=' + keyName + ']');
	key_select.empty();
	key_select.append("<option value='Select:'>Select:</option>");
	var x;
	for (x in myKeyOptions) {
		if (exists_in_array(dateOptions, myKeyOptions[x]))
			keyOption = 'dateOptions'; 
		else if (exists_in_array(personOptions, myKeyOptions[x]))
			keyOption = 'personOptions';
		else 
			keyOption = myKeyOptions[x];
		if(!exists_in_array(usedOptions, keyOption))
			key_select
			.append("<option value='" + myKeyOptions[x] + "'>" + myKeyOptions[x] + "</option>"); 			
	}			
	$(key_select).parents('div.key_selectors:first').show();
}

function show_value_selector() {
	//cleanup earlier entered values
	cleanupSelections(this);

	var mySelection = $(this).val();
	if (exists_in_array(dateOptions, mySelection))
		usedOptions.push('dateOptions');//just push a str indicating date type
	else if (exists_in_array(personOptions, mySelection))
		usedOptions.push('personOptions');//just push a string indicating person type
	else
		usedOptions.push(mySelection);
	

	switch (mySelection) {	
		case 'Person Name':
		case 'Post Author':
		case 'Completed by':
		case 'Entered by':
			$(this).parents('div:first').after($('#person_selector'));
			$('#person_selector').show();
			break;		
		case 'Project Name':
			$(this).parents('div:first').after($('#proj_selector'));
			$('#proj_selector').show();
			break;
		case 'Client Name':
			$(this).parents('div:first').after($('#client_selector'));
			$('#client_selector').show();
			break;
		case 'Date created':
		case 'Date due':
		case 'Date completed':
		case 'Post Date':
		case 'Entry Date':
			$(this).parents('div:first').after($('#date_selector'));
			$('#date_selector').show();
			break;		
		case 'Completion Status':
			$(this).parents('div:first').after($('#completion_selector'));
			$('#completion_selector').show();
			break;		
		case 'Post Category':			
		
	}
	correctShadows();	
	
	// to display help text about 'grouping' for the first key selector
	if ($(this).is('[name=key_1]')) {
    var mySelector = $('#first_key_selector').next('#proj_selector, #person_selector');
    if ($(mySelector).children('.help').length == 0)
      $(mySelector).append('<p class="help">Enter \'All\' to group by this field</p>');
	}    
}

function cleanupSelections(key_select) {
	$(key_select).parents('.key_selectors').siblings('.value_selectors')
	.each(function() {
		$(this).children('select').children('option:first-child').attr('selected', true);
		$(this).children(':text').val('');
		$(this).children('p').remove();
		$(this).hide();
	});
	resetUsedOptions();
}

//this is to ensure that keys are unique
function resetUsedOptions() {
	usedOptions = new Array();
	$('select[name=key_1], select[name=key_2], select[name=key_3]').each(function() {	
		myOption = $(this).val();
		if (myOption) { 		
			if (exists_in_array(dateOptions, myOption))
				myOption = 'dateOptions';
			else if (exists_in_array(personOptions, myOption))
				myOption = 'personOptions';
			usedOptions.push(myOption);
		}
	});	
}

function correctShadows() {
	//correcting the height of shadows
	if (navigator.appName != 'Microsoft Internet Explorer') {
		var myWrapper = $("#rpwzd").parents('.contentPanelWrapper:first');
		var h = myWrapper.height();
		$("div.cp_shadow, div.cp_shadow1, div.cp_shadow2", myWrapper).height(h);
	}	
}

