var cf_interval = 5000;
var selected = 0;
var flip;

$(document).ready(function(){
	initCrossfade();
	$("#top_links").superfish();
	initHomePage();
	initSearch();
	initAccordion();
	initTabs();
	initSearchResults();
	initForms();
	initProducts();
	initFAQ();
	initTables();
	initCleanUp();
	initSitemap();
	initFeedbackForms();
	initBookmarks();
});

function initBookmarks(){
	var hash = window.location.hash;
	if(hash != ""){
		var tabs = $("#tabs .ui-tabs-nav a");
		
		var tokens = hash.split('#tab=');
		if(tokens.length == 2){
			hash = '#' + tokens[1];
		}
		
		$(tabs).each(function(){
			if(hash == $(this).attr("href")){
				$(this).trigger('click');
			}
		});
		
		
		
	}
	
}

function initSitemap(){
	$("#sitemap #col2 li.primary:odd").appendTo("#col3 ul");
}

function initCleanUp(){
	$("#extendable_sidebox ul").each(function(){
		if($("li", this).length == 0){
			$("#extendable_sidebox").remove();
		}
	});
}

function initTables(){
	$("table.center").each(function(i){
		var masterID = "table_" + i;
		var table = $(this);
		var cells = $("td", table);
		var rows = $("tr", table);
		if($(table).hasClass('center_1')){
			$(rows).each(function(){
				var cells = $("td,th", $(this));
				$(cells).each(function(i){
					if(i == 0){
						$(this).css('text-align', 'center');
					}
				});
			});
		}
		
		if($(table).hasClass('center_2')){
			$(rows).each(function(){
				var cells = $("td,th", $(this));
				$(cells).each(function(i){
					if(i == 1){
						$(this).css('text-align', 'center');
					}
				});
			});
		}
		
		if($(table).hasClass('center_3')){
			$(rows).each(function(){
				var cells = $("td,th", $(this));
				$(cells).each(function(i){
					if(i == 2){
						$(this).css('text-align', 'center');
					}
				});
			});
		}
		
		if($(table).hasClass('center_4')){
			$(rows).each(function(){
				var cells = $("td,th", $(this));
				$(cells).each(function(i){
					if(i == 3){
						$(this).css('text-align', 'center');
					}
				});
			});
		}
		
		if($(table).hasClass('center_5')){
			$(rows).each(function(){
				var cells = $("td,th", $(this));
				$(cells).each(function(i){
					if(i == 4){
						$(this).css('text-align', 'center');
					}
				});
			});
		}
		
		if($(table).hasClass('center_6')){
			$(rows).each(function(){
				var cells = $("td,th", $(this));
				$(cells).each(function(i){
					if(i == 5){
						$(this).css('text-align', 'center');
					}
				});
			});
		}
		
		
		var currentIndex = 0;
		
		/*
$(rows).each(function(){
			var headings = $("th", this);
			if(headings.length > 0){
				currentIndex++;
				$(this).attr("id", masterID + "_toggle_" + currentIndex);
				$(this).addClass('toggler');
			} else {
				$(this).attr("class", masterID + "_toggle_" + currentIndex);
				$(this).hide();
			}
			
		});
		
		var togglers = $(".toggler", this);
		$(togglers).each(function(i){
			$(this).click(function(e){
				var id = $(this).attr('id');
				$("." + id).toggle();
			});
			
		});
		
		if(i == 0){
			$(".toggler:first", this).trigger('click');
		}
*/

	
	});
	
	
	
}

function initFAQ(){
	
		$(".question, .answer").hide();
	
		$(".faqs .ui-tabs-panel, #tabs .faqs").each(function(){
			
			var questions = $(".question", this);
			var answers = $(".answer", this);
			if(questions.length > 0){
				$(this).prepend("<ol class='questions'></ol>");
			}
			var ol = $("ol.questions", this);
			$(questions).each(function(i){
				var question = $(this).text();
				var answer = answers[i];
				answer = $(answer).html();
				$(ol).append("<li class='li_question'><a href='#'>" + question + "</a><div class='answer'>" + answer + "</div></li>");
			});
			
			var parent = $(this);
			
			$(".questions li a", this).each(function(i){
			
				$(this).click(function(e){
					e.preventDefault();
					$(".answer").hide();
					$(".question").hide();
					//$(".answer:eq(" + i + ")", parent).show();
					//$(".question:eq(" + i + ")", parent).show();
					//$("#wrapper").animate({ scrollTop: $("#wrapper").attr("scrollHeight") }, 3000);
					$(this).parents('li.li_question').find('.answer').show();
				});
			
			});
			
		});
		
		
}

function initProducts(){
	
	$(".product").height('auto');
	$(".product_row").each(function(){
		var rowHeight = 0;
		$(".product", this).each(function(){
			if($(this).height() > rowHeight){
				rowHeight = $(this).height();
			}
			//$(this).height(rowHeight);
		});
		
		var indiv = $(".product", this).height(rowHeight);
		if(indiv.length == 2){
			$(indiv).width("250px");
		}
		
	});
}

$(window).load(function(){
	startCrossFade();
	$(".prompt").focus(function(e){
		$(this).css('background', 'white');
	});
});

function initForms(){
	
	$("#subscription-form").submit(function(e){
		var ids = new Array();
		var required = $(".required", this).parents('label');
		$(required).each(function(){
			var field = $('input', this);
			
			if(field.length == 0){
				field = $('textarea', this);
			}
			
			if($(field).val() == ""){
				ids.push("#" + $(field).attr('id'));
			}
			
		});
	
		var selectors = "";
	
		if(ids.length > 0){
			selectors = ids.join(',');
			e.preventDefault();
		} else {
			
			if(!isValidEmailAddress($('#subscribe_email').val())){
				selectors = "#subscribe_email";
				e.preventDefault();
			}
		}
		
		
		
		$(selectors).animate({
			backgroundColor: '#ff0000'
		}).animate({
			backgroundColor: '#ffffff'
		});
	
	});
		
}

function initFeedbackForms(){

	$("#feedback-form").submit(function(e){

		var ids = new Array();
		var ids_selects = new Array();
		//var select_selectors = new Array();
		var required = $(".req", this).parents('label');
		$(required).each(function(){
			var field = $('input', this);
			var add = 'true';
			if(field.length == 0){
				field = $('textarea', this);
				if(field.length == 0){
					field = $('select', this);
					add = 'false';
				}
			}
			
			if($(field).val() == ""){
				ids.push("#" + $(field).attr('id'));
			}
			
			
			
		});
	
		var selectors = "";
		var error_message = "";

	
		if(ids.length > 0){
			selectors = ids.join(',');
			error_message = $(ids[0]).attr('title');
			$(ids[0]).focus();
			e.preventDefault();
		} else {
			
			if($('#email').val() != "" && !isValidEmailAddress($('#email').val())){
				selectors = "#email";
				e.preventDefault();
			}
			
			
			
		}
		
		if(error_message != ""){
			alert(error_message);
		}
		
		//$(selectors).hint();
		
		//$(selectors).css('background-color', '#ff0000');
		//$(select_selectors).css('color', '#ff0000');
		//alert(selectors);
		//setTimeout("highlightErrors('" + selectors + "', '" + select_selectors + "')", 500);	
		

	
	});
}

function highlightErrors(selectors, select_selectors){
	$(selectors).animate({
		backgroundColor: '#ffffff'
	}, 1000);
	
	/*
$(select_selectors).animate({
		color: '#000000'
	}, 1000);
*/
}



function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function initSearchResults(){
	
	$(".ajaxSearch_result:odd").addClass('ajaxSearch_result_odd');
	
}

function initTabs(){
	
	$("#tabs").tabs();
	
	
	$('#tabs').bind('tabsselect', function(event, ui) {
		setTimeout(function(){
			initProducts();
			var tab = $(ui.tab);
			var url = $(tab).attr('href');
			window.location.hash = "#tab=" + url.replace(/#/, '');
			event.stopPropagation();
			return false;
		}, 500);
    });
	
}


function initAccordion(){
	$("#main_nav li a.primary").addClass('followDirect');
	//kill any empties.
	$("ul.secondary").each(function(){
		
		if($("a", this).length == 0){
			$(this).parents('li.primary').find('a.primary').addClass('followDirect');
			$(this).remove();
		}
	});

	$("#support_nav li a.primary").addClass('followDirect');

	$('.accordion ul.primary ul').hide();
	$('.accordion li.selected ul').show();
	$('.accordion li a.primary').click(function(e) {
		
		if($(this).hasClass('followDirect')){
			
		} else {
			var parent = $(this).parents('.accordion');
			var checkElement = $(this).next();
			$('li a.primary', parent).removeClass('active');
			$(this).addClass('active');
			if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
				return false;
			}
			if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
				$('.accordion ul.primary ul:visible').slideUp('normal');
				checkElement.slideDown('normal');
				return false;
			}
		
		}
	});

}

function initSearch(){
	$('#search_form').hint();
}

function initHomePage(){
	
		
	$(".resource a.toggler").hover(function(e){
		e.preventDefault();
		if($(this).hasClass('active')){
			//just ignore this click.
		} else {
			var id = "#intro_" + $(this).attr('id');
			$(".introtext").hide();
			$(id).show();
			$(".resource a").removeClass('active');
			$(this).addClass('active');
		}
	}, function(){
	
	});

	
	$(".resource a.toggler:eq(0)").trigger('mouseenter');
	
	$("div.hover").hover(function(){
		$(this).addClass('hovered');
	}, function(){
		$(this).removeClass('hovered');
	});
	
	var height = $("div.hover").height();
	
	$("div.hover").each(function(){
		
		var content = $(".expander_content", this);
		var gap = (height - $(content).height()) / 2;
		$(content).css('padding-top', gap);
		
	});
	
	//begin the on demand icon sequence.
	/*
var icons = $("#on_demand_services li");
	$(icons).clone().appendTo("#on_demand_services");
	
	
	if(icons.length > 5){
		flip2 = setInterval("swapIcons()", 3000);
	}
*/

	
}

var flip2;

function swapIcons(){
	
	var left = $("#on_demand_services li:first").outerWidth();
	
	$("#on_demand_services").animate({
		left: '-' + left + 'px'
	}, 1500, 'linear', function(){
	
		$("#on_demand_services").css('left', '0px');
		$("#on_demand_services li:first").appendTo('#on_demand_services');
		
		
	});
	
}


function initCrossfade(){
	
	$("#crossfader div.section").each(function(i){
		if(i > 0){
			$(this).css('opacity', 0).css('left', '-10000px');
			$(this).removeClass('atStart');
		} else {
			$(this).addClass('active');
			$(this).removeClass('atStart');
		}
		
	});
	
	$("#crossfader div.section").each(function(i){
		$("#indicator").append("<a href='#' class='' onclick='interruptCrossfade(" + i + ");return false;'>" + i +"</a>");
	});
	
	$("#indicator").append("<div style='clear: both'></div>");
	
	var left = (960 - $("#indicator").width()) / 2;
	
	$("#indicator").css('left', left);
	
	updateCrossfadeCrumbs(selected);
	
}


function startCrossFade(){
	flip = setInterval("crossfade()", cf_interval);
}

function interruptCrossfade(index){
	if(selected == index){
		//ignore it, but kill the interval.
		clearInterval(flip);
	} else {
		index--;
		selected = index;
		clearInterval(flip);
		crossfade();
	}
}

function updateCrossfadeCrumbs(index){
	$("#indicator a").removeClass('current');
	$("#indicator a:eq(" + index + ")").addClass('current');
}

function crossfade(){
	var images = $("#crossfader div.section");
	var total = images.length;
	
	if(selected + 1 == total){
		nextIndex = 0;
	} else {
		nextIndex = selected + 1;
	}
	
	$("#crossfader div.active").animate({
		opacity: 0
	}, 'slow', 'swing', function(){
		$(this).css('left', '-10000px');
	});
	
	$("#crossfader div.section").removeClass('active');
	var nextImage = $("#crossfader div.section:eq(" + nextIndex + ")");
	
	$(nextImage).css('left', '0px');
	
	$(nextImage).animate({
		opacity: 1
	}, 'slow').addClass('active');
	
	
	selected = nextIndex;
	
	updateCrossfadeCrumbs(selected);
	
}



/*
 * Superfish v1.4.8 - jQuery menu widget
 * Copyright (c) 2008 Joel Birch
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 * CHANGELOG: http://users.tpg.com.au/j_birch/plugins/superfish/changelog.txt
 */

;(function($){
	$.fn.superfish = function(op){

		var sf = $.fn.superfish,
			c = sf.c,
			$arrow = $(['<span class="',c.arrowClass,'"> &#187;</span>'].join('')),
			over = function(){
				var $$ = $(this), menu = getMenu($$);
				clearTimeout(menu.sfTimer);
				$$.showSuperfishUl().siblings().hideSuperfishUl();
			},
			out = function(){
				var $$ = $(this), menu = getMenu($$), o = sf.op;
				clearTimeout(menu.sfTimer);
				menu.sfTimer=setTimeout(function(){
					o.retainPath=($.inArray($$[0],o.$path)>-1);
					$$.hideSuperfishUl();
					if (o.$path.length && $$.parents(['li.',o.hoverClass].join('')).length<1){over.call(o.$path);}
				},o.delay);	
			},
			getMenu = function($menu){
				var menu = $menu.parents(['ul.',c.menuClass,':first'].join(''))[0];
				sf.op = sf.o[menu.serial];
				return menu;
			},
			addArrow = function($a){ $a.addClass(c.anchorClass).append($arrow.clone()); };
			
		return this.each(function() {
			var s = this.serial = sf.o.length;
			var o = $.extend({},sf.defaults,op);
			o.$path = $('li.'+o.pathClass,this).slice(0,o.pathLevels).each(function(){
				$(this).addClass([o.hoverClass,c.bcClass].join(' '))
					.filter('li:has(ul)').removeClass(o.pathClass);
			});
			sf.o[s] = sf.op = o;
			
			$('li:has(ul)',this)[($.fn.hoverIntent && !o.disableHI) ? 'hoverIntent' : 'hover'](over,out).each(function() {
				if (o.autoArrows) addArrow( $('>a:first-child',this) );
			})
			.not('.'+c.bcClass)
				.hideSuperfishUl();
			
			var $a = $('a',this);
			$a.each(function(i){
				var $li = $a.eq(i).parents('li');
				$a.eq(i).focus(function(){over.call($li);}).blur(function(){out.call($li);});
			});
			o.onInit.call(this);
			
		}).each(function() {
			var menuClasses = [c.menuClass];
			if (sf.op.dropShadows  && !($.browser.msie && $.browser.version < 7)) menuClasses.push(c.shadowClass);
			$(this).addClass(menuClasses.join(' '));
		});
	};

	var sf = $.fn.superfish;
	sf.o = [];
	sf.op = {};
	sf.IE7fix = function(){
		var o = sf.op;
		if ($.browser.msie && $.browser.version > 6 && o.dropShadows && o.animation.opacity!=undefined)
			this.toggleClass(sf.c.shadowClass+'-off');
		};
	sf.c = {
		bcClass     : 'sf-breadcrumb',
		menuClass   : 'sf-js-enabled',
		anchorClass : 'sf-with-ul',
		arrowClass  : 'sf-sub-indicator',
		shadowClass : 'sf-shadow'
	};
	sf.defaults = {
		hoverClass	: 'sfHover',
		pathClass	: 'overideThisToUse',
		pathLevels	: 1,
		delay		: 200,
		animation	: {opacity:'show'},
		speed		: 'normal',
		autoArrows	: true,
		dropShadows : true,
		disableHI	: false,		// true disables hoverIntent detection
		onInit		: function(){}, // callback functions
		onBeforeShow: function(){},
		onShow		: function(){},
		onHide		: function(){}
	};
	$.fn.extend({
		hideSuperfishUl : function(){
			var o = sf.op,
				not = (o.retainPath===true) ? o.$path : '';
			o.retainPath = false;
			var $ul = $(['li.',o.hoverClass].join(''),this).add(this).not(not).removeClass(o.hoverClass)
					.find('>ul').hide().css('visibility','hidden');
			o.onHide.call($ul);
			return this;
		},
		showSuperfishUl : function(){
			var o = sf.op,
				sh = sf.c.shadowClass+'-off',
				$ul = this.addClass(o.hoverClass)
					.find('>ul:hidden').css('visibility','visible');
			sf.IE7fix.call($ul);
			o.onBeforeShow.call($ul);
			$ul.animate(o.animation,o.speed,function(){ sf.IE7fix.call($ul); o.onShow.call($ul); });
			return this;
		}
	});

})(jQuery);

/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/

(function ($) {

$.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }
    
  return this.each(function () {
    // get jQuery version of 'this'
    var $input = $(this),
    
    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = $(this.form),
      $win = $(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title
      
      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};

})(jQuery);

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);


