// <![CDATA[

function addEvent(elm, evType, fn, useCapture)
// cross-browser event handling for IE5+, NS6+ and Mozilla/Gecko
// By Scott Andrew
{
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	} else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	} else {
		elm['on' + evType] = fn;
	}
}

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

/*
 * Clear Default Text: functions for clearing and replacing default text in
 * <input> elements.
 */
addEvent(window, 'load', init, false);

function init() {
    var formInputs = document.getElementsByTagName('input');
    for (var i = 0; i < formInputs.length; i++) {
        var theInput = formInputs[i];

        if (theInput.parentNode.id != 'dontclear' && theInput.type !='submit' || theInput.type == 'search' && theInput.className.match(/\bcleardefault\b/)) {
            /* Add event handlers */
            addEvent(theInput, 'focus', clearDefaultText, false);
            addEvent(theInput, 'blur', replaceDefaultText, false);

            /* Save the current value */
            if (theInput.value != '') {
                theInput.defaultText = theInput.value;
            }
        }
    }
}

function clearDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;

    if (target.value == target.defaultText) {
        target.value = '';
    }
}

function replaceDefaultText(e) {
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;

    if (target.value == '' && target.defaultText) {
        target.value = target.defaultText;
    }
}

// show external links in new window
function externalLinks() {
    if (!document.getElementsByTagName) {
        // do nothing
    } else {
        var anchors = document.getElementsByTagName("a");
        for(var i=0; i<anchors.length; i++) {
            var anchor = anchors[i];
            if (anchor.getAttribute("rel") == "external") {
                anchor.target = "_blank";
            }

            if (anchor.getAttribute("rel") == "webImage") {
                anchor.onclick = imageWindow;
            }
        }
    }
 }
addEvent(window, "load", externalLinks, false);

// show and hide comparinator tabs
var cmp = {
	expandFirst: function() {
		if (!document.getElementById || !document.getElementsByTagName) { return; }
  		if (!document.getElementById('comparinator')) { return; }
		var comparinatorContent = document.getElementById('cmp-content');
		var comparinatorContainers = comparinatorContent.getElementsByTagName('dl');
		var links = document.getElementById("cmp-tabs").getElementsByTagName("a");
		var firstTab = links[0];
		comparinatorContainers[0].style.display = 'block';
		firstTab.parentNode.className = 'active';
	},

    hideContent: function() {
    	if (!document.getElementById || !document.getElementsByTagName) { return; }
  		if (!document.getElementById('comparinator')) { return; }
    	var comparinatorContent = document.getElementById('cmp-content');
		var comparinatorContainers = comparinatorContent.getElementsByTagName('dl');
		var links = document.getElementById("cmp-tabs").getElementsByTagName("a");
        for (var i=0; i<comparinatorContainers.length; i++) {
            comparinatorContainers[i].style.display = 'none';
            links[i].parentNode.className = '';
		}
	},

   clickedTab: function() {
   		if (!document.getElementById || !document.getElementsByTagName) { return; }
  		if (!document.getElementById('comparinator')) { return; }
   		var comparinatorContent = document.getElementById('cmp-content');
		var comparinatorContainers = comparinatorContent.getElementsByTagName('dl');
		var links = document.getElementById("cmp-tabs").getElementsByTagName("a");
        for (var i=0; i<links.length; i++) {
            eval("links[i].onclick = function() { cmp.hideContent(); links["+i+"].parentNode.className = 'active'; comparinatorContainers["+i+"].style.display = 'block'; return false;}");
   		}
	}
}
addLoadEvent(cmp.hideContent);
addLoadEvent(cmp.clickedTab);
addLoadEvent(cmp.expandFirst);

function inArray(needle) { for (var i=0; i < this.length; i++) { if (this[i] === needle) { return i; } } return false; } Array.inArray = inArray;
function addClass(theClass) { if (this.className != '') { this.className += ' ' + theClass; } else { this.className = theClass; } } Object.addClass = addClass;

// text utilities
function replaceText(el, text) {
  if (el != null) {
	clearText(el);
	var newNode = document.createTextNode(text);
	el.appendChild(newNode);
  }
}

function clearText(el) {
  if (el != null) {
	if (el.childNodes) {
	  for (var i = 0; i < el.childNodes.length; i++) {
		var childNode = el.childNodes[i];
		el.removeChild(childNode);
	  }
	}
  }
}

function appendText(node, text) {
   var newTextNode = document.createTextNode(text);
   node.appendChild(newTextNode);
}

function getText(el) {
  var text = "";
  if (el != null) {
	if (el.childNodes) {
	  for (var i = 0; i < el.childNodes.length; i++) {
		var childNode = el.childNodes[i];
		if (childNode.nodeValue != null) {
		  text = text + childNode.nodeValue;
		}
	  }
	}
  }
  return text;
}

/*
 * Dynamic Menu
 * Written by Andy Peatling - http://www.cssdev.com/
 * April 1, 2006.
 */

addLoadEvent(collapseMenu);
addLoadEvent(prepareMenu);

function collapseMenu(node) {
	if (!document.getElementById) return false;
	if (!document.getElementById("menu")) return false;
	if (!node) node = document.getElementById("menu");

	if (node.childNodes.length > 0) {
		for (var i=0; i<node.childNodes.length; i++) {
			var child = node.childNodes[i];
			if (child.nodeName == "UL") {
					child.style.display = "none";
			}
			collapseMenu(child);
		}
	}

}

function prepareMenu() {
	if (!document.getElementById || !document.getElementsByTagName) return false;
	if (!document.getElementById("menu")) return false;

	var links = document.getElementById("menu").getElementsByTagName("a");
	for (var i=0; i<links.length; i++) {
		links[i].onclick = function() {
			toggleMenu(this.parentNode.getElementsByTagName("UL")[0], this.href);
		}
		// addEvent(links[i], "blur", hideAll, false);
	}
}

/* function hideAll() {
	lists = document.getElementById('menu').getElementsByTagName('UL');
	for (var i=0; i<lists.length; i++) {
		lists[i].style.display = 'none';
	}
} */

function toggleMenu(node, link) {
	if (!document.getElementById) return false;
	if (!link || !node) return false;

	// Collapse all nodes, and only show clicked node (when clicking top level of menu)
	if (node.parentNode.parentNode.id == "menu") {
		hideTopLevels();
	}

	if (node.style.display == "") {
		node.style.display = "none"
	} else {
		node.style.display = ""
	}
}

function hideTopLevels() {
	if (!document.getElementById) return false;
	if (!(node = document.getElementById("menu"))) return false;

	if (node.childNodes.length > 0) {
		for (var i=0; i<node.childNodes.length; i++) {
			var child = node.childNodes[i];
			for(var j=0; j<child.childNodes.length; j++) {
				var grandchild = child.childNodes[j];
				if (grandchild.nodeName == "UL") {
					if (grandchild.style.display == '') {
						grandchild.style.display = "none";
					}
				}
			}
		}
	}
}

// curvy corners for ticker on homepage and throughout site
function tickerCorners() {
	if (!document.getElementById) return;
	if (!document.getElementById('ticker')) return;
	settings = {
		tl: { radius: 8 },
		tr: { radius: 8 },
		bl: { radius: 8 },
		br: { radius: 8 },
		antiAlias: true,
		autoPad: false
    }
    var divObj = document.getElementById("ticker");
    var cornersObj = new curvyCorners(settings, divObj);
    cornersObj.applyCornersToAll();
}
addLoadEvent(tickerCorners);

// ]]>

/*
 * jQuery ifixpng plugin
 * renamed from pngfix to ifixpng due to naming conflict 
 * with another plugin
 * Version 1.7  (18/09/2007)
 * @requires jQuery v1.1.3 or above
 *
 * Examples at: http://jquery.khurshid.com
 * Copyright (c) 2007 Kush M.
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

 /**
  *
  * @example
  *
  * optional if location of pixel.gif if different to default which is images/pixel.gif
  * $.ifixpng('media/pixel.gif');
  *
  * $('img[@src$=.png], #panel').ifixpng();
  *
  * @apply hack to all png images and #panel which icluded png img in its css
  *
  * @name ifixpng
  * @type jQuery
  * @cat Plugins/Image
  * @return jQuery
  * @author jQuery Community
  */

(function($) {

	/**
	 * helper variables and function
	 */

	$.ifixpng = function(customPixel) {
		$.ifixpng.pixel = customPixel;
	};

	$.ifixpng.getPixel = function() {
		return $.ifixpng.pixel || 'images/pixel.gif';
	};

	var hack = {
		ltie7  : $.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent),
		filter : function(src) {
			return "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true,sizingMethod=crop,src='"+src+"')";
		}
	};

	/**
	 * Applies ie png hack to selected dom elements
	 *
	 * $('img[@src$=.png]').ifixpng();
	 * @desc apply hack to all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').ifixpng();
	 * @desc apply hack to element #panel and all images with png extensions
	 *
	 * @name ifixpng
	 */

	$.fn.ifixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var base = $('base').attr('href'); // need to use this in case you are using rewriting urls
			if ($$.is('img') || $$.is('input')) { // hack image tags present in dom
				if ($$.attr('src').match(/.*\.png([?].*)?$/i)) { // make sure it is png image
					// use source tag value if set
					var source = (base && $$.attr('src').substring(0,1)!='/') ? base + $$.attr('src') : $$.attr('src');
					// apply filter
					$$.css({filter:hack.filter(source), width:$$.width(), height:$$.height()})
					  .attr({src:$.ifixpng.getPixel()})
					  .positionFix();
				}
			} else { // hack png css properties present inside css
				var image = $$.css('backgroundImage');
				if (image.match(/^url\(["']?(.*\.png([?].*)?)["']?\)$/i)) {
					image = RegExp.$1;
					$$.css({backgroundImage:'none', filter:hack.filter(image)})
					  .positionFix();
				}
			}
		});
	} : function() { return this; };

	/**
	 * Removes any png hack that may have been applied previously
	 *
	 * $('img[@src$=.png]').iunfixpng();
	 * @desc revert hack on all images with png extensions
	 *
	 * $('#panel, img[@src$=.png]').iunfixpng();
	 * @desc revert hack on element #panel and all images with png extensions
	 *
	 * @name iunfixpng
	 */

	$.fn.iunfixpng = hack.ltie7 ? function() {
    	return this.each(function() {
			var $$ = $(this);
			var src = $$.css('filter');
			if (src.match(/src=["']?(.*\.png([?].*)?)["']?/i)) { // get img source from filter
				src = RegExp.$1;
				if ($$.is('img') || $$.is('input')) {
					$$.attr({src:src}).css({filter:''});
				} else {
					$$.css({filter:'', background:'url('+src+')'});
				}
			}
		});
	} : function() { return this; };

	/**
	 * positions selected item relatively
	 */

	$.fn.positionFix = function() {
		return this.each(function() {
			var $$ = $(this);
			var position = $$.css('position');
			if (position != 'absolute' && position != 'relative') {
				$$.css({position:'relative'});
			}
		});
	};

})(jQuery);

$(document).ready(function() {
	$.ifixpng('http://netdrive.bobcat.com/shared/pixel.gif');
	$('img[@src$=.png]').ifixpng();

	if ($('.jCategory')) { // check for JavaScript category class name
		jCat.init();
		jCat.toggle();
	}
	if ($('.tabletoggle')) {
		tToggle.setTabs();
	}
	if ($('#media_widget_chooser')) {
		mediaWidget.selectMedia();
	}
});

var jCat = { // JavaScript category organizer

	init: function() {
		var catIndex = 1;
		$('.jCategory').each(function() {
			$(this).attr('id','jCat' + catIndex);

			var groupIndex = 1;
			$(this).children('div.group').each(function() {
				$(this).attr('id','cat' + catIndex + '-' + 'group' + groupIndex);
				groupIndex++;
			});

			var catId = $(this).attr('id');
			categoryItems = $(this).find('h4').length; // get total of items for category

			// index each item to use later for pagination
			var itemIndex = 1;
			$(this).find('h4').each(function() {
				$(this).attr('id','cat' + catIndex + '-' + itemIndex);
				itemIndex++;
			});

			catIndex++;

			$('.group[id$=group1]').addClass('activeGroup');
			jCat.sort(catId, categoryItems); // sort initial active items
		});
		$('.group:not("[id$=group1]")').hide(); // hide all but first category group
	},

	toggle: function() {
		$('.jCategory').append('<img src="http://netdrive.bobcat.com/shared/button_collapse.png" width="22" height="23" alt="button" title="collapse" class="noborder btn-toggle" />');
		$('.btn-toggle').ifixpng();
		$('.btn-toggle').css('cursor','pointer');
		$('.btn-toggle').toggle(
			function() {
				$(this).parent().children('.activeGroup, .paginate').slideUp('fast');
				$(this).attr({ src: 'http://netdrive.bobcat.com/shared/button_expand.png', title: 'expand' });
				$('.btn-toggle').ifixpng();
			},
			function() {
				$(this).parent().children('.activeGroup, .paginate').slideDown();
				$(this).attr({ src: 'http://netdrive.bobcat.com/shared/button_collapse.png', title: 'collapse' });
				$('.btn-toggle').ifixpng();
			});
	},

	sort: function(catId, categoryItems) { // get first and last item from group for pagination
		$('#' + catId).children('.group').each(function() {
			if ($(this).is('.activeGroup')) {
				var firstItemId = $(this).find('h4:first').attr('id');
				var firstItemId = firstItemId.split('-');
				firstItem = firstItemId[1];
				var lastItemId = $(this).find('h4:last').attr('id');
				var lastItemId = lastItemId.split('-');
				lastItem = lastItemId[1];
				previousGroup = $(this).prev().attr('id'); // get previous group to display
				nextGroup = $(this).next().attr('id'); // get next group to display
				jCat.paginate(catId, categoryItems, firstItem, lastItem, previousGroup, nextGroup);
			}
		});
	},

	paginate: function(catId, categoryItems, firstItem, lastItem, previousGroup, nextGroup) { // display pagination
		if (categoryItems <= 4) { // no need for pagination
			var paginateHTML = '';
		} else if (firstItem <= 4 && categoryItems >= 5) { // add next link
			var paginateHTML = '<p class="paginate">Viewing ' + firstItem + '-' + lastItem + ' of ' + categoryItems + '&nbsp;&nbsp;<a href="#' + nextGroup + '" class="next">Next<\/a><\/p>';
		} else if (firstItem > 4 && lastItem < categoryItems) { // add previous and next links
			var paginateHTML = '<p class="paginate">Viewing ' + firstItem + '-' + lastItem + ' of ' + categoryItems + '&nbsp;&nbsp;<a href="#' + previousGroup + '" class="previous">Previous<\/a> | <a href="#' + nextGroup + '" class="next">Next<\/a><\/p>';
		} else if (firstItem == categoryItems) { // reached the end and there was only one item, add previous link
			var paginateHTML = '<p class="paginate">Viewing ' + firstItem + ' of ' + categoryItems + '&nbsp;&nbsp;<a href="#' + previousGroup + '" class="previous">Previous<\/a><\/p>';
		} else if (firstItem > 4 && lastItem == categoryItems) { // reached the end, add previous link
			var paginateHTML = '<p class="paginate">Viewing ' + firstItem + '-' + lastItem + ' of ' + categoryItems + '&nbsp;&nbsp;<a href="#' + previousGroup + '" class="previous">Previous<\/a><\/p>';
		}
		if ($('#' + catId).children().is('.paginate')) {
			$('#' + catId).children('.paginate').replaceWith(paginateHTML);
		} else {
			$('#' + catId).append(paginateHTML);
		}
		jCat.flip(catId, categoryItems);
	},

	flip: function(catId, categoryItems) {
		$('#' + catId + ' .paginate a').click(function() {
			var flipGroupId = $(this).attr('href');
			var flipGroupId = flipGroupId.split('#'); // fix for IE href value
			var flipGroup = flipGroupId[1];
			$('#' + flipGroup).siblings().removeClass('activeGroup');
			$('#' + flipGroup).addClass('activeGroup');
			$('#' + flipGroup).fadeIn().siblings("div").hide();
			jCat.sort(catId, categoryItems); // re-initialize displayed group to update pagination
			return false;
		});
	}
}

var tToggle = { // specifications table toggle
	
	setTabs: function() {
		// assign ids to tables and hide them
		$('.tabletoggle table').each(function(i) {
			$(this).attr('id','toggletable' + i).hide();
		});
		$('.tabletoggle table:first').show();
		
		// create and place new elements for tabs
		$('.tabletoggle').prepend('<div class="tabbar"></div>');
		$('.tabletoggle h3').each(function() {
			var tablabel = $(this).text();
			$('.tabbar').append('<a href="#" class="toggletab-off"><span>' + tablabel + '</span></a>');
			$(this).remove();
		});
		$('.tabbar a:first').addClass('toggletab-on');
		
		// toggle tables and highlight active tab
		$('.toggletab-off').each(function(i) {
			$(this).click(function() {
				$(this).addClass('toggletab-on').siblings('a').removeClass('toggletab-on');
				$('#toggletable' + i).siblings('table').hide();
				$('#toggletable' + i).show(); return false;
			});
		});
	}
}

var mediaWidget = { // media widget chooser

	selectMedia: function() {
		$("#media_widget_chooser").change(function() {
			var myAtt = $(this).find("option:selected").attr("class");
			$("#media_widget").slideUp(function() {
				$(this).empty();
				$(this).load("/publicadmin/elements/" + myAtt + ".css", function() { $(this).slideDown(); tb_init('a.thickbox, area.thickbox, input.thickbox'); });
			});
		});
	}
}
						
function updateSICValue() {
    var sicValue = readCookie('_sic');
    if (sicValue != null) {
        var sicElement = document.getElementById('Sic');
        sicElement.setAttribute('value', sicValue);
    }
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}