/* http://www.kryogenix.org/code/browser/searchhi/ */
/* Modified 20021006 to fix query string parsing and add case insensitivity */
/* Modified 20070316 to stop highlighting inside nosearchhi nodes */
function highlightWord(node,word) {
	// Iterate into this nodes childNodes
	if (node.hasChildNodes) {
		var hi_cn;
		for (hi_cn=0;hi_cn<node.childNodes.length;hi_cn++) {
			highlightWord(node.childNodes[hi_cn],word);
		}
	}

	// And do this node itself
	if (node.nodeType == 3) { // text node
		tempNodeVal = node.nodeValue.toLowerCase();
		tempWordVal = word.toLowerCase();
		if (tempNodeVal.indexOf(tempWordVal) != -1) {
			pn = node.parentNode;
			// check if we're inside a "nosearchhi" zone
			checkn = pn;
			while (checkn.nodeType != 9 &&
			checkn.nodeName.toLowerCase() != 'body') {
			// 9 = top of doc
				if (checkn.className.match(/\bnosearchhi\b/)) { return; }
				checkn = checkn.parentNode;
			}
			if (pn.className != "searchword") {
				// word has not already been highlighted!
				nv = node.nodeValue;
				ni = tempNodeVal.indexOf(tempWordVal);
				// Create a load of replacement nodes
				before = document.createTextNode(nv.substr(0,ni));
				docWordVal = nv.substr(ni,word.length);
				after = document.createTextNode(nv.substr(ni+word.length));
				hiwordtext = document.createTextNode(docWordVal);
				hiword = document.createElement("font");
				hiword.className = "searchword";
				hiword.appendChild(hiwordtext);
				pn.insertBefore(before,node);
				pn.insertBefore(hiword,node);
				pn.insertBefore(after,node);
				pn.removeChild(node);
			}
		}
	}
}

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

};

function searchHighlight() {

	if (Cookie.get('vs-search-keywords')) {
		var words = Cookie.get('vs-search-keywords');
		//words = words.split(/[\s|\+]+/);
	}
	else if (window.query && window.query.keywords && (window.query.keywords.length > 0)) {
		//var words = window.query.keywords.split(/[\s|\+]+/);
		var words = window.query.keywords;
	}
	else {
		return;
	}

	/*for (var w=0; w<words.length; w++) {
    	$$('.vs-search-word-container').each(function(obj) {
    		highlightWord(obj, words[w]);
    	});
	}*/
	if(words.length <= 1) return false;
	
	words = words.replace('+',' ');
	$$('.vs-search-word-container').each(function(obj) {
		highlightWord(obj, words);
	});
}

FastInit.addOnLoad(function() {
	$$('.highlight').each(function(el) {
		el.onmouseover = function() {
			this.addClassName('light_grey');
		};
		el.onmouseout = function() {
			this.removeClassName('light_grey');
		};
		
		Event.observe(el, 'click', function(event) {
			var element = Event.element(event);
			if(element.hasClassName('vs-fav-image')) return;
		//el.onclick = function() {
			/*if(this.down(0).hasClassName('vs_md') && this.down(6).href) {
				location.href = this.down(6).href.toString();
			}
			else */
			if(el.down(1).href) {
				location.href = el.down(1).href.toString();
			}
			else if(el.down(2).href) {
				location.href = el.down(2).href.toString();
			}
			else if(el.down(3).href) {
				location.href = el.down(3).href.toString();
			}
		//};
		});
	});
});

var SEARCHFORM = new Object();
SEARCHFORM = {

	options: new Object(),	// stores the array of options for the multiselect
	links: new Object(),		// stores the parent (main type) element name

	init: function() {
		$$('div.selectMultiple').each(
			function(select) {
				var selectName = select.readAttribute('rel');
				var selectTextBox = select.getElementsBySelector('input.text')[0];
				
				//
				// Make sure we have options defined for this select.
				//
				if (SEARCHFORM.options[selectName]) {
					var selectOptions = SEARCHFORM.options[selectName];
				}
				else {
					//if (window.console) console.log("No options defined for the select " + selectName);
					return true;
				}
				
				//
				// Make sure we have a main type select in the dom.
				//
				if (SEARCHFORM.links[selectName] && document.getElementsByName(SEARCHFORM.links[selectName]).length == 1) {
					var parentSelect = document.getElementsByName(SEARCHFORM.links[selectName])[0];
				}
				//
				// No linked main type, so what we do is print all options.
				//
				else {
					//if (window.console) console.log("Parent does not exist or no linked element");
					SEARCHFORM.drawOptions(select, selectOptions, false);
					return true;
				}
				
				//
				// First step is to figure out if there are any pre-selected
				// items in the main type select, then get the name of the section
				// that is selected. We next load that section into the multiselect box.
				//
				if (parentSelect.selectedIndex > 0 && parentSelect.options[parentSelect.selectedIndex].value.toLowerCase().gsub(/([\/\à\ \/\'])/, '-').gsub(/(-{1,})/, '-').gsub(/([^\S+])/, '-') != '') {
					var selectValue = parentSelect.options[parentSelect.selectedIndex].value.toLowerCase().gsub(/([\/\à\ \/\'])/, '-').gsub(/(-{1,})/, '-').gsub(/([^\S+])/, '-');
					
					//
					// Check if we have options and then display them
					//
					if (selectOptions[selectValue]) {
						SEARCHFORM.drawOptions(select, selectOptions[selectValue], false);
					}
				}
				//
				// Nothing selected, so disable the multiselect.
				//
				else {
					SEARCHFORM.setToEmpty(select, VIVASTREET.captions['select_previous'] + ' ' + parentSelect.options[0].text);
				}
			}
		);
	},
	
	drawOptions: function(select, selectOptions, reset) {
		var selectName = select.readAttribute('rel');
		var selectUl = select.getElementsBySelector('ul')[0];
		var html = '';
		var optValue;
		var optLabel;
		var defaultSelected;
		var j = 0;
		
		//
		// whether or not to check for default values in
		// the query string
		//
		if (!reset) {
			reset = false;
		}
		
		for (var option in selectOptions) {
			defaultSelected = false;
			optValue = option;
			optLabel = selectOptions[option];
			
			//
			// If reset is false, we want to check the global
			// query string for search terms
			//
			if (false == reset && window.query[selectName]) {
				for (var i in window.query[selectName]) {
					if (window.console && typeof(window.query[selectName][i]) == 'string') console.log("Trying (" + i + ") " + Url.decode(window.query[selectName][i]) + " : " + optValue);
				
					if (typeof(window.query[selectName][i]) == 'string' && Url.decode(window.query[selectName][i]).gsub(/\+/, ' ') == optValue) {
						defaultSelected = true;
						break;
					}
					if (typeof(window.query[selectName][Url.decode(i)]) == 'string' && window.query[selectName][Url.decode(i)].gsub(/\+/, ' ') == optValue) {
						defaultSelected = true;
						break;
					}
				}
			}
			
			html += '<li><label for="' + selectName + '_' + j + '">'
				  + '<input' + (defaultSelected == true ? ' checked="checked"' : '') + ' style="border-width:0px;" type="checkbox" id="' + selectName + '_' + j
				  + '" name="' + selectName + '[]" value="' + optValue + '" />'
				  + optLabel + '</label></li>';
			
			j++;
		}
		
		selectUl.update(html);
		SEARCHFORM.selectMultiples(select);
	},
	
	resetMultipleSelect: function(elem) {
		$$('#ul_' + $(elem).up().readAttribute('rel') + ' input[type="checkbox"]').each(function(echk) {
			echk.checked = false;
			$(echk.parentNode.parentNode).removeClassName('selected');
		});
		var ename = 'value_' + $(elem).up().readAttribute('rel');
		$(ename).value = $(ename).getAttribute('title');
	},

	selectMultiples: function(select) {
		//
		// This function loops through the multiselects and
		// applies the hover and click events.
		//
		var _selectMultiples = function(e) {
			setroll('rollover_'+e.readAttribute('rel'), 'ul_'+e.readAttribute('rel'), false);
			
			var val_holder = $('value_'+$(e).readAttribute('rel'));
			var has_checked = false;
						
			if (val_holder) {
				val_holder.value = '';
			}

			$('ul_'+e.readAttribute('rel')).childElements().each(function(eli){
				eli.onmouseover = function(){this.addClassName('altrow')};
				eli.onmouseout = function(){this.removeClassName('altrow')};
				
				var echk = eli.down(1);
				
				if (echk.checked && val_holder) {
					val_holder.value += (val_holder.value.length ? ', ' : '') + echk.value;
					$(echk.parentNode.parentNode).addClassName('selected');
					has_checked = true;
				}
				echk.onclick = function(){
					if(this.checked) {
						var tmp = $('value_'+$(this).up(3).readAttribute('rel'));
						tmp.value = tmp.value.gsub(tmp.readAttribute('title'), '');
						tmp.value += (tmp.value.length ? ', ' : '')+this.value;
						$(this.parentNode.parentNode).addClassName('selected');
					}
					else {
						var tmp = $('value_'+$(this).up(3).readAttribute('rel'));
						if(tmp.value.indexOf(', '+this.value) != -1)
							tmp.value = tmp.value.gsub(', '+this.value, '');
						else
							tmp.value = tmp.value.gsub(this.value, '');

						if(tmp.value.substr(0,2) == ', ')
							tmp.value = tmp.value.substr(2);

						if(tmp.value == '')
							tmp.value = tmp.readAttribute('title');

						$(this.parentNode.parentNode).removeClassName('selected');
					}
				};
			});
			
			if (has_checked == false) {
				SEARCHFORM.resetMultipleSelect($('ul_' + e.readAttribute('rel')));
			}
		};
		
		//
		// If we were passed a select, use that one instead
		// of looping through all of them
		//
		if (select) {
			_selectMultiples(select);
		}
		else {
			$$('#search .selectMultiple').each(_selectMultiples);
		}
	},
	
	//
	// empties the UL and removes the rollover
	// event from the mutliselect
	//
	setToEmpty: function(select, caption) {
		var selectUl = select.getElementsBySelector('ul')[0];
		var selectTextBox = select.getElementsBySelector('input.text')[0];
		selectUl.update('');
		selectTextBox.value = caption;
		unsetroll('rollover_'+select.readAttribute('rel'), 'ul_'+select.readAttribute('rel'));
	},

	//
	// when a section is selected in main type, set
	// the sub-type options in the multiselect
	//
	showSection: function(sel, section_name, reset) {
		var select = $(sel);
		var selectName = '';
		
		//if (window.console) console.log("Looking for linked select...");
		
		for (var i in SEARCHFORM.links) {
			if (SEARCHFORM.links[i] == select.readAttribute('name')) {
				selectName = i;
				//if (window.console) console.log("The linked select name is " + i);
				break;
			}
		}
		
		if ('' == selectName) {
			return true;
		}
		
		var mSelect = $('multi_' + selectName);
		var selectedValue = select.options[select.selectedIndex].value.toLowerCase().gsub(/([\/\à\ \/\'])/, '-').gsub(/(-{1,})/, '-').gsub(/([^\S+])/, '-');

		//
		// The main type select value is empty, which means either
		// the first option (not selected) or the second option (ignore field)
		//
		if (selectedValue == '') {
			if (select.selectedIndex == 0) {
				SEARCHFORM.setToEmpty(mSelect, VIVASTREET.captions['select_previous'] + ' ' + select.options[0].text);
			}
			else {
				SEARCHFORM.setToEmpty(mSelect, VIVASTREET.captions['no_select_options']);
			}
		}
		//
		// Main type select value is good, find the value array
		// and fill the multiselect.
		//
		else {
			if (SEARCHFORM.options[selectName][selectedValue]) {
				SEARCHFORM.drawOptions(mSelect, SEARCHFORM.options[selectName][selectedValue], true);
				SEARCHFORM.selectMultiples(mSelect);
			}
			else {
				SEARCHFORM.setToEmpty(mSelect, VIVASTREET.captions['no_select_options']);
			}
		}
		
		return true;
	}

};