//fix background image flickering in IE

/*@cc_on 
	@if (@_win32)
	try {
	  document.execCommand('BackgroundImageCache', false, true);
	} catch(e) {}
	@end
@*/
//flash map Adam Bankin

var _$=function(id){return document.getElementById(id);};var populateDropdown=function(o){var el=_$(o.selectId);for(var i=Number(0),j=Number(el.length);i<j;i++){if(el.options[i].text==o.region){el.selectedIndex=i;break;}}};var getURL=function(o){var el=_$(o.selectId);for(var i=Number(0),j=Number(el.length);i<j;i++){if(el.options[i].text==o.region){break;}}
window.location=el.options[i].value;};var populateTitle=function(o){var el=_$(o.titleId);while(el.firstChild){el.removeChild(el.firstChild);}
el.appendChild(document.createTextNode(o.region));};var receiveFlash=function(o){getURL(o);};var sendFlash=function(o){if(o.region!="--select--"){_$(o.id)[o.func](o.region);populateTitle(o);}else{o.region="Select a region...";populateTitle(o);}};

//FCfunctions Fazal Khan
var FCfunctions = {
datepicker : function(o) { 
		var thepicker = o.picker;
		$(thepicker).datepicker({showOn: 'both', buttonImage: 'calendar.gif', buttonImageOnly: true});
},
accordian : function(o){
		var $element = o.element;
		var $content = o.content;	
		var $activeClass = o.activeClass;
		$($element).find(":header").removeClass($activeClass).next($content).hide();		
		$($element).each(function (){
			$(this).find(":header").bind("click", function(){				
				var $heading = $(this);
				var $next = $heading.next($content);					
				if($next.is(":visible")){
					$next.slideUp("fast");
					$heading.removeClass($activeClass);
				} else {
					$next.slideDown("fast");
					$heading.addClass($activeClass);
				}				
			})
		})
},
advancedsearch : function(o){
		$("#filter-results").submit(function(){
			var $inputs = $(".ajax-search, input:checked").serialize();
			var $loading =  o.loading;
			var $success = true;
			var $errormessage = o.errormessage;
			$.ajax({
				url: this.action,
				type: "POST",
   				data: $inputs,
				dataType: "html",
				beforeSend: function(){
					$(".module-15.search").animate({"opacity":"toggle"},300);
					if($(".module-15.search:hidden")){
						$(".span-2.right").append($loading);
					}
				},
				error: function(){
					$(".module-15.search").animate({"opacity":"toggle"},500);
					if(!$("#ajax-error").length){
						$(".module-15.search").prepend("<div id=\"ajax-error\">"+$errormessage+"</div>");
					}
					$("#loading").remove();
					$success = false;
				},
  				success: function(response){
					if($("#loading:visible")){
						$("#loading").animate({"opacity":"toggle"},300);
						$(".module-15.search").html(response);
					}
					$success = true;
   				},
				complete: function(){
					if ($success){
						$(".module-15.search").animate({"opacity":"toggle"},500);
						$("#loading").remove();
					}
				}
 			});
			return false;
		 })
},
calendar : function(){
		$(".get-month").bind("click", function(){
			var $month = "month="+$(this).attr("rel");
			var $link = $(this).attr("href");
			var $loading =  '<div id="loading"></div>';
			var $success = true;
			var $errormessage = "sorry there was an error, please try again";
			$.ajax({
				url: $link,
				type: "POST",
				data: $month,
				dataType: "html",
				beforeSend: function(){
					$("#datepicker").animate({"opacity":"toggle"},300);
					if($("#datepicker:hidden")){
						$("#datepicker").append($loading);
					}
					
				},
				error: function(){
					$("#datepicker").animate({"opacity":"toggle"},300);
					if(!$("#ajax-error").length){
						$("#datepicker").prepend("<div id=\"ajax-error\">"+$errormessage+"</div>");
					}
					$("#loading").remove();
					$success = false;
				},
				success: function(response){
					if($("#loading:visible")){
						$("#loading").animate({"opacity":"toggle"},300);
						$("#datepicker").html(response);
						
					}
					
					$success = true;
   				},
				complete: function(){
					if ($success){
						$("#datepicker").animate({"opacity":"toggle"},300);
							$("#loading").remove();
							FCfunctions.tooltip({container :"td.feature", tooltip : ".tooltip-wrapper", delay:500, inspeed:300,outspeed:100});
							FCfunctions.calendar();
					}
				}
 			});
			return false;
		})
},
tooltip : function(o){
		var $_timeout;
		var $_delay = 500;
		/* COMMENTED OUT TO MAKE OUR TOOL TIPS WORK. GUESS WE DID IT DIFFERENTLY
			$(".feature a").bind("click", function(){
      		return false
    	}); */
		$(o.container).bind("mouseenter focus", function(){
				var $_this = this;
				$(this).css({"cursor":"help"});	
				$_timeout = setTimeout( function (){
										$($_this).children(o.tooltip).animate({"opacity": "toggle"},o.inspeed, 'swing', function(){	

										});
							}, $_delay);
				
		}).bind("mouseleave blur", function(){
				clearTimeout($_timeout);
				$(this).children(o.tooltip+":visible").animate({"opacity": "toggle"}, o.outspeed);
		});	
},
scroller : function(o){
		var $scrollWrapper = $(o.scrollWrapper);
		$(o.itemsList).css("position","absolute");
		var $scrollItemWidth = $(o.items).width() +o.scrollPadding;
		var $scrollTotalItems = $(o.items).length;
		var $totalWidth = ($scrollTotalItems*$scrollItemWidth);
		var $viewableArea = $(o.scrollWrapper).width();
		var $maxValue = ($totalWidth-$viewableArea);
		($scrollTotalItems > o.minValue) ? enableSlider() : $scrollWrapper.css("width","auto");	
		function enableSlider(){
			$(o.itemsList).width($totalWidth);
			$(o.scrollerId).css("display","block");
			$scrollWrapper.height($(o.itemsList).outerHeight());
			var slider = new $.ui.slider($(o.scrollerId)[0],{
						minValue:0,
						maxValue: $maxValue, 
						startValue: 0,
						/*slide: function(e,ui) {
							$(o.itemsList).css({"left": - parseInt((ui.value))});			
						},*/					
						slide: function (ev, ui) {
       						$(o.itemsList).css("left", "-" + parseInt((ui.value)) + "px");
      					}, 
      					stop: function (ev, ui) {
        					$(o.itemsList).animate({ "left" : "-" +parseInt((ui.value)) + "px" }, 500, "linear");
     					 }

			});
			$(o.scrollWrapper).mousewheel(function(event, delta) {
					if (delta > 0)
						slider.moveTo(slider.interaction.curValue+$scrollItemWidth,null,true);
					else if (delta < 0)
						slider.moveTo(slider.interaction.curValue-$scrollItemWidth,null,true);
					return false;
			});
		}
		$(".item").bind("mouseenter focus", function(){
			$(this).addClass("focus");
		}).bind("mouseleave blur", function(){
			$(this).removeClass("focus");
		});
			$(".item").bind("click", function(e){
			//add ajax options here if required
		});		
},
focusfields : function(){
			$("input.text, textarea").bind("focus",function(){
       			 $(this).addClass("focus");
   			});
   			$("input.text, textarea").bind("blur",function(){
        		$(this).removeClass("focus");
   			});
},
formhelp : function(o){
		var $activebubble = false;
		$(o.wrapper).addClass(o.hideClass);
		$(o.mainForm).find(o.helpButton).each(function (){
			var $this = this;
			var $id = $($this).attr(o.attr);
			var $bubble = $($id).addClass(o.showClass).insertAfter($this); 
			$($this).bind("click", function(){
					if ($activebubble != $id){ 
						if ($activebubble){
							$($activebubble).prev(o.helpButton).children("img").attr({src: o.offSrc, alt: o.offSrcAlt});
							$($activebubble).fadeOut(o.outSpeed);	
						}
						$activebubble = $id;
						$($this).children("img").attr({src: o.onSrc, alt: o.onSrcAlt});
						$($id).fadeIn(o.inSpeed);
						//
					} else {
						$($id).fadeOut(o.outSpeed);
						$($this).children("img").attr({src: o.offSrc, alt: o.offSrcAlt});
						$activebubble = false;
					}
					return false;
			});
		});	
},

feature : function(o){
			var $_pausesrc = o.pausesrc;
			var $_playsrc =  o.playsrc;
			var $_prevsrc = o.prevsrc;
			var $_nextsrc = o.nextsrc;
			var $_isplaying = true;
			var $_feature = "#feature";
			if($("#feature .content .item").length > 1){
			$("#feature .strap").append('<div id="controls"><img src="'+$_prevsrc+'" alt="previous" id="previous"/><img src="'+$_pausesrc+'" alt="pause" id="pause"/><img src="'+$_nextsrc+'" alt="next" id="next"/></div>');
			}	
		function onAfter(){
			$('.caption span').text(this.alt);
		}
		$('#feature .content').cycle({ 			
    		fx: 'scrollHorz', 
    		timeout: 8000 ,
			speedIn: 1000,
    		speedOut: 1000,
			next:'#next',
			prev:'#previous',
			after: onAfter
		 });
		$('#pause').bind("click", function(){
			var $_playbutton = $(this);
			if($_isplaying != false){ 
			$('#feature .content').cycle('pause'); 
				$_playbutton.attr({src : $_playsrc});
				$_isplaying = false;	
			} else {
				$('#feature .content').cycle('resume');
				$_playbutton.attr({src : $_pausesrc});
				$_isplaying = true;
			}
		});	
},
tab : function(){
	//find ul.hidden and display:block it then set tab options
		$(".tabs-hidden").addClass("block").tabs( { 
			cache: true, 
			fxSlide: true, 
			fxSpeed: 'fast' 
		});
	//remove the top border (used when js is disabled)	
		$(".module-3 .fragments").css("border-top","none");
		$(".fragments .heading-3").addClass("hidden");
},
fontresize : function(){
		var $_cookie_name = "textsize";
		var $_originalFontSize = $("html").css("font-size");
		var $_date = new Date();
		var $_selected = "";
		var $_str = '<li><div id="text-smaller" class="text-resize">Smaller text</div></li><li><div id="text-reset" class="text-resize">Reset text</div></li><li><div id="text-larger" class="text-resize">Larger text</div></li>';
		$(".screen-controls li").after($_str);
        $_date.setTime($_date.getTime() + 2419200000);//28 days		
		if ($.cookie($_cookie_name)) {
			var $_getSize = $.cookie($_cookie_name);
			/*@cc_on
   				/*@if (@_win32)
      				$("html").css({fontSize : $_getSize});
   				@else @*/
      				$("html").css({fontSize : $_getSize + "px"});
   				/*@end
			@*/
			$("html").css({fontSize : $_getSize});
			if ($_getSize > $_originalFontSize) {
				$("#text-larger").addClass("selected");
				getselected("#text-larger");
			} else if ($_getSize < $_originalFontSize) {
				$("#text-smaller").addClass("selected");
				getselected("#text-smaller");
			}
		} else {
			$.cookie($_cookie_name, $_originalFontSize, { expires : $_date });
		}
		$(".screen-controls").find(".text-resize").each(function(){
			$(this).bind("click", function(){
				var $_currentFontSize = $("html").css("font-size");
				var $_currentFontSizeNum = parseFloat($_currentFontSize, 10);				
					if ( $(this).is("#text-smaller")){
						var $_newFontSize = $_currentFontSizeNum*0.8;
						if ($_newFontSize > 12) {
							$("html").css({fontSize : $_newFontSize});
							$.cookie($_cookie_name, $_newFontSize, { expires : $_date });	
						}
						getselected("#text-smaller");
					} else if ( $(this).is("#text-larger")){
						var $_newFontSize = $_currentFontSizeNum*1.2;
						if ($_newFontSize < 20) {
							$("html").css({fontSize : $_newFontSize});
							$.cookie($_cookie_name, $_newFontSize, { expires : $_date });
						}
						getselected("#text-larger");
					} else	{
						$("html").css({fontSize : $_originalFontSize});
						$.cookie($_cookie_name, $_originalFontSize, { expires : $_date });
						getselected("#text-reset");
					}
			});
		});
		function getselected($_id){
			if($_selected != $_id){
				$($_selected).removeClass("selected");
				$($_id).addClass("selected");
				$_selected = $_id;
			}
		}
},
styleswitcher : function(){
		var $_cookie_name = "contrast";
		var $_cookie = $.cookie($_cookie_name);
       	if ($_cookie) switchstyle($_cookie);
		var $_date = new Date();
		var $_selected = $_cookie;
        $_date.setTime($_date.getTime() + 2419200000);//28 days			
		$('#text-contrast a').bind("click", function(){
				var $_rel = $(this).attr("rel");
				switchstyle($_rel);
                return false;
        });
		function switchstyle($_style)	{
			$('link[@rel*=stylesheet][@title]').each(function(i){
					this.disabled = true;
					if (this.getAttribute('title') != $_selected){
						if (this.getAttribute('title') == $_style) this.disabled = false;
						$.cookie($_cookie_name, $_style, { expires : $_date });
						$_selected = $_style;
						$('#text-contrast a').children("img").attr("src", "text-contrast-reset.gif");
					} else {
						this.disabled = true;
						$.cookie($_cookie_name, null);
						$_selected = "";
						$('#text-contrast a').children("img").attr("src", "text-contrast-high.gif");
					}
			});
		}
	},
	
	navSwitcher : function(){
		var origSrc = [];
		var newSrc = [];
		$("img","#main-nav ul").each(function(i){
			var oSrc = $(this).attr("src");
			imgOn = new Image();
			imgOff = new Image();
			imgOn.src = oSrc;
			imgOff.src = oSrc.split(".")[0]+"-over."+oSrc.split(".")[1];
			origSrc.push(imgOn);
			newSrc.push(imgOff);
			this.i = i;
		});
		$("#main-nav ul").bind("mouseover", function(e){
			if (e.target.src){
				e.target.src = newSrc[e.target.i].src;
			}
			return false;
		}).bind("mouseout", function(e){
			if (e.target.src){
				e.target.src = origSrc[e.target.i].src;
			}
			return false;
		});
	},
	
	
accordian : function(o){
		var $element = o.element;
		var $content = o.content;	
		var $activeClass = o.activeClass;
		$($element).find(":header").removeClass($activeClass).next($content).hide();		
		$($element).each(function (){
			$(this).find(":header").bind("click", function(){				
				var $heading = $(this);
				var $next = $heading.next($content);					
				if($next.is(":visible")){
					$next.slideUp("fast");
					$heading.removeClass($activeClass);
				} else {
					$next.slideDown("fast");
					$heading.addClass($activeClass);
				}				
			})
		})
	}	
}

$(document).ready(function(){
	FCfunctions.navSwitcher();
	FCfunctions.focusfields();
	FCfunctions.tab();
	FCfunctions.calendar();
	FCfunctions.styleswitcher();
	FCfunctions.fontresize();
	FCfunctions.advancedsearch({
		loading : '<div id="loading"></div>',
		errormessage : "sorry there was an error, please try again"
	});
	FCfunctions.feature({
		pausesrc: "controls-pause.gif",
		playsrc: "controls-play.gif",
		prevsrc: "controls-prev.gif",
		nextsrc: "controls-next.gif"
	});
	FCfunctions.formhelp({
		wrapper : "#help", 							// where the original helptext is held
		hideClass : "hide", 						// the class to hide the wrapper
		mainForm : "form", 							// where the helpbuttons are stored 
		helpButton : ".helpbutton", 				// the class of the help buttons 
		attr : "rel", 								// the attribute in the helpbutton that has the id of the helptext
		showClass : "help", 						// the styles used style the helptext
		onSrc : "form-help-close.png", 		// active state
		onSrcAlt : "close",							// alt text when its active
		offSrc : "form-help.png",			// off state
		offSrcAlt : "help",							// alt text when inactive
		inSpeed : "fast", 							// speed at which it should fase in slow/fast or give milliseconds 250/500/1000 etc
		outSpeed : "fast"							// speed out
	});
	FCfunctions.scroller({
		scrollerId:"#scroller",						// the div containing scrollbar
		scrollWrapper:".items",						// the div that holds all the content
		itemsList:".items ul",						// items list
		items:".items .item",						// the path to the item
		oneItem:".item",							// individial item
		scrollPadding:18,							// extra padding so that the last item fits in nicely
		minValue:5									// the minimum amount of objects needed before the scrollbar gets initiated
	});
	FCfunctions.tooltip({
		container :".feature",		   				// where the tooltip content is sitting
		tooltip : ".tooltip-wrapper",				// the tooltip		
		inspeed:300,								// speed to fade in the tooltip
		outspeed:100								// speed to fade out the tooltip
	});	
	if ($(".date-pick").length){
		FCfunctions.datepicker({
			picker : ".date-pick"				  
		});
	}	
});


