var ie6 = false;
var _CONTENT_CATEGORY_SUFFIX = "";
var _PAGE_NAME = "";

var curMonth;
var curYear;

// workaround for use of unsupported 'indexOf' in IE
if (!Array.indexOf)
{
	Array.prototype.indexOf = function (obj)
	{
		for (var i = 0; i < this.length; i++)
		{
			if (this[i] == obj)
			{
				return i;
			}
		}
		return -1;
	};
}



/*************************************************************
SETUP
*************************************************************/

jQuery(document).ready(function ()
{
	searchOverlabel();
	writeFeature();

	if (jQuery(document).find("div#locations-map-container").size() >= 1)
	{
		_PAGE_NAME = "/data/locations.xml/";
		writeMapSwf();
	};


	//workaround to fire the powerfilter buttons in case user hits enter key
	jQuery(document).keypress(function (e)
	{
		if ((e.which && e.which == 13) || (e.keyCode &&
e.keyCode == 13))
		{
			//alert('h');
			if (jQuery("#beginSearch").is(":visible"))
			{
				e.preventDefault();
				jQuery("#viewResults").focus();
				jQuery("#viewResults").click();
			} else if (jQuery("#endSearch").is(":visible"))
			{
				e.preventDefault();
				jQuery("#searchAgain").focus();
				jQuery("#searchAgain").click();
			} else
			{
				e.preventDefault();
				jQuery("#search-button").click();
			}

		}
	});


});

function stopSpotlightSlide()
{
	jQuery('#caro').trigger("pause");
}

function writeSpotlight(autoSliding)
{
	jQuery("#caro").carouFredSel({
		width: 375,
		height: 150,
		items: {
			visible: 1,
			start: 0
		},
		scroll: {
			pauseOnHover: true
		},
		auto: {
			play: autoSliding,
			pauseDuration: 5000
		},
		pagination: {
			container: ".spotlightPaginationDyn",
			anchorBuilder: function (nr)
			{
				return "<li class='rightBorder'><a href='#'>" + nr + "</a></li>";
			}
		}
	});
	jQuery(".spotlightPaginationDyn li").last().removeClass("rightBorder");
}

function stopFeatureSlide()
{
	jQuery('#caroFeature').trigger("pause");
}

function writeFeature()
{
	jQuery("#caroFeature").carouFredSel({
		width: "auto",
		height: "auto",
		items: 1,
		auto: {
			play: true,
			pauseDuration: 9000
		},
		scroll: {
			fx: "fade",
			pauseOnHover: true,
			queue: false,
			easing: "easeInOutExpo",
			duration: 100
		},
		pagination: {
			container: ".featurePagination .buttons",
			anchorBuilder: function (nr)
			{
				return '<a href="#">' + nr + '</a>';
			}
		},
		next: {
			button: ".featurePagination .button.next"
		}
	});
	jQuery('.featurePagination .buttons').append('<div class="clear"></div>');
}

function writeMapSwf()
{
	var swf = "/flash/locations_map.swf";
	var id = "locationsmap";
	var width = "745";
	var height = "400";
	var fpVersion = "8";
	var bgColor = "#FFFFFF";

	var so = new SWFObject(swf, id, width, height, fpVersion, bgColor);
	if (flashVersionIsValid(so))
	{
		so.addParam("wmode", "opaque");

		var autoSelectRegion;
		if (language == "en-uk") autoSelectRegion = "Europe";
		else autoSelectRegion = "North America";
		so.addVariable("autoSelectRegion", encodeURIComponent(autoSelectRegion));

		var segment3Input = jQuery("segment_3");
		if (segment3Input)
		{
			so.addVariable("autoSelectLocation", encodeURIComponent(segment3Input.value));
		}

		so.write("locations-map-container");
	}
	else
	{
		writeNoflashHTML("locations-map-container");
	}
}

var imagesToPreload =
[
"/images/site/header/nav/dropdown_background.png",
"/images/site/header/nav/dropdown_shadow.png",
"/images/site/header/biz_nav_background.png",
"/images/site/header/search_input_focus_background.gif"
];


/*************************************************************
UTILITY FUNCTIONS
*************************************************************/

function validateSearchForm()
{
	var keywords = jQuery("search-input").value;
	if (keywords.value == "")
	{
		return false;
	}
	else if (keywords.length < 3)
	{
		alert("Search terms must be at least 3 characters in length");
		return false;
	}
	else
	{
		return true;
	}
	//return( jQuery( "search-input" ).value != "" );
}

function flashVersionIsValid(so)
{
	return (so.installedVer.versionIsValid(so.getAttribute("version")));
}

function searchAndReplace(haystack, search, replace)
{
	if (search != replace)
	{
		while (haystack.indexOf(search) != -1)
		{
			var index = haystack.indexOf(search);
			haystack =
			(
			haystack.substring(0, index) +
			replace +
			haystack.substring((index + search.length), haystack.length)
			);
		}
	}
	return haystack;
}

function searchAndDestroy(haystack, search)
{
	return searchAndReplace(haystack, search, "");
}

function writeNoflashHTML(flashContainerID)
{
	var flashContainer = jQuery(flashContainerID);
	if (!flashContainer) return;
	var noflashHTML = flashContainer.innerHTML;
	noflashHTML = searchAndDestroy(noflashHTML, "<noscript>");
	noflashHTML = searchAndDestroy(noflashHTML, "</noscript>");
	noflashHTML = searchAndReplace(noflashHTML, "<span class=\"tohide\">", "<span class=\"hide\">");
	flashContainer.innerHTML = noflashHTML;
}

function cleanse(str)
{
	if (!str) return "";

	var oldstr = str;

	// Strip excluded chars from edges
	var allowedChars = "abcdefghijklmnopqrstuvwxyz0123456789ÃœÃ¼Ã¤Éé’èêçóíáñéúÓÍÚÉÑÁßÜÖÄäöü'";
	for (var i = 0; i < str.length; i++)
	{
		if (allowedChars.indexOf(str.charAt(i).toLowerCase()) != -1)
		{
			str = str.substring(i);
			break;
		}
	}
	for (var i = (str.length - 1); i >= 0; i--)
	{
		if (allowedChars.indexOf(str.charAt(i).toLowerCase()) != -1)
		{
			str = str.substring(0, (i + 1));
			break;
		}
	}

	// Remove all other excluded chars
	allowedChars += "&/_. ";
	var newstr = "";
	for (var i = 0; i < str.length; i++)
	{
		var char = str.charAt(i);
		if (allowedChars.indexOf(char.toLowerCase()) != -1)
		{
			newstr += char;
		}
	}

	newstr = searchAndReplace(newstr, "  ", " ");
	newstr = searchAndReplace(newstr, "<em>", "");
	newstr = searchAndReplace(newstr, "</em>", "");

	return (newstr);
}



/*************************************************************
DOM LOAD FUNCTIONS
*************************************************************/



function searchOverlabel()
{

	jQuery("#search-form").addClass('overlabel');


	jQuery("#search-label").click(function ()
	{
		jQuery("#search-input").focus();
		jQuery("#search-form").addClass("focus");
	});

	jQuery("#search-input").click(function ()
	{
		jQuery("#search-form").addClass("focus");
		jQuery("#search-button").bind('click', searchButtonClick);
	});

	jQuery("#search-input").blur(function ()
	{
		if (jQuery(this).val() == "")
		{
			jQuery("#search-form").removeClass("focus");
			jQuery("#search-button").unbind('click');


		}

		if (jQuery("#search-form").val() != "")
		{
			//  jQuery("#search-input").focus();
		}
	});



	//jQuery("#search-button").click(function () {
	//     jQuery(window.location).attr('href', '/search/?q=' + jQuery("#search-input").val());
	//  return false;
	// });


}

function searchButtonClick()
{
	jQuery(window.location).attr('href', '/search/?q=' + jQuery("#search-input").val());
	return false;
}

function state_Change()
{
	if (xmlhttp.readyState == 4)
	{
		if (xmlhttp.status == 200)
		{


		}
		else
		{
			alert("Problem retrieving XML data");
		}
	}
}


function preloadImages()
{
	imagesToPreload.each(function (imageSrc)
	{
		new Image().src = imageSrc;
	});
}

var popwindow;
function popup(url, name, options)
{
	newwindow = window.open(url, name, options);
	if (window.focus) { newwindow.focus();
	}
}


/*************************************************************
DOM LOAD HANDLER
*************************************************************/

var windowLoadFunctions = [ preloadImages ];

/****************************************************
TOOLTIPS
*****************************************************/

(function ($)
{
	$.fn.colorTip = function(settings) {
		var defaultSettings = { color: 'colorTipYellow', timeout: 100 };

		/* Combining the default settings object with the supplied one */
		settings = $.extend(defaultSettings, settings);

		/*
		*	Looping through all the elements and returning them afterwards.
		*	This will add chainability to the plugin.
		*/
		return this.each(function() {
			var elem = $(this);

			// Creating new eventScheduler and Tip objects for this element.
			// (See the class definition at the bottom).
			var scheduleEvent = new eventScheduler();
			var tip = new Tip(settings.content);

			// Adding the tooltip markup to the element and
			// applying a special class:
			elem.append(tip.generate()).addClass('colorTipContainer');

			var hasClass = elem.hasClass(settings.color);
			if (!hasClass) 
				elem.addClass(settings.color);

			// On mouseenter, show the tip, on mouseleave set the
			// tip to be hidden in half a second.
			elem.hover(function() {
				tip.show();

				// If the user moves away and hovers over the tip again,
				// clear the previously set event:
				scheduleEvent.clear();

			}, function() {
				// Schedule event actually sets a timeout (as you can
				// see from the class definition below).
				scheduleEvent.set(function() {
					tip.hide();
				}, settings.timeout);
			});
			
			return true;
		});
	};

	/*
	/	Event Scheduler Class Definition
	*/
	function eventScheduler() { }

	eventScheduler.prototype = {
		set: function (func, timeout)
		{
			// The set method takes a function and a time period (ms) as
			// parameters, and sets a timeout
			this.timer = setTimeout(func, timeout);
		},
		clear: function ()
		{
			// The clear method clears the timeout
			clearTimeout(this.timer);
		}
	}; 
	
	/*
	/	Tip Class Definition
	*/
	function Tip(txt)
	{
		this.content = txt;
		this.shown = false;
	}

	Tip.prototype = {
		generate: function ()
		{

			// The generate method returns either a previously generated element
			// stored in the tip variable, or generates it and saves it in tip for
			// later use, after which returns it.

			return this.tip || (this.tip = $('<span class="colorTip">' + this.content +
											 '<span class="pointyTipShadow"></span><span class="pointyTip"></span></span>'));
		},
		show: function ()
		{
			if (this.shown) return;

			// Center the tip and start a fadeIn animation
			this.tip.css('margin-left', -this.tip.outerWidth() / 2).fadeIn('fast');
			this.shown = true;
		},
		hide: function ()
		{
			this.tip.fadeOut('fast');
			this.shown = false;
		}
	};
})(jQuery);

(function ()
{
	jQuery(document).ready(function ()
	{
		jQuery('.pageElement.form .formRow').each(function () {
			var formRow = jQuery(this);
			if (formRow.has('.help').length) {
				var content = formRow.find('.help').html();
				formRow.colorTip({ color: 'colorTipYellow', content: content });
			}
		});
	});
})();
