// see http://knowledge-base.server/making-nice-link-lists/

// applies onclick events to the first parent of a link, and mouseover styles
// el can be a reference to an element, or the id of said element
// pTag is the type of parent tag we're looking for- for example, li, or tr. If not set, the first parent found will be used
// over and out should be objects containing the style rules to apply onmouseover or onmouseout
// c is the class of the links to be processed- others will be ignored if this is set
// for example: {'backgroundColor' : '#FFA', 'border' : '1px solid green'};
function fixLinks(el, pTag, over, out, c){
	// over and out are objects defining the styles to set onmouseover and onmouseout. if over is text, assumed to be a class
	over = over != null ? over : {'backgroundColor' : '#FFA'};
	out = out != null ? out :  {'backgroundColor' : '#FFF'};

// create text for the onmouseover and onmouseout functions
	var fover = '', fout = '';
	if (typeof over === 'string'){
		fover = 'this.className += " ' + over + '";';
		fout = 'this.className = (this.className).replace(/' + over + '/g, "");';
	}
	else {
		for (i in over)
			fover += 'this.style.' + i + '="' + over[i] + '";';
		for (i in out)
			fout += 'this.style.' + i + '="' + out[i] + '";';
	}
	//console.log(fover);
	//console.log(fout);
	
	// loop through all the links within the element and apply events. 
	t = (typeof el == 'string' ? $(el) : el).getElementsByTagName('a');
	for (var i = 0, j = t.length; i < j; i++){
		//alert(c + ' ' + t[i].className);
		if (c && t[i].className.indexOf(c) == -1) continue;
		// find appropriate parent
		el = t[i].parentNode;
		while (pTag && pTag.toUpperCase() != el.tagName && el.parentNode) el = el.parentNode;
		// apply onclick events to parent
		var att;
		if (att = t[i].getAttribute('href')){
			att = att.replace(/\"/,'\"');
			if (att.match(/^javascript\:/)){
				//alert(att.replace(/^javascript\:/,''));
				//alert(el);
				ghost_addEvent(el, 'click', new Function(att.replace(/^javascript\:/,'').replace(/%20/, ' ')));
				//ghost_addEvent(el, 'click', new Function('alert("sdsdsd")'));
			}
			else
				ghost_addEvent(el, 'click', new Function('window.location="' + att + '"'));
		}
		else if(t[i].onclick){
			ghost_addEvent(el, 'click', t[i].onclick);
		}
		else continue; 
		
		// kill click event if link is clicked, so we don't get the same event firing twice
		ghost_addEvent(t[i], 'click', function(evt){
																		try{ evt.stopPropagation(); }
																		catch(err){ evt.cancelBubble = true; }
																	});		
		
		el.style.cursor = 'pointer';
		if (fover) ghost_addEvent(el, 'mouseover', new Function(fover));
		if (fout) ghost_addEvent(el, 'mouseout', new Function(fout));
	}
	
};
var ghost_fixLinks = fixLinks;