// requires jquery library

////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////

var LeapCPListings = $.extend({},{
	column_offsets_by_group: {},
	_group_showing: {},
	_overall_showing: false,
	_columns_visible: {},
	_left_most_column: 2,
	_right_most_column: 0,
	_tooltips: {},
	_sort_data: {},
	compare_ids: [],
	sort_field: '',

	REPEAT_HEADER: 5,
	
	init: function(column_offsets_by_group, group_codes_to_show_text, sort_field) {
		this.column_offsets_by_group = column_offsets_by_group;
		
		// columns 0-1
		this._columns_visible = {0:true, 1:true};
		
		var last_col_offset = 0;
		for(var group_code in this.column_offsets_by_group) {
			var offsets = this.column_offsets_by_group[group_code];
			for (var i=0; i < offsets.length; i++) {
				this._columns_visible[offsets[i]] = true;
				last_col_offset = Math.max(last_col_offset, offsets[i]);
			};

			this._group_showing[group_code] = true;
		}

		// last column
		this._columns_visible[last_col_offset + 1] = true;
		this._right_most_column = last_col_offset;
		
		// show a column
		// if (typeof console != 'undefined') console.log('before initGroupsToShow')
		this.initGroupsToShow(group_codes_to_show_text);
		
		// we need to show or hide at least one group to get positioning to work correctly
		// if (this._group_showing['a']) this.showGroup('a');
		// 	else this.hideGroup('a');
		
		// init CompareNowButton
		$('#CompareNowButton').bind('click', function() { LeapCPListings.compareNow(); return false; });
		
		// init radius change button
		$('#RadiusPulldown').bind('change', function() { LeapCPListings.changeRadius(); });
		
		// ini info popup images
		$('img.infoButton').bind('mouseenter', function() { this.src='/template/modules/leapfrog/cp_files/listings/images/i_over.png' });
		$('img.infoButton').bind('mouseleave', function() { this.src='/template/modules/leapfrog/cp_files/listings/images/i_up.png' });

		// activate the change pulldown
		// if (typeof console != 'undefined') console.log('before initProcedureChangePulldown')
		this.initProcedureChangePulldown();
		
		// init the sort
		this.sort_field = sort_field;
		this.initSortImage();
	},

	// these happen after everything is loaded, including CSS
	initOnLoad: function() {
		// move the title
		// if (typeof console != 'undefined') console.log('before updateProcedureTitleAndPulldown')
		this.updateProcedureTitleAndPulldown();
		
		// if no groups are showing, hide the dividers
		this.updateMiddleDivider();
	},

	initToolTips: function(tooltips) {
		this._tooltips = tooltips;
		
		// attach the tootips handler
		$('.columnHeaderWithTip').tooltip({
			bodyHandler: function() {
				var id = this.id.substr(20);
				return LeapCPListings._tooltips[id];
				// return 'tooltip for '+(id);
			},
			extraClass: 'summary',
			delay: 350
		});
	},
	
	initSortData: function(sort_data) {
		this._sort_data = sort_data;
	},

	initGroupsToShow: function(group_codes_to_show_text) {
		var groups_to_show_map = {};
		for (var group_code in this._group_showing) {
			groups_to_show_map[group_code] = false;
		}
		
		var group_codes_to_show = group_codes_to_show_text.split('.');
		$.each(group_codes_to_show, function() {
			// don't count the overall group
			if (this == 'oa') {
				LeapCPListings._overall_showing = true;
				return;
			}

			groups_to_show_map[this] = true;
		});


		// just change the variables
		for (var group_code in this._group_showing) {
			if (groups_to_show_map[group_code]) {
				// if (typeof console != 'undefined') console.log('before this.showGroup('+group_code+')')
				this.changeVariablesToShowGroup(group_code);
				$('#procedureColumnSelectCheckbox_'+group_code).attr('checked',true);
			} else {
				// if (typeof console != 'undefined') console.log('before this.hideGroup('+group_code+')')
				this.changeVariablesToHideGroup(group_code);
				$('#procedureColumnSelectCheckbox_'+group_code).attr('checked',false);
			}
		}
	},
	
	initSortImage: function() {
		var code = this.sort_field;
		if (code.length == 0) code = 'name';
		this.updateSortImage(code);
	},
	
	sortBy: function(sort_code) {
		if (sort_code.length == 0) sort_code = 'name';
		
		// calculate desired order
		var id;
		var ids_in_order = [];
		
		if (this.compare_ids.length > 0) {
			// only use the compare ids
			for (var i=0; i < this.compare_ids.length; i++) {
				ids_in_order.push(this.compare_ids[i]);
			};
		} else {
			// no compare ids, sort all ids in the sort data
			for(id in this._sort_data) {
				ids_in_order.push(id);
			}
		}
		
		ids_in_order.sort(function(a,b) {
			var weight_a = LeapCPListings._sort_data[a][sort_code] * 1000 + LeapCPListings._sort_data[a]['name'];
			var weight_b = LeapCPListings._sort_data[b][sort_code] * 1000 + LeapCPListings._sort_data[b]['name'];

			// reversed, highest first
			return weight_b - weight_a;
		});
				
		// make changes
		//  add rows beneath tr.last_header
		var spacer_tr_obj,hosp_tr_obj,rpt_header1,rpt_header2;
		var last_tr_obj = $('tr.last_header');
		var first = true;
		var repeat_counter = 0;
		var repeat_header_offset = 0;
		for (var i=0; i < ids_in_order.length; i++) {
			id = ids_in_order[i];
			
			// check for repeat counter
			if (repeat_counter > 0 && repeat_counter % this.REPEAT_HEADER == 0) {
				// add move up the headers
				rpt_header1 = $('#rpt_header_'+repeat_header_offset+'-0');
				rpt_header2 = $('#rpt_header_'+repeat_header_offset+'-1');
				last_tr_obj.after(rpt_header1);
				rpt_header1.after(rpt_header2);
				last_tr_obj = rpt_header2;
				++repeat_header_offset;
			}


			// move the spacer rows to the top of the table
			spacer_tr_obj = $('#spacer_row_'+id);
			last_tr_obj.after(spacer_tr_obj);

			// move the hospital rows to the top of the table
			hosp_tr_obj = $('#hosp_row_'+id);
			spacer_tr_obj.after(hosp_tr_obj);

			// assign the last tr object for the next row
			last_tr_obj = hosp_tr_obj;
			
			// hide or show the spacer if it is first
			if (first) {
				spacer_tr_obj.addClass('horizontal_spacer_hidden');
			} else {
				spacer_tr_obj.removeClass('horizontal_spacer_hidden');
			}
			

			++repeat_counter;
			first = false;
		}
		
		// get rid of any extra rpt_header rows
		var headers_shown = repeat_header_offset;
		$('tr.rpt_header').each(function() {
			var offset = parseInt(this.id.replace(/rpt_header_(\d+)-\d+/,'$1'));
			// console.log('offset (',offset,') >= headers_shown (',headers_shown,') = ',(offset >= headers_shown))
			if (offset >= headers_shown) {
				// hide this header
				$(this).hide();
			}
		});
		
		// remember the sort field and update the bookmark
		this.sort_field = sort_code;
		this.updateBookmarkLink();
		
		// update the img
		this.updateSortImage(this.sort_field);
		
		// cancel click
		return false;
	},
	
	updateSortImage: function(sort_field) {
		// clear all
		$('img.sortArrow').each(function() { this.src='/template/modules/leapfrog/cp_files/listings/images/lf-column_sort-icon.gif'; });
		
		// update the highlighted one
		// $('img#sort-'+sort_field).css('border','2px solid yellow');
		$('img#sort-'+sort_field).each(function() { 
			this.src='/template/modules/leapfrog/cp_files/listings/images/lf-column_sort-icon-current.gif'; 
		});
	},

	toggleGroup: function(group_code) {
		if (this._group_showing[group_code]) {
			this.hideGroup(group_code);
		} else {
			this.showGroup(group_code);
		}
	},

	
	showGroup: function(group_code) {
		this.changeVariablesToShowGroup(group_code);

		// always make sure the dividers are shown
		// if (typeof console != 'undefined') console.log('before this.showProcedureDividers()')
		this.updateMiddleDivider();
		
		// if (typeof console != 'undefined') console.log('before this.updateProcedureTitleAndPulldown()')
		this.updateProcedureTitleAndPulldown();
	},
	changeVariablesToShowGroup: function(group_code) {
		var offsets = this.calculateOffsetsForToggle(group_code, true);
		for (var i=0; i < offsets.length; i++) {
			$('._lcp'+offsets[i]).show();
			this._columns_visible[offsets[i]] = true;
		};
		
		this._group_showing[group_code] = true;
	},
	
	hideGroup: function(group_code) {
		this.changeVariablesToHideGroup(group_code);
		
		this.updateMiddleDivider();

		this.updateProcedureTitleAndPulldown();
	},
	changeVariablesToHideGroup: function(group_code) {
		var offsets = this.calculateOffsetsForToggle(group_code, false);
		for (var i=0; i < offsets.length; i++) {
			$('._lcp'+offsets[i]).hide();
			this._columns_visible[offsets[i]] = false;
		};
		
		this._group_showing[group_code] = false;
	},
	
	calculateOffsetsForToggle: function(group_code, showing) {
		var offsets = this.column_offsets_by_group[group_code];

		// always include the column to the left, unless we are at the leftmost column
		//  this is done server-side now
		// if (offsets[0] > this._left_most_column) {
		// 	offsets.push(offsets[0] - 1);
		// }
		
		return offsets;
	},
	
	updateProcedureTitleAndPulldown: function() {
		if (this.anyProcedureGroupsAreShowing()) {
			// show title and pulldown above ratings
			var left_pos, top_pos, new_width;
			var left_col_offset = this.getLeftMostVisibleColumnOffset();
			var right_col_offset = this.getRightMostVisibleColumnOffset();
			if (!left_col_offset) {
				// no title visible at all - shouldn't get here
				return;
			}

			// get the top left position
			var left_bg_obj = $('._lcpobg'+left_col_offset);
			if (!left_bg_obj.is('*')) return;
			var right_bg_obj = $('._lcpobg'+right_col_offset);

			var left_bg_position = left_bg_obj.position();
			left_pos = left_bg_position.left;
			top_pos = left_bg_position.top;

			// get the right position
			var right_edge = right_bg_obj.position().left + right_bg_obj.width();

			new_width = right_edge - left_pos;
			$('div.psrContainer').css({position:'absolute', left:left_pos+'px', top:top_pos+'px', width:new_width+'px', display:'block'}).show();
			
			// hide the other pulldown
			$('#MoreInfoProcedureChangePulldown').hide();
		} else {
			// show the pulldown underneath the more info image
			$('#MoreInfoProcedureChangePulldown').show();
			
			// hide the other pulldown (and title)
			$('div.psrContainer').hide();
		}

		// reposition the pulldown to match the location of the currently showing pulldown image
		this.repositionChangePulldown();


/*
		var left_pos, top_pos, new_width;
		
		var left_col_offset = this.getLeftMostVisibleColumnOffset();
		var right_col_offset = this.getRightMostVisibleColumnOffset();
		// if (typeof console != 'undefined') console.log('getLeftMostVisibleColumnOffset='+left_col_offset+' getRightMostVisibleColumnOffset='+right_col_offset+'')
		
		if (!left_col_offset) {
			// no title visible at all
			$('div.psrContainer').hide();
			$('div#MoreInfoProcedurePulldownContainer #MoreInfoProcedureChangePulldown').show();
			this.repositionChangePulldown();
			return;
		}

		// get the top left position
		var left_bg_obj = $('._lcpobg'+left_col_offset);
		var right_bg_obj = $('._lcpobg'+right_col_offset);
		var table_obj = $('table#container');
		if (!left_bg_obj.is('*')) return;

		var left_bg_position = left_bg_obj.position();
		left_pos = left_bg_position.left;
		top_pos = left_bg_position.top;
		
		// get the right position
		var right_edge = right_bg_obj.position().left + right_bg_obj.width();
		

		new_width = right_edge - left_pos;
//		if (typeof console != 'undefined') console.log('left_bg_position.top='+left_bg_position.top+' left_bg_obj.height()='+left_bg_obj.height()+' left_pos='+left_pos+' right_edge='+right_edge+' new_width='+new_width+'');
		$('div.psrContainer').css({position:'absolute', left:left_pos+'px', top:top_pos+'px', width:new_width+'px', display:'block'}).show();
		
		// reposition the pulldown
		this.repositionChangePulldown();
*/
	},
	

	initProcedureChangePulldown: function() {
		$('#ProcedureChangePulldown').bind('click', function() {
			LeapCPListings.clickProcedureChangePulldown();
		});
		$('#MoreInfoProcedureChangePulldown').bind('click', function() {
			LeapCPListings.clickProcedureChangePulldown();
		});

		$('#popupClear').bind('click', function() {
			LeapCPListings.clearProcedureChangePulldown();
		});
		
		$('.procedureColumnSelectCheckbox').bind('click', function() {
			LeapCPListings.handleCheckboxChange(this.id);
		});

		$('#popup .item .itemLabel').bind('click', function() {
			LeapCPListings.toggleCheckbox(this.id);
		});
	},

	
	toggleCheckbox: function(label_id) {
		var group_code = this.idToGroupCode(label_id);
		$('#procedureColumnSelectCheckbox_'+group_code).click();
		this.handleCheckboxChange('procedureColumnSelectCheckbox_'+group_code);
	},
	
	handleCheckboxChange: function(checkbox_id) {
		var group_code = this.idToGroupCode(checkbox_id);
		var checked = $('#'+checkbox_id).attr('checked');
		if (checked) {
			this.showGroup(group_code);
		} else {
			this.hideGroup(group_code);
		}
		
		// update the bookmarkable link
		this.updateBookmarkLink();
	},
	

	idToGroupCode: function(element_id) {
		return element_id.replace(/^(.*_).*?/,"");
	},
	
	// click pulldown
	clickProcedureChangePulldown: function() {
		$('#popup').show();

		// set to the body height
		// alert('$(\'body\').height()='+$('body').height()+' $(window).height()='+$(window).height()+'')
		var new_height = Math.max($('body').height(), $(window).height());
		$('#popupClear').css('height',new_height+'px');
		$('#popupClear').show();
	},
	
	clearProcedureChangePulldown: function() {
		$('#popup').hide();
		$('#popupClear').hide();
	},
	
	repositionChangePulldown: function() {
		var left_pos, top_pos;
		var pulldown_obj = (this.anyProcedureGroupsAreShowing() ? $('#ProcedureChangePulldown') : $('#MoreInfoProcedureChangePulldown'));
		var pulldown_position = pulldown_obj.offset();
		left_pos = pulldown_position.left - 7;
		top_pos = pulldown_position.top + pulldown_obj.outerHeight();
//		if (typeof console != 'undefined') console.log('ProcedureChangePulldown pulldown_position='+pulldown_position+' left_pos='+left_pos+' top_pos='+top_pos+'');
		
		$('#popup').css({position:'absolute', left:left_pos+'px', top:top_pos+'px'});
	},
	
	getLeftMostVisibleColumnOffset: function() {
		for (var i=this._left_most_column; i <= this._right_most_column; i++) {
			if (this._columns_visible[i]) return i;
		};
		return false;
	},
	getRightMostVisibleColumnOffset: function() {
		for (var i=this._right_most_column; i >= this._left_most_column; i--) {
			if (this._columns_visible[i]) return i;
		};
		return false;
	},
	
	anyProcedureGroupsAreShowing: function() {
		for (var group_code in this._group_showing) {
			if (this._group_showing[group_code]) return true;
		}
		return false;
	},
	
	updateMiddleDivider: function() {
		// if (typeof console != 'undefined') console.log('this.anyProcedureGroupsAreShowing='+this.anyProcedureGroupsAreShowing()+' this._overall_showing='+this._overall_showing+'');
		if (this.anyProcedureGroupsAreShowing() && this._overall_showing) {
			// show the divider
			$('.mid_spacer').show();
		} else {
			// hide the divider
			$('.mid_spacer').hide();
		}
	},
	// showProcedureDividers: function() {
	// 	// $('._lcp'+(this._left_most_column-1)).show();
	// 	$('._lcp'+(this._right_most_column+1)).show();
	// },
	// hideProcedureDividers: function() {
	// 	// $('._lcp'+(this._left_most_column-1)).hide();
	// 	// alert('hiding '+(this._right_most_column+1))
	// 	$('._lcp'+(this._right_most_column+1)).hide();
	// 	// $('._lcp'+(this._right_most_column+1)).css({'background-color':'green',border:'1px solid red'});
	// },
	
	/// compare now
	compareNow: function() {
		// get all the selected values
		var selected_ids_map = {};
		var checked_count = 0;

		this.compare_ids = [];
		$('.compareCheckbox:checked').each(function() {
			selected_ids_map[this.id] = true;
			LeapCPListings.compare_ids.push(this.id);
			++checked_count;
		});
		if (checked_count < 1) {
			/* keep */ alert('Please choose at lease one hospital to compare.');
			return;
		}

		// hide any hospital row or spacer row not matching the following ids
		$('tr.hospital_row').each(function() {
			// hosp_row_xxx
			var hospital_id = this.id.substr(9);
			if (typeof selected_ids_map[hospital_id] == 'undefined') {
				$('#hosp_row_'+hospital_id).hide();
				$('#spacer_row_'+hospital_id).hide();
			}
		});
		
		// re-sort to fix headers
		this.sortBy(this.sort_field);

		// update the bookmarkable link
		this.updateBookmarkLink();
	},

	updateBookmarkLink: function() {
		if ($('#BookmarkLink').is('*')) {
			$('#BookmarkLink').attr('href',this.rebuildURL(true));
		}
	},
	
	changeRadius: function() {
		var new_url = this.rebuildURL(false);
		document.location = new_url;
	},
	
	rebuildURL: function(include_compare_ids) {
		var get_vars = AWCOURLUtil.extractGetVarsFromURL(document.location);
		
		// add the checked groups
		var new_group_codes_text = '';
		for (var group_code in this._group_showing) {
			if (this._group_showing[group_code]) {
				new_group_codes_text += (new_group_codes_text.length ? '.' : '')+group_code;
			}
		}
		if (this._overall_showing) {
			new_group_codes_text += (new_group_codes_text.length ? '.' : '')+'oa';
		}
		get_vars['cols'] = new_group_codes_text;
		
		// get the radius if there is one
		if ($('#RadiusPulldown').is('*')) {
			get_vars['radius'] = $('#RadiusPulldown').val();
		}
		
		// add the compare ids if they exist
		if (typeof get_vars['hids'] != 'undefined') get_vars['hids'] = '';
		if (include_compare_ids) {
			var hids_text = this.compare_ids.join('.');
			if (hids_text.length) {
				get_vars['hids'] = this.compare_ids.join('.');
			}
		}
		
		// add the sort preference
		if (this.sort_field.length) {
			get_vars['srt'] = this.sort_field;
		}
		
		return AWCOURLUtil.addGetVarsToURL(get_vars, document.location);
	},
	
	unset: function(old_hash, key_to_remove) {
		var new_hash = {};
		for (var k in old_hash) {
			if (k == key_to_remove) continue;
			new_hash[k] = old_hash[k];
		};
		return new_hash;
	},
	
	_end: null
});

