/**
 * Creating our own name space so not to interfere with other scripts
 */
var __ATW_Core = function() {

	var seal = function (obj, method) {
		var __this = obj;
		var __method = __this[method];
		// all remaining arguments are for the method
		var __args = Array.prototype.slice.apply(arguments, [2]);
		return function() { __method.apply(__this, __args); }
	};

	this.clone = function(obj, deep) {
		var cl = new obj.constructor();
		for (var k in obj) {
			if (!deep) {
				cl[k] = obj[k];
			} else if (typeof obj[k] == 'object') {
				cl[k] = clone(obj[k], deep);
			} else {
				cl[k] = obj[k];
			}
		}
		return cl;
	}
	var clone = this.clone;

	this.init = function() {
		if (window.ATW_Cookbook_Control_List) {
			this.init_cookbook(window.ATW_Cookbook_Control_List);
		}
		if (window.__ATW_Start_Vitamin_Advisor) {
			window.__ATW_Start_Vitamin_Advisor();
		}
		this.init_drug_toggles();
	}

	var $ = function(id) {
		if (typeof id == 'string') {
			return document.getElementById(id);
		}
		return id;
	};

	this.$ = $;

	this.show = function(element, how) {
		if (!how) {
			how = 'block';
		}
		if (typeof element == 'string') {
			element = $(element);
		}

		if (element && element.style) {
            element.style.display = how;
        }
	};
	var show = this.show;

	this.hide = function(element) {
		if (typeof element == 'string') {
			element = $(element);
		}
		if (element && element.style) {
            element.style.display = 'none';
		}
	};
	var hide = this.hide;

	var N = function(nodeType) {
		return document.createElement(nodeType);
	};
	this.N = N;

	var T = function(content) {
		return document.createTextNode(content);
	};
	this.T = T;

	// http://prototype.conio.net/dist/prototype-1.4.0.js
	var Try = {
	  these: function() {
	    var returnValue;
	    for (var i = 0; i < arguments.length; i++) {
	      var lambda = arguments[i];
	      try {
	        returnValue = lambda();
	        break;
	      } catch (e) {}
	    }

	    return returnValue;
	  }
	}
	this.Try = Try;

	var enable_cookbook_row = function(element, row) {
		var new_class = (row % 2) ? 'odd-row' : 'even-row';
		element.className = element.className.
			replace('even-row', new_class).
			replace('odd-row', new_class);
		show(element, document.all ? 'block' : 'table-row');
	}

	this.update_cookbook_filter = function(sel) {
		var list = $('Cookbook-Content');
		if (!list) {
			return;
		}
		list = list.getElementsByTagName('TR');
		var row = 0, re = new RegExp(sel.value), e;
		for(var i = 0; i < list.length; i++) {
			e = list[i];
			if (sel.value == 'show_all') {
				if (e.className != 'Cookbook-Captions') {
					row++;
				}
	            enable_cookbook_row(e, row);
	        } else if (e.className == 'Cookbook-Captions') {
	        	enable_cookbook_row(e, 0);
	        } else if (re.test(e.className)) {
	        	row++;
	            enable_cookbook_row(e, row);
	        } else {
	            this.hide(e);
	        }
		}
	}

	this.init_cookbook = function(filter_list) {
		var i, e, sel = N('SELECT'), o;
		sel.options[0] = new Option('All', 'show_all');
		// wiring event handler
		sel.onchange = seal(this, 'update_cookbook_filter', sel);
		// building drop-down of recipe filter options
		for(var i = 0; i < filter_list.length; i++) {
			e = filter_list[i].split('|');
			o = new Option(e[1], e[0]);
			sel.options[sel.options.length] = o;
		}
		var loc = $('Cookbook-Captions-DropDown');
		if (loc) {
			loc.appendChild(new T(' '));
			loc.appendChild(sel);
		}
		show(loc, 'inline');
	}

	this.init_a_drug_toggle = function(
			toggle_div, show_link, hide_link, toggle_content
	) {
		toggle_div = $(toggle_div);
		show_link = $(show_link);
		hide_link = $(hide_link);
		toggle_content = $(toggle_content);
		if (toggle_div && show_link && hide_link && toggle_content) {
			show(toggle_div, 'block');
			show(show_link, 'inline');
			hide(hide_link);
			hide(toggle_content);
			show_link.onclick = function() {
				hide(show_link);
				show(hide_link, 'inline');
				show(toggle_content);
				return false;
			}
			hide_link.onclick = function() {
				show(show_link, 'inline');
				hide(hide_link);
				hide(toggle_content);
				return false;
			}
		}
	}

	this.init_drug_toggles = function() {
		/* other brands */
		this.init_a_drug_toggle(
			'Other-Brands-Toggle', 'Other-Brands-Toggle-Show',
			'Other-Brands-Toggle-Hide', 'Also-Indexed'
		);
		/* combination drugs */
		this.init_a_drug_toggle(
			'Combo-Drugs-Toggle', 'Combo-Drugs-Toggle-Show',
			'Combo-Drugs-Toggle-Hide', 'Combination-List'
		);
	}

	this.site_link = '';
	this.link_extension = false;
	this.restrict_list = '';
	this.do_recipe_search = function(do_it) {
		// make recipe restriction list into map for faster lookup
		if (typeof this.restrict_list == 'string') {
			var _list = this.restrict_list.split(',');
			if (_list.length == 0) {
				this.restrict_list = false;
			} else {
				this.restrict_list = {};
				for (var i = 0; i < _list.length; i++) {
					this.restrict_list[_list[i]] = true;
				}
			}
		}

		if (_ATWRecipeList == undefined || !_ATWRecipeList) {
			return;
		}
		var filters = document.getElementsByName('__ATW_filter_options');
		var res = $('__ATW_recipe_search_results');
		var res_num = $('__ATW_recipe_search_results_num');
		var query = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0 };
		var check;
		var category;
		var key;
		if (res && res_num && filters.length) {
			// loop through all filters and collect which ones are checked,
			// thereby building a query bitmap
			var c = '';
			for(var i = 0; i < filters.length; i++) {
				check = filters[i];
				if (check && check.checked) {
					check = check.value.split('_');
					if (check.length == 2) {
						category = check[0];
						key = query[category];
						query[category] = key | check[1];
					}
				}
			}

			// loop through all recipes and see which ones match the filter
			var matches = true;
			var found_results = 0;
			var total_recipes = 0;
			var re = /%([0-9A-F]{2})/g;
			for(var id in _ATWRecipeList) {
				// make sure that, if there a restricted recipe list,
				// this one is on it
				if (
					!this.restrict_list
					|| (this.restrict_list && this.restrict_list[id])
				) {
					total_recipes++;
					check = _ATWRecipeList[id];
					matches = 0;
					for(var cat in query) {
						if (query[cat]) {
							switch(_ATWTypeLJS[cat].type) {
								case 'and':
									if ((check[cat] & query[cat]) == query[cat]) {
										matches++;
									}
									break;
								default:
									if (check[cat] & query[cat]) {
										matches++;
									}
							}
						} else {
							matches++;
						}
					}
					if (matches == 6) {
						c += '<a href="' + this.site_link + 'ContentID=' + id + (
								this.link_extension ? (
									'&category=Recipe&type=&title=' + check[0]
								) : ''
							) + '">' + check[0].replace(re, '&#x$1;') +
							'</a><br />';
						found_results++;
					}
				}
			}
			if (total_recipes == found_results) {
				found_results = 0;
			}
			res_num.innerHTML = 'Recipes matching your selection: ' +
				found_results;
			if (found_results) {
				show('__ATW_show_recipe_results_btn');
			} else {
				hide('__ ATW_show_recipe_results_btn');
			}
			res.innerHTML = c;
		}
	}

	this.find_parent_of_type = function(element, tag_name)
	{
		var current = element.parentNode;
		while (current != null)
		{
			if (
				current.nodeName != null &&
				current.nodeName.toLowerCase() == tag_name.toLowerCase()
			)
				return element.parentNode;
			current = current.parentNode;
		}
		return null;
	}

	this.paint_recipe_search = function(do_it) {
		if (!do_it) {
			setTimeout(seal(this, 'paint_recipe_search', true), 1);
			return;
		}
		var rsc = $('__ATW_recipe_search'); // recipe search container
		var in_form = (this.find_parent_of_type(rsc, 'form') != null);
		if (rsc) {
			var c = '<div id="__ATW_recipe_search_form">' +
				(!in_form ? '<form>' : '') + '<table class="r_search">';
			var type;
			var opt;
			var cid;
			var d = 0;
			for(var i in _ATWTypeLJS) {
				type = _ATWTypeLJS[i];
				d = 0;
				if (type && type.name && type.options) {
					c += '<tr class="rs_top_border"><th align="right">' + type.name + '</th>';
					for(var o in type.options) {
						opt = type.options[o];
						if (typeof opt == "string") {
							d++;
							cid = i + '_' + o;
							c += '<td><input type="checkbox" value="' + cid +
								'" name="__ATW_filter_options" id="__hni_f' + cid +
								'" onclick="__ATW_Core.do_recipe_search();" ' +
								' onkeyup="__ATW_Core.do_recipe_search();" ' +
								'/></td><td><label for="__atw_f' + cid + '" >' +
								opt + '</label></td>';
							if (d % 3 == 0) {
								c += '</tr><tr><td style="font-size: 1px;">&nbsp</td>';
							}
						}
					}
					c += '</tr>';
					if (d % 3 != 0) {
						c += '</tr><tr><td style="font-size: 1px;">&nbsp</td><tr>';
					}
				}
			}
			rsc.innerHTML = c + '</table>' + (!in_form ? '</form>' : '') +
				'</div><div id="__ATW_recipe_search_results_num"></div>' +
				'<div class="recipe_button_wrap">' +
				' <input type="button" id="__ATW_show_recipe_results_btn"' +
				' onclick="__ATW_Core.show_recipe_search_results();" ' +
				' value="Show Results" style="display: none;" /> ' +
				' <input type="button" id="__ATW_search_recipe_btn"' +
				' onclick="__ATW_Core.show_recipe_search_form();" ' +
				' value="Return to Search" style="display: none;" /> ' +
				' </div><div id="__ATW_recipe_search_results" ' +
				' class="recipe_search_results" style="display: none;"></div>';
			}
		this.do_recipe_search();
	}

	this.show_recipe_search_results = function() {
		hide('__ATW_show_recipe_results_btn');
		hide('__ATW_recipe_search_form');
		show('__ATW_recipe_search_results');
		show('__ATW_search_recipe_btn');
	}

	this.show_recipe_search_form = function() {
		hide('__ATW_recipe_search_results');
		hide('__ATW_search_recipe_btn');
		show('__ATW_show_recipe_results_btn');
		show('__ATW_recipe_search_form');
	}
};

__ATW_Core = new __ATW_Core();
