//Fixes

$(document).ready(function(){
	if(!($.browser.msie)) {
		$("html").css({ height: "110%" });
	}
	if ($.browser.msie==true) {
		$("a.lienRecherche").addClass("lienRechercheIE");
	}
});

//Browser Adjustments
$(document).ready(function(){
						   
	if ($.browser.msie==true) {
		$("#top-bandeau").height(94);
		$("#hrreadylist").css('line-height','1.5');
	
	
		if ($.browser.version=="6.0")
		{ 
		
			$("#w4page").width(1025);
			$("#w4header").width(1025);
			$("#w4container").width(1025);
			$("#news-container-bf").width(340);
			$("#news-container-bf").css('position','relative');
			$("#news-container-bf").css('top','0');
			$(".carreau").css('margin',"9px");
			
			$(".tabcontent").css('background-color','#fffffe');
			$("#bandeau_orange-bf").width(175);
			$("#bandeau_darkblue-bf").width(175);
			$("#bandeau_lightblue-bf").width(175);
			$("#bandeau_grey-bf").width(175);
			$("#carreau_4_content").height(160);
			$(".carreau").height(190);
		
			//fix demolinks
			$(".demolink-cadre").width(230);
			$("#demolink-cadre").width(230);
			
			//fix wb2e
			$("#wb2e-space").width(250);
			
			//fix message boxes
			$("#home_page-bottom-row").width(1000);		
			$("#home_page-bottom-row-bf").height(200);
			
			//fix bandeau			
			$("#topbandeau").width(950);
			$("#topbandeau").css('overflow','hidden');
			$("#bandeau_header_award").width(954);
			$("#bpm-excellence-award").css('padding-right',20);

		    //fix bandeau pt es
			$("#bandeau-header").width(954);

			//fix topmenu
			$("#topmenu").width(950);
			$(".menu-border").width(954);
			$("#search-container").width(110);
			$("#search-container").height(20);
			$("#search-container").css('margin-right',0);
			$("#search-container").css('margin-left',0);
			$("#search-container").css('margin-top',2);
			$("#search-container").css('margin-bottom',0);
			$("#search-container").css('overflow','hidden');
			
			//fix main content top row
			$("#main-border").width(954);
			$("#home_page").width(950);
			$("#home_page").height(220);
			$("#homepage-top-bpm").height(218);
			$(".home_page-top-block-bpm").height(190);
			$(".home_page-top-block-bpm").css('padding-bottom',2);
			$(".homepage-top-block-bpm").height(190);
			$(".homepage-top-block-bpm").css('padding-bottom',2);
			
			//fix message boxes
			$("#home_page-bottom-row").width(950);
			$("#home_page-bottom-row").height(200);
			$("#home_page-bottom-row").css('margin-top',5);
			$("#carreau_1").css('margin-left',15);
			$("#carreau_1").css('margin-right',15);
			$("#carreau_2").css('margin-left',15);
			$("#carreau_2").css('margin-right',15);
			$("#carreau_3").css('margin-left',15);
			$("#carreau_3").css('margin-right',15);
			$("#carreau_4").css('margin-left',15);
			$("#carreau_4").css('margin-right',15);
			$("#carreau_1_content").height(150);
			$("#carreau_2_content").height(150);
			$("#carreau_3_content").height(150);
			$("#carreau_4_content").height(150);
			
			
		}


	} else {
		$(".border-rescue").css('padding-top',5);
		//$("#w4searchform").css('padding-top','0.01em');
	}
	if ($.browser.mozilla==true) {
		$("#top-bandeau").height(95);
		$("#home-page-top").css("margin","0 0.5em 0.5em");
	}
	
	if ($.browser.safari==true) {
			//fix topmenu

			$(".menu-border").css("border","1px solid #e0e0e0");
			$("#main-border").css("border-right","1px solid #e0e0e0");
			$("#main-border").css("border-bottom","1px solid #e0e0e0");
			$("#main-border").css("border-top","1px solid #e0e0e0");
			$("#topmenu").css("margin-top",0);
			$("#maincontent").css("margin-top",0);
			$(".menu-border").css("margin-top",1);
			$("#main-border").css("margin-top",0);
			$("#main-border").width(951);
			$("#bandeau_header_award").width(949);
			$("#topbandeau").css("padding","0.9em 0.9em 0.8em 0.9em");
			$("#topbandeau").css("margin-bottom",0);
			$("#topbandeau").css("overflow","hidden");

	}
	
});

//DemoLinks PT Display
var demoLinksW4PT={
	
	currentTimer: 0,
	currentHTML: "",
	currentTop: "",
	currentLeft: "",
	
	setTimer:function(sFunctionName) {
		clearTimeout(demoLinksW4PT.currentTimer);
		demoLinksW4PT.currentTimer = setTimeout(sFunctionName, 200);
	},
	
	hideLinksDescription:function() {	
		$("#dispDemoLinksPT").fadeOut("slow");
		//$("#spotlighttitle").css("margin-top","3em");
	},
	
	showLinksDescription:function() {
		
		$("#dispDemoLinksPT").stop().hide("fast", function() {
			$("#dispDemoLinksPT").css({ position: "absolute", top: demoLinksW4PT.currentTop, left: demoLinksW4PT.currentLeft });
			if (!($("#dispDemoLinksPT").hasClass("demolink-detail-pt"))) {
				$("#dispDemoLinksPT").addClass("demolink-detail-pt");						   
			}		
			$("#dispDemoLinksPT").html(demoLinksW4PT.currentHTML);
			$("#dispDemoLinksPT").slideDown("slow");
			//$("#spotlighttitle").animate({marginTop: "16em"}, 500 );
		});
			
	},
	
	showLinksDescriptionTimer:function() {
		var sFonction = "demoLinksW4PT.showLinksDescription()";
		demoLinksW4PT.setTimer(sFonction);
	},
	
	
	init:function(params){
		
		$(document).ready(function(){
			
			$("#dispDemoLinksPT").hover( function (ev) {										  
			},function(ev){
				demoLinksW4PT.hideLinksDescription();
			}); 
			
			$("#cadre-demo-menu-right").hover( function (ev) {
				demoLinksW4PT.currentHTML = $("#demoLinkList").html();
				demoLinksW4PT.currentTop = $(this).position().top;
				demoLinksW4PT.currentLeft = $(this).position().left;
				demoLinksW4PT.showLinksDescriptionTimer();				
			},function(ev){
			
			}); 
	 
	 }); 
				
	}
	
}

demoLinksW4PT.init();

//DemoLinks ES Display
var demoLinksW4ES={
	
	currentTimer: 0,
	currentHTML: "",
	currentTop: "",
	currentLeft: "",
	
	setTimer:function(sFunctionName) {
		clearTimeout(demoLinksW4ES.currentTimer);
		demoLinksW4ES.currentTimer = setTimeout(sFunctionName, 200);
	},
	
	hideLinksDescription:function() {	
		$("#dispDemoLinksES").fadeOut("slow");
		//$("#spotlighttitle").css("margin-top","3em");
	},
	
	showLinksDescription:function() {
		
		$("#dispDemoLinksES").stop().hide("fast", function() {
			$("#dispDemoLinksES").css({ position: "absolute", top: demoLinksW4ES.currentTop, left: demoLinksW4ES.currentLeft });
			if (!($("#dispDemoLinksES").hasClass("demolink-detail-es"))) {
				$("#dispDemoLinksES").addClass("demolink-detail-es");						   
			}		
			$("#dispDemoLinksES").html(demoLinksW4ES.currentHTML);
			$("#dispDemoLinksES").slideDown("slow");
			//$("#spotlighttitle").animate({marginTop: "16em"}, 500 );
		});
			
	},
	
	showLinksDescriptionTimer:function() {
		var sFonction = "demoLinksW4ES.showLinksDescription()";
		demoLinksW4ES.setTimer(sFonction);
	},
	
	
	init:function(params){
		
		$(document).ready(function(){
			
			$("#dispDemoLinksES").hover( function (ev) {										  
			},function(ev){
				demoLinksW4ES.hideLinksDescription();
			}); 
			
			$("#cadre-demo-menu-right").hover( function (ev) {
				demoLinksW4ES.currentHTML = $("#demoLinkList").html();
				demoLinksW4ES.currentTop = $(this).position().top;
				demoLinksW4ES.currentLeft = $(this).position().left;
				demoLinksW4ES.showLinksDescriptionTimer();				
			},function(ev){
			
			}); 
	 
	 }); 
				
	}
	
}

demoLinksW4ES.init();

//DemoLinks Display 
var demoLinksW4={
	
	currentTimer: 0,
	currentHTML: "",
	currentTop: "",
	currentLeft: "",
	
	setTimer:function(sFunctionName) {
		clearTimeout(demoLinksW4.currentTimer);
		demoLinksW4.currentTimer = setTimeout(sFunctionName, 200);
	},
	
	hideLinksDescription:function() {	
		$("#dispDemoLinks").fadeOut("slow");
		$("#spotlighttitle").css("margin-top","3em");
	},
	
	showLinksDescription:function() {
		
		$("#dispDemoLinks").stop().hide("fast", function() {
			$("#dispDemoLinks").css({ position: "absolute", top: demoLinksW4.currentTop, left: demoLinksW4.currentLeft });
			if (!($("#dispDemoLinks").hasClass("demolink-detail"))) {
				$("#dispDemoLinks").addClass("demolink-detail");						   
			}		
			$("#dispDemoLinks").html(demoLinksW4.currentHTML);
			$("#dispDemoLinks").slideDown("slow");
			$("#spotlighttitle").animate({marginTop: "16em"}, 500 );
		});
			
	},
	
	showLinksDescriptionTimer:function() {
		var sFonction = "demoLinksW4.showLinksDescription()";
		demoLinksW4.setTimer(sFonction);
	},
	
	
	init:function(params){
		
		$(document).ready(function(){
			
			$("#dispDemoLinks").hover( function (ev) {										  
			},function(ev){
				demoLinksW4.hideLinksDescription();
			}); 
			
			$("#cadre-demo-menu").hover( function (ev) {
				demoLinksW4.currentHTML = $("#demoLinkList").html();
				demoLinksW4.currentTop = $(this).position().top;
				demoLinksW4.currentLeft = $(this).position().left;
				demoLinksW4.showLinksDescriptionTimer();				
			},function(ev){
			
			}); 
	 
	 }); 
				
	}
	
}

demoLinksW4.init();

//Jquery print function
var jqprintpage={
	
	gAutoPrint:true,
	
	init:function(conf){
		
		$(document).ready(function(){
								   
				$("#printimage").click( function() {
						jqprintpage.printPage();	
				});
								   
		});
	},
	
	printPage:function() {
		if (document.getElementById != null)
		{
			var html = '<HTML>\n<HEAD>\n';
	
			if (document.getElementsByTagName != null)
			{
				var headTags = document.getElementsByTagName("head");
				if (headTags.length > 0)
					html += headTags[0].innerHTML;
			}
			
			html += '\n</HE' + 'AD>\n<BODY style="margin:15px">\n';
			
			if (location.pathname=='/indexfr.html') {
				var printReadyElem = document.getElementById("w4page");
			} else {
				var printReadyElem = document.getElementById("pagecontent");
			}
			
			
			if (printReadyElem != null)
			{
					html += printReadyElem.innerHTML;
			}
			else
			{
				var printFullPage = document.getElementByID("w4page");
				
				if (printFullPage != null) {
					
					html += printReadyElem.innerHTML;
					
				} else {
				
					alert("Could not find the printReady section in the HTML");
					return;
				}
			}
				
			html += '\n</BO' + 'DY>\n</HT' + 'ML>';
			
			var printWin = window.open("","printSpecial");
			printWin.document.open();
			printWin.document.write(html);
			printWin.document.close();
			if (jqprintpage.gAutoPrint) {
				printWin.print();
			}
		}
		else
		{
			alert("Sorry, the print ready feature is only available in modern browsers.");
		}
	}
}

jqprintpage.init();

//Search

var jqsearchutil={
	
	init:function(){
		$(document).ready(function(){
								   
			$("#search_string").click( function() {
				$(this).attr('value', '');
				$(this).css("border-color","#EB6E07");
			});
		
			jqsearchutil.InitiateMouseOver();
			
			$("#goLinkfr").click( function() {
				jqsearchutil.SearchLinkClick('fr','Veuillez saisir un mot de recherche...','http://www.w4.eu/Resultats.aspx');							
			});
			
			$("#searchFormfr").submit ( function() {
				jqsearchutil.SearchFormSubmit('fr','Veuillez saisir un mot de recherche...','http://www.w4.eu/Resultats.aspx');							
			});
			
			$("#goLinken").click( function() {
				jqsearchutil.SearchLinkClick('en','Please enter a search item...','http://www.w4.eu/Results.aspx');							
			});
										   
			$("#searchFormen").submit ( function() {
				jqsearchutil.SearchFormSubmit('en','Please enter a search item...','http://www.w4.eu/Results.aspx');		
			});
			
			$("#goLinkes").click( function() {
				jqsearchutil.SearchLinkClick('es','Incorpore por favor un artículo de la búsqueda...','/Resultados.aspx');							
			});
										   
			$("#searchFormes").submit ( function() {
				jqsearchutil.SearchFormSubmit('es','Incorpore por favor un artículo de la búsqueda...','/Resultados.aspx');		
			});
			
			$("#goLinkbr").click( function() {
				jqsearchutil.SearchLinkClick('br','Incorpore por favor un artículo de la búsqueda...','/Resultados_br.aspx');							
			});
										   
			$("#searchFormbr").submit ( function() {
				jqsearchutil.SearchFormSubmit('br','Incorpore por favor un artículo de la búsqueda...','/Resultados_br.aspx');		
			});
												   
		});
	},
	
	InitiateMouseOver:function() {
		$("#goLinkfr").mouseover( function() {
				 window.status='';
		});
		
		$("#goLinken").mouseover( function() {
			 window.status='';
		});
		
		$("#goLinkes").mouseover( function() {
			 window.status='';
		});
		
		$("#goLinkbr").mouseover( function() {
			 window.status='';
		});	
	},
	
	SearchLinkClick:function(sLang,sMessageEcran,sResultPage) {
		var sSearchForm = '#searchForm'+sLang;
		if ($("#search_string").attr('value')=='') {
				alert(sMessageEcran);
				$("#search_string").focus();
				return false;
		} else {
			var strResultPage = sResultPage + '?q=' + $("#search_string").attr('value');
			//$(sSearchForm).attr('action',strResultPage);
			//$(sSearchForm).submit();
			window.open(strResultPage,"LyriaResults","left=20,top=20,width=700,height=500,toolbar=1,resizable=0");
		} 
	},
	
	SearchFormSubmit:function(sLang,sMessageEcran,sResultPage) {
		var sSearchForm = '#searchForm'+sLang;
		if ($("#search_string").attr('value')=='') {
				alert(sMessageEcran);
				$("#search_string").focus();
				return false;
		} else {
			var strResultPage = sResultPage + '?q=' + $("#search_string").attr('value');
			//$(sSearchForm).attr('action',strResultPage);
			window.open(strResultPage,"LyriaResults","left=20,top=20,width=700,height=500,toolbar=1,resizable=0");
		}
	}
};

jqsearchutil.init();


//Partner Rollover 

$(document).ready(function(){
						   

	$("#cadre-partenaires").click( function() {
			
			jQuery.facebox({ ajax: '/myDocuments/bpm-partners/plaquette-oem.html' });
		
	});
	
	$("#cadre-partenaires-es").click( function() {
			
			jQuery.facebox({ ajax: '/myDocuments/bpm-partners/plaquette-oem-es.html' });
		
	});
	
	$("#cadre-partenaires-integrateurs").click( function() {
			
			jQuery.facebox({ ajax: '/myDocuments/bpm-partners/plaquette-integrateurs.html' });
		
	});
	
	 
});


//Bandeau Rollover

$(document).ready(function(){
						   
	var sAwardLink = "";
	
	$("#bpm-excellence-award").hover( function (ev) {
												
		sAwardLink = $("#award-2").html();
		$("#award-2").html("Cliquez pour en savoir plus");
		$("#award-1").css("display", "none");
			$("#award-1").hide("fast", function() {
				$("#award-3").slideDown("fast", function() {
					
				});
			});

						
	},function(ev){
			
			$("#award-2").html(sAwardLink);
			$("#award-3").css("display", "none");
			$("#award-3").hide("fast", function() {
				$("#award-1").slideDown("fast", function() {
					 
				});
			});

		
	});
	
	$("#bpm-excellence-award-en").hover( function (ev) {
												
		sAwardLink = $("#award-2").html();
		$("#award-2").html("Click here to find out more");
		$("#award-1").css("display", "none");
			$("#award-1").hide("fast", function() {
				$("#award-3").slideDown("fast", function() {
					
				});
			});

						
	},function(ev){
			
			$("#award-2").html(sAwardLink);
			$("#award-3").css("display", "none");
			$("#award-3").hide("fast", function() {
				$("#award-1").slideDown("fast", function() {
					 
				});
			});

		
	});
						   
});


//Menu Colors

$(document).ready(function() {
	var docLoc = jQuery.url.attr("path");
	
	$('.accordeonmenu').find('a').each(function() {
							
		if ($(this).attr('href')==docLoc) {
			
			$(this).css("color","#ffffff");
			$(this).css("background-color","#7CA1BF");
		}
	});
	
	$('.accordeonmenu').children().find('a').each(function() {
							
		if ($(this).attr('href')==docLoc) {
			
			$(this).css("color","#ffffff");
			$(this).css("background-color","#7CA1BF");
		}
	});
	
	$('#qm0').find('a').each(function() {
									 
		if ($(this).attr('href')==docLoc) {
			
			$(this).css("color","#ffffff");
			$(this).css("background-color","#7CA1BF");
		}
									  
	});
	
});

/* =========================================================
 *
 * jquery.reorder.js - version 0.1.1
 * 2007-12-11
 *
 * jquery plugin to randomly reorder 
 * first-child elements of selected elements 
 * by rebecca murphey
 * http://blog.rebeccamurphey.com/ 
 *
/* ========================================================= */

(function($){
$.fn.reorder = function() {

  // random array sort from 
  // http://javascript.about.com/library/blsort2.htm
  function randOrd() { return(Math.round(Math.random())-0.5); }

  return($(this).each(function() {
    var $this = $(this);
    var $children = $this.children();
    var childCount = $children.length;

    if (childCount > 1) {
      $children.remove();

      var indices = new Array();
      for (i=0;i<childCount;i++) { indices[indices.length] = i; }
      indices = indices.sort(randOrd);
      $.each(indices,function(j,k) { $this.append($children.eq(k)); });

    }
  }));
} 
})(jQuery);

//Jquery URL Plugin
jQuery.url=function(){var segments={};var parsed={};var options={url:window.location,strictMode:false,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};var parseUri=function(){str=decodeURI(options.url);var m=options.parser[options.strictMode?"strict":"loose"].exec(str);var uri={};var i=14;while(i--){uri[options.key[i]]=m[i]||""}uri[options.q.name]={};uri[options.key[12]].replace(options.q.parser,function($0,$1,$2){if($1){uri[options.q.name][$1]=$2}});return uri};var key=function(key){if(!parsed.length){setUp()}if(key=="base"){if(parsed.port!==null&&parsed.port!==""){return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/"}else{return parsed.protocol+"://"+parsed.host+"/"}}return(parsed[key]==="")?null:parsed[key]};var param=function(item){if(!parsed.length){setUp()}return(parsed.queryKey[item]===null)?null:parsed.queryKey[item]};var setUp=function(){parsed=parseUri();getSegments()};var getSegments=function(){var p=parsed.path;segments=[];segments=parsed.path.length==1?{}:(p.charAt(p.length-1)=="/"?p.substring(1,p.length-1):path=p.substring(1)).split("/")};return{setMode:function(mode){strictMode=mode=="strict"?true:false;return this},setUrl:function(newUri){options.url=newUri===undefined?window.location:newUri;setUp();return this},segment:function(pos){if(!parsed.length){setUp()}if(pos===undefined){return segments.length}return(segments[pos]===""||segments[pos]===undefined)?null:segments[pos]},attr:key,param:param}}();


//** Accordion Content script: By Dynamic Drive, at http://www.dynamicdrive.com
//** Created: Jan 7th, 08'

//Version 1.3: April 3rd, 08':
//**1) Script now no longer conflicts with other JS frameworks
//**2) Adds custom oninit() and onopenclose() event handlers that fire when Accordion Content instance has initialized, plus whenever a header is opened/closed
//**3) Adds support for expanding header(s) using the URL parameter (ie: http://mysite.com/accordion.htm?headerclass=0,1)

//April 9th, 08': Fixed "defaultexpanded" setting not working when page first loads

//Version 1.4: June 4th, 08':
//**1) Added option to activate a header "mouseover" instead of the default "click"
//**2) Bug persistence not working when used with jquery 1.2.6

//Version 1.5: June 20th, 08':
//**1) Adds new "onemustopen:true/false" parameter, which lets you set whether at least one header should be open at all times (so never all closed).
//**2) Changed cookie path to site wide for persistence feature
//**3) Fixed bug so "expandedindices" parameter in oninit(headers, expandedindices) returns empty array [] instead of [-1] when no expanded headers found

//**1) Version 1.5.1: June 27th, 08': Fixed "defaultexpanded" setting not working properly when used with jquery 1.2.6

//Version 1.6: Oct 3rd, 08':
//**1) Adds new "mouseoverdelay" param that sets delay before headers are activated when "revealtype" param is set to "mouseover"
//**2) Fixed bug with "onemustopen" param not working properly when "revealtype" is set to "click"


var ddaccordion2={
	
	contentclassname:{}, //object to store corresponding contentclass name based on headerclass

	expandone:function(headerclass, selected){ //PUBLIC function to expand a particular header
		this.toggleone(headerclass, selected, "expand")
	},

	collapseone:function(headerclass, selected){ //PUBLIC function to collapse a particular header
		this.toggleone(headerclass, selected, "collapse")
	},

	expandall:function(headerclass){ //PUBLIC function to expand all headers based on their shared CSS classname
		var $=jQuery
		var $headers=$('.'+headerclass)
		$('.'+this.contentclassname[headerclass]+':hidden').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	collapseall:function(headerclass){ //PUBLIC function to collapse all headers based on their shared CSS classname
		var $=jQuery
		var $headers=$('.'+headerclass)
		$('.'+this.contentclassname[headerclass]+':visible').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	toggleone:function(headerclass, selected, optstate){ //PUBLIC function to expand/ collapse a particular header
		var $=jQuery
		var $targetHeader=$('.'+headerclass).eq(selected)
		var $subcontent=$('.'+this.contentclassname[headerclass]).eq(selected)
		if (typeof optstate=="undefined" || optstate=="expand" && $subcontent.is(":hidden") || optstate=="collapse" && $subcontent.is(":visible"))
			$targetHeader.trigger("evt_accordion")
	},

	expandit:function($targetHeader, $targetContent, config, useractivated){
		$targetContent.slideDown(config.animatespeed, function(){config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), useractivated)})
		this.transformHeader($targetHeader, config, "expand")
	},

	collapseit:function($targetHeader, $targetContent, config, isuseractivated){
		$targetContent.slideUp(config.animatespeed, function(){config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), isuseractivated)})
		this.transformHeader($targetHeader, config, "collapse")
	},

	transformHeader:function($targetHeader, config, state){
		$targetHeader.addClass((state=="expand")? config.cssclass.expand : config.cssclass.collapse) //alternate btw "expand" and "collapse" CSS classes
		.removeClass((state=="expand")? config.cssclass.collapse : config.cssclass.expand)
		if (config.htmlsetting.location=='src'){ //Change header image (assuming header is an image)?
			$targetHeader=($targetHeader.is("img"))? $targetHeader : $targetHeader.find('img').eq(0) //Set target to either header itself, or first image within header
			$targetHeader.attr('src', (state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse) //change header image
		}
		else if (config.htmlsetting.location=="prefix") //if change "prefix" HTML, locate dynamically added ".accordprefix" span tag and change it
			$targetHeader.find('.accordprefix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
		else if (config.htmlsetting.location=="suffix")
			$targetHeader.find('.accordsuffix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
	},

	urlparamselect:function(headerclass){
		var result=window.location.search.match(new RegExp(headerclass+"=((\\d+)(,(\\d+))*)", "i")) //check for "?headerclass=2,3,4" in URL
		if (result!=null)
			result=RegExp.$1.split(',')
		return result //returns null, [index], or [index1,index2,etc], where index are the desired selected header indices
	},

	getCookie:function(Name){ 
		var re=new RegExp(Name+"=[^;]+", "i") //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie:function(name, value){
		document.cookie = name + "=" + value + "; path=/"
	},

	init:function(config){
	document.write('<style type="text/css">\n')
	document.write('.'+config.contentclass+'{display: none}\n') //generate CSS to hide contents
	document.write('<\/style>')
	jQuery(document).ready(function($){
		ddaccordion.urlparamselect(config.headerclass)
		var persistedheaders=ddaccordion.getCookie(config.headerclass)
		ddaccordion.contentclassname[config.headerclass]=config.contentclass //remember contentclass name based on headerclass
		config.cssclass={collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
		config.revealtype=/^(click)|(mouseover)$/i.test(config.revealtype)? config.revealtype.replace(/mouseover/i, "mouseenter") : "click"
		config.htmlsetting={location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
		config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
		config.onopenclose=(typeof config.onopenclose=="undefined")? function(){} : config.onopenclose //attach custom "onopenclose" event handler
		var lastexpanded={} //object to hold reference to last expanded header and content (jquery objects)
		var expandedindices=ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders!=null)? persistedheaders : config.defaultexpanded)
		if (typeof expandedindices=='string') //test for string value (exception is config.defaultexpanded, which is an array)
			expandedindices=expandedindices.replace(/c/ig, '').split(',') //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
		var $subcontents=$('.'+config["contentclass"])
		if (expandedindices.length==1 && expandedindices[0]=="-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
			expandedindices=[]
		if (config["collapseprev"] && expandedindices.length>1) //only allow one content open?
			expandedindices=[expandedindices.pop()] //return last array element as an array (for sake of jQuery.inArray())
		if (config["onemustopen"] && expandedindices.length==0) //if at least one content should be open at all times and none are, open 1st header
			expandedindices=[0]
		$('.'+config["headerclass"]).each(function(index){ //loop through all headers
			if (/(prefix)|(suffix)/i.test(config.htmlsetting.location) && $(this).html()!=""){ //add a SPAN element to header depending on user setting and if header is a container tag
				$('<span class="accordprefix"></span>').prependTo(this)
				$('<span class="accordsuffix"></span>').appendTo(this)
			}
			$(this).attr('headerindex', index+'h') //store position of this header relative to its peers
			$subcontents.eq(index).attr('contentindex', index+'c') //store position of this content relative to its peers
			var $subcontent=$subcontents.eq(index)
			var needle=(typeof expandedindices[0]=="number")? index : index+'' //check for data type within expandedindices array- index should match that type
			if (jQuery.inArray(needle, expandedindices)!=-1){ //check for headers that should be expanded automatically (convert index to string first)
				if (config.animatedefault==false)
					$subcontent.show()
				ddaccordion.expandit($(this), $subcontent, config, false) //Last Boolean value sets 'isuseractivated' parameter
				lastexpanded={$header:$(this), $content:$subcontent}
			}  //end check
			else{
				$subcontent.hide()
				config.onopenclose($(this).get(0), parseInt($(this).attr('headerindex')), $subcontent.css('display'), false) //Last Boolean value sets 'isuseractivated' parameter
				ddaccordion.transformHeader($(this), config, "collapse")
			}
		})
		$('.'+config["headerclass"]).bind("evt_accordion", function(){ //assign custom event handler that expands/ contacts a header
				var $subcontent=$subcontents.eq(parseInt($(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
				if ($subcontent.css('display')=="none"){
					ddaccordion.expandit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
					if (config["collapseprev"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){ //collapse previous content?
						ddaccordion.collapseit(lastexpanded.$header, lastexpanded.$content, config, true) //Last Boolean value sets 'isuseractivated' parameter
					}
					lastexpanded={$header:$(this), $content:$subcontent}
				}
				else if (!config["onemustopen"] || config["onemustopen"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){
					ddaccordion.collapseit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
				}
 		})
		$('.'+config["headerclass"]).bind(config.revealtype, function(){
			if (config.revealtype=="mouseenter"){
				clearTimeout(config.revealdelay)
				var headerindex=parseInt($(this).attr("headerindex"))
				config.revealdelay=setTimeout(function(){ddaccordion.expandone(config["headerclass"], headerindex)}, config.mouseoverdelay || 0)
			}
			else{
				$(this).trigger("evt_accordion")
				return false //cancel default click behavior
			}
		})
		$('.'+config["headerclass"]).bind("mouseleave", function(){
			clearTimeout(config.revealdelay)
		})
		config.oninit($('.'+config["headerclass"]).get(), expandedindices)
		$(window).bind('unload', function(){ //clean up and persist on page unload
			$('.'+config["headerclass"]).unbind()
			var expandedindices=[]
			$('.'+config["contentclass"]+":visible").each(function(index){ //get indices of expanded headers
				expandedindices.push($(this).attr('contentindex'))
			})
			if (config.persiststate==true){ //persist state?
				expandedindices=(expandedindices.length==0)? '-1c' : expandedindices //No contents expanded, indicate that with dummy '-1c' value?
				ddaccordion.setCookie(config.headerclass, expandedindices)
			}
		})
	})
	}
}

jQuery.fn.corner = function(options) {
    
        
        var settings = {
          tl: { radius: 20 },
          tr: { radius: 20 },
          bl: { radius: 20 },
          br: { radius: 20 },
          antiAlias: true,
          autoPad: true,
          validTags: ["div"] };
        if ( options && typeof(options) != 'string' )
            jQuery.extend(settings, options);


    return this.each(function() {
        new curvyObject(settings,this).applyCorners();
        //new curvyCorners(settings, this ).applyCornersToAll();
	});   
            
};




/****************************************************************
*                                                              *
*  curvyCorners                                                *
*  ------------                                                *
*                                                              *
*  This script generates rounded corners for your divs.        *
*                                                              *
*  Version 1.2.10                                              *
*  Modified by Stefan Holmberg - for jquery usage              *
*  http://www.aspcode.net                                      *
*                                                              *
*  Version 1.2.9                                               *
*  Copyright (c) 2006 Cameron Cooke                            *
*  By: Cameron Cooke and Tim Hutchison.                        *
*                                                              *
*                                                              *
*  Website: http://www.curvycorners.net                        *
*  Email:   info@totalinfinity.com                             *
*  Forum:   http://www.curvycorners.net/forum/                 *
*                                                              *
*                                                              *
*  This library is free software;
you can redistribute         *
*  it and/or modify it under the terms of the GNU              *
*  Lesser General Public License as published by the           *
*  Free Software Foundation;
either version 2.1 of the         *
*  License, or (at your option) any later version.             *
*                                                              *
*  This library is distributed in the hope that it will        *
*  be useful, but WITHOUT ANY WARRANTY;
without even the       *
*  implied warranty of MERCHANTABILITY or FITNESS FOR A        *
*  PARTICULAR PURPOSE. See the GNU Lesser General Public       *
*  License for more details.                                   *
*                                                              *
*  You should have received a copy of the GNU Lesser           *
*  General Public License along with this library;
*
*  Inc., 59 Temple Place, Suite 330, Boston,                   *
*  MA 02111-1307 USA                                           *
*                                                              *
****************************************************************/





function curvyObject()

{
    this.box = arguments[1];
    this.settings = arguments[0];
    this.topContainer = null;
    this.bottomContainer = null;
    this.masterCorners = new Array();
    this.contentDIV = null;
    var boxHeight = get_style(this.box, "height", "height");
    var boxWidth = get_style(this.box, "width", "width");
    var borderWidth = get_style(this.box, "borderTopWidth", "border-top-width");
    var borderColour = get_style(this.box, "borderTopColor", "border-top-color");
    var boxColour = get_style(this.box, "backgroundColor", "background-color");
    var backgroundImage = get_style(this.box, "backgroundImage", "background-image");
    var boxPosition = get_style(this.box, "position", "position");
    var boxPadding = get_style(this.box, "paddingTop", "padding-top");
    this.boxHeight = parseInt(((boxHeight != "" && boxHeight != "auto" && boxHeight.indexOf("%") == -1)? boxHeight.substring(0, boxHeight.indexOf("px")) : this.box.scrollHeight));
    this.boxWidth = parseInt(((boxWidth != "" && boxWidth != "auto" && boxWidth.indexOf("%") == -1)? boxWidth.substring(0, boxWidth.indexOf("px")) : this.box.scrollWidth));
    this.borderWidth = parseInt(((borderWidth != "" && borderWidth.indexOf("px") !== -1)? borderWidth.slice(0, borderWidth.indexOf("px")) : 0));
    this.boxColour = format_colour(boxColour);
    this.boxPadding = parseInt(((boxPadding != "" && boxPadding.indexOf("px") !== -1)? boxPadding.slice(0, boxPadding.indexOf("px")) : 0));
    this.borderColour = format_colour(borderColour);
    this.borderString = this.borderWidth + "px" + " solid " + this.borderColour;
    this.backgroundImage = ((backgroundImage != "none")? backgroundImage : "");
    this.boxContent = this.box.innerHTML;
    if(boxPosition != "absolute") this.box.style.position = "relative";
    this.box.style.padding = "0px";
    
    var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1;
    
    if(isIE && boxWidth == "auto" && boxHeight == "auto") this.box.style.width = "100%";
    if(this.settings.autoPad == true && this.boxPadding > 0)
    this.box.innerHTML = "";
    this.applyCorners = function()
    
    {
        for(var t = 0;
        t < 2;
        t++)
        
        {
            switch(t)
            
            {
                case 0:
                if(this.settings.tl || this.settings.tr)
                
                {
                    var newMainContainer = document.createElement("DIV");
                    newMainContainer.style.width = "100%";
                    newMainContainer.style.fontSize = "1px";
                    newMainContainer.style.overflow = "hidden";
                    newMainContainer.style.position = "absolute";
                    newMainContainer.style.paddingLeft = this.borderWidth + "px";
                    newMainContainer.style.paddingRight = this.borderWidth + "px";
                    var topMaxRadius = Math.max(this.settings.tl ? this.settings.tl.radius : 0, this.settings.tr ? this.settings.tr.radius : 0);
                    newMainContainer.style.height = topMaxRadius + "px";
                    newMainContainer.style.top = 0 - topMaxRadius + "px";
                    newMainContainer.style.left = 0 - this.borderWidth + "px";
                    this.topContainer = this.box.appendChild(newMainContainer);
                    
                }
                
                break;
                case 1:
                if(this.settings.bl || this.settings.br)
                
                {
                    var newMainContainer = document.createElement("DIV");
                    newMainContainer.style.width = "100%";
                    newMainContainer.style.fontSize = "1px";
                    newMainContainer.style.overflow = "hidden";
                    newMainContainer.style.position = "absolute";
                    newMainContainer.style.paddingLeft = this.borderWidth + "px";
                    newMainContainer.style.paddingRight = this.borderWidth + "px";
                    var botMaxRadius = Math.max(this.settings.bl ? this.settings.bl.radius : 0, this.settings.br ? this.settings.br.radius : 0);
                    newMainContainer.style.height = botMaxRadius + "px";
                    newMainContainer.style.bottom = 0 - botMaxRadius + "px";
                    newMainContainer.style.left = 0 - this.borderWidth + "px";
                    this.bottomContainer = this.box.appendChild(newMainContainer);
                    
                }
                
                break;
                
            }
            
            
        }
        
        if(this.topContainer) this.box.style.borderTopWidth = "0px";
        if(this.bottomContainer) this.box.style.borderBottomWidth = "0px";
        var corners = ["tr", "tl", "br", "bl"];
        for(var i in corners)
        
        {
            if(i > -1 < 4)
            
            {
                var cc = corners[i];
                if(!this.settings[cc])
                
                {
                    if(((cc == "tr" || cc == "tl") && this.topContainer != null) || ((cc == "br" || cc == "bl") && this.bottomContainer != null))
                    
                    {
                        var newCorner = document.createElement("DIV");
                        newCorner.style.position = "relative";
                        newCorner.style.fontSize = "1px";
                        newCorner.style.overflow = "hidden";
                        if(this.backgroundImage == "")
                        newCorner.style.backgroundColor = this.boxColour;
                        else
                        newCorner.style.backgroundImage = this.backgroundImage;
                        switch(cc)
                        
                        {
                            case "tl":
                            newCorner.style.height = topMaxRadius - this.borderWidth + "px";
                            newCorner.style.marginRight = this.settings.tr.radius - (this.borderWidth*2) + "px";
                            newCorner.style.borderLeft = this.borderString;
                            newCorner.style.borderTop = this.borderString;
                            newCorner.style.left = -this.borderWidth + "px";
                            break;
                            case "tr":
                            newCorner.style.height = topMaxRadius - this.borderWidth + "px";
                            newCorner.style.marginLeft = this.settings.tl.radius - (this.borderWidth*2) + "px";
                            newCorner.style.borderRight = this.borderString;
                            newCorner.style.borderTop = this.borderString;
                            newCorner.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px";
                            newCorner.style.left = this.borderWidth + "px";
                            break;
                            case "bl":
                            newCorner.style.height = botMaxRadius - this.borderWidth + "px";
                            newCorner.style.marginRight = this.settings.br.radius - (this.borderWidth*2) + "px";
                            newCorner.style.borderLeft = this.borderString;
                            newCorner.style.borderBottom = this.borderString;
                            newCorner.style.left = -this.borderWidth + "px";
                            newCorner.style.backgroundPosition = "-" + (this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px";
                            break;
                            case "br":
                            newCorner.style.height = botMaxRadius - this.borderWidth + "px";
                            newCorner.style.marginLeft = this.settings.bl.radius - (this.borderWidth*2) + "px";
                            newCorner.style.borderRight = this.borderString;
                            newCorner.style.borderBottom = this.borderString;
                            newCorner.style.left = this.borderWidth + "px"
                            newCorner.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (botMaxRadius + this.borderWidth)) + "px";
                            break;
                            
                        }
                        
                        
                    }
                    
                    
                }
                
                else
                
                {
                    if(this.masterCorners[this.settings[cc].radius])
                    
                    {
                        var newCorner = this.masterCorners[this.settings[cc].radius].cloneNode(true);
                        
                    }
                    
                    else
                    
                    {
                        var newCorner = document.createElement("DIV");
                        newCorner.style.height = this.settings[cc].radius + "px";
                        newCorner.style.width = this.settings[cc].radius + "px";
                        newCorner.style.position = "absolute";
                        newCorner.style.fontSize = "1px";
                        newCorner.style.overflow = "hidden";
                        var borderRadius = parseInt(this.settings[cc].radius - this.borderWidth);
                        for(var intx = 0, j = this.settings[cc].radius;
                        intx < j;
                        intx++)
                        
                        {
                            if((intx +1) >= borderRadius)
                            var y1 = -1;
                            else
                            var y1 = (Math.floor(Math.sqrt(Math.pow(borderRadius, 2) - Math.pow((intx+1), 2))) - 1);
                            if(borderRadius != j)
                            
                            {
                                if((intx) >= borderRadius)
                                var y2 = -1;
                                else
                                var y2 = Math.ceil(Math.sqrt(Math.pow(borderRadius,2) - Math.pow(intx, 2)));
                                if((intx+1) >= j)
                                var y3 = -1;
                                else
                                var y3 = (Math.floor(Math.sqrt(Math.pow(j ,2) - Math.pow((intx+1), 2))) - 1);
                                
                            }
                            
                            if((intx) >= j)
                            var y4 = -1;
                            else
                            var y4 = Math.ceil(Math.sqrt(Math.pow(j ,2) - Math.pow(intx, 2)));
                            if(y1 > -1) this.drawPixel(intx, 0, this.boxColour, 100, (y1+1), newCorner, -1, this.settings[cc].radius);
                            if(borderRadius != j)
                            
                            {
                                for(var inty = (y1 + 1);
                                inty < y2;
                                inty++)
                                
                                {
                                    if(this.settings.antiAlias)
                                    
                                    {
                                        if(this.backgroundImage != "")
                                        
                                        {
                                            var borderFract = (pixelFraction(intx, inty, borderRadius) * 100);
                                            if(borderFract < 30)
                                            
                                            {
                                                this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, 0, this.settings[cc].radius);
                                                
                                            }
                                            
                                            else
                                            
                                            {
                                                this.drawPixel(intx, inty, this.borderColour, 100, 1, newCorner, -1, this.settings[cc].radius);
                                                
                                            }
                                            
                                            
                                        }
                                        
                                        else
                                        
                                        {
                                            var pixelcolour = BlendColour(this.boxColour, this.borderColour, pixelFraction(intx, inty, borderRadius));
                                            this.drawPixel(intx, inty, pixelcolour, 100, 1, newCorner, 0, this.settings[cc].radius, cc);
                                            
                                        }
                                        
                                        
                                    }
                                    
                                    
                                }
                                
                                if(this.settings.antiAlias)
                                
                                {
                                    if(y3 >= y2)
                                    
                                    {
                                        if (y2 == -1) y2 = 0;
                                        this.drawPixel(intx, y2, this.borderColour, 100, (y3 - y2 + 1), newCorner, 0, 0);
                                        
                                    }
                                    
                                    
                                }
                                
                                else
                                
                                {
                                    if(y3 >= y1)
                                    
                                    {
                                        this.drawPixel(intx, (y1 + 1), this.borderColour, 100, (y3 - y1), newCorner, 0, 0);
                                        
                                    }
                                    
                                    
                                }
                                
                                var outsideColour = this.borderColour;
                                
                            }
                            
                            else
                            
                            {
                                var outsideColour = this.boxColour;
                                var y3 = y1;
                                
                            }
                            
                            if(this.settings.antiAlias)
                            
                            {
                                for(var inty = (y3 + 1);
                                inty < y4;
                                inty++)
                                
                                {
                                    this.drawPixel(intx, inty, outsideColour, (pixelFraction(intx, inty , j) * 100), 1, newCorner, ((this.borderWidth > 0)? 0 : -1), this.settings[cc].radius);
                                    
                                }
                                
                                
                            }
                            
                            
                        }
                        
                        this.masterCorners[this.settings[cc].radius] = newCorner.cloneNode(true);
                        
                    }
                    
                    if(cc != "br")
                    
                    {
                        for(var t = 0, k = newCorner.childNodes.length;
                        t < k;
                        t++)
                        
                        {
                            var pixelBar = newCorner.childNodes[t];
                            var pixelBarTop = parseInt(pixelBar.style.top.substring(0, pixelBar.style.top.indexOf("px")));
                            var pixelBarLeft = parseInt(pixelBar.style.left.substring(0, pixelBar.style.left.indexOf("px")));
                            var pixelBarHeight = parseInt(pixelBar.style.height.substring(0, pixelBar.style.height.indexOf("px")));
                            if(cc == "tl" || cc == "bl")
                            {
                                pixelBar.style.left = this.settings[cc].radius -pixelBarLeft -1 + "px";
                                
                            }
                            
                            if(cc == "tr" || cc == "tl")
                            {
                                pixelBar.style.top = this.settings[cc].radius -pixelBarHeight -pixelBarTop + "px";
                                
                            }
                            
                            switch(cc)
                            
                            {
                                case "tr":
                                pixelBar.style.backgroundPosition = "-" + Math.abs((this.boxWidth - this.settings[cc].radius + this.borderWidth) + pixelBarLeft) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px";
                                break;
                                case "tl":
                                pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs(this.settings[cc].radius -pixelBarHeight -pixelBarTop - this.borderWidth) + "px";
                                break;
                                case "bl":
                                pixelBar.style.backgroundPosition = "-" + Math.abs((this.settings[cc].radius -pixelBarLeft -1) - this.borderWidth) + "px -" + Math.abs((this.boxHeight + this.settings[cc].radius + pixelBarTop) -this.borderWidth) + "px";
                                break;
                                
                            }
                            
                            
                        }
                        
                        
                    }
                    
                    
                }
                
                if(newCorner)
                
                {
                    switch(cc)
                    
                    {
                        case "tl":
                        if(newCorner.style.position == "absolute") newCorner.style.top = "0px";
                        if(newCorner.style.position == "absolute") newCorner.style.left = "0px";
                        if(this.topContainer) this.topContainer.appendChild(newCorner);
                        break;
                        case "tr":
                        if(newCorner.style.position == "absolute") newCorner.style.top = "0px";
                        if(newCorner.style.position == "absolute") newCorner.style.right = "0px";
                        if(this.topContainer) this.topContainer.appendChild(newCorner);
                        break;
                        case "bl":
                        if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px";
                        if(newCorner.style.position == "absolute") newCorner.style.left = "0px";
                        if(this.bottomContainer) this.bottomContainer.appendChild(newCorner);
                        break;
                        case "br":
                        if(newCorner.style.position == "absolute") newCorner.style.bottom = "0px";
                        if(newCorner.style.position == "absolute") newCorner.style.right = "0px";
                        if(this.bottomContainer) this.bottomContainer.appendChild(newCorner);
                        break;
                        
                    }
                    
                    
                }
                
                
            }
            
            
        }
        
        var radiusDiff = new Array();
        radiusDiff["t"] = Math.abs(this.settings.tl.radius - this.settings.tr.radius)
        radiusDiff["b"] = Math.abs(this.settings.bl.radius - this.settings.br.radius);
        for(z in radiusDiff)
        
        {
            if(z == "t" || z == "b")
            
            {
                if(radiusDiff[z])
                
                {
                    var smallerCornerType = ((this.settings[z + "l"].radius < this.settings[z + "r"].radius)? z +"l" : z +"r");
                    var newFiller = document.createElement("DIV");
                    newFiller.style.height = radiusDiff[z] + "px";
                    newFiller.style.width = this.settings[smallerCornerType].radius+ "px"
                    newFiller.style.position = "absolute";
                    newFiller.style.fontSize = "1px";
                    newFiller.style.overflow = "hidden";
                    newFiller.style.backgroundColor = this.boxColour;
                    switch(smallerCornerType)
                    
                    {
                        case "tl":
                        newFiller.style.bottom = "0px";
                        newFiller.style.left = "0px";
                        newFiller.style.borderLeft = this.borderString;
                        this.topContainer.appendChild(newFiller);
                        break;
                        case "tr":
                        newFiller.style.bottom = "0px";
                        newFiller.style.right = "0px";
                        newFiller.style.borderRight = this.borderString;
                        this.topContainer.appendChild(newFiller);
                        break;
                        case "bl":
                        newFiller.style.top = "0px";
                        newFiller.style.left = "0px";
                        newFiller.style.borderLeft = this.borderString;
                        this.bottomContainer.appendChild(newFiller);
                        break;
                        case "br":
                        newFiller.style.top = "0px";
                        newFiller.style.right = "0px";
                        newFiller.style.borderRight = this.borderString;
                        this.bottomContainer.appendChild(newFiller);
                        break;
                        
                    }
                    
                    
                }
                
                var newFillerBar = document.createElement("DIV");
                newFillerBar.style.position = "relative";
                newFillerBar.style.fontSize = "1px";
                newFillerBar.style.overflow = "hidden";
                newFillerBar.style.backgroundColor = this.boxColour;
                newFillerBar.style.backgroundImage = this.backgroundImage;
                switch(z)
                
                {
                    case "t":
                    if(this.topContainer)
                    
                    {
                        if(this.settings.tl.radius && this.settings.tr.radius)
                        
                        {
                            newFillerBar.style.height = topMaxRadius - this.borderWidth + "px";
                            newFillerBar.style.marginLeft = this.settings.tl.radius - this.borderWidth + "px";
                            newFillerBar.style.marginRight = this.settings.tr.radius - this.borderWidth + "px";
                            newFillerBar.style.borderTop = this.borderString;
                            if(this.backgroundImage != "")
                            newFillerBar.style.backgroundPosition = "-" + (topMaxRadius + this.borderWidth) + "px 0px";
                            this.topContainer.appendChild(newFillerBar);
                            
                        }
                        
                        this.box.style.backgroundPosition = "0px -" + (topMaxRadius - this.borderWidth) + "px";
                        
                    }
                    
                    break;
                    case "b":
                    if(this.bottomContainer)
                    
                    {
                        if(this.settings.bl.radius && this.settings.br.radius)
                        
                        {
                            newFillerBar.style.height = botMaxRadius - this.borderWidth + "px";
                            newFillerBar.style.marginLeft = this.settings.bl.radius - this.borderWidth + "px";
                            newFillerBar.style.marginRight = this.settings.br.radius - this.borderWidth + "px";
                            newFillerBar.style.borderBottom = this.borderString;
                            if(this.backgroundImage != "")
                            newFillerBar.style.backgroundPosition = "-" + (botMaxRadius + this.borderWidth) + "px -" + (this.boxHeight + (topMaxRadius + this.borderWidth)) + "px";
                            this.bottomContainer.appendChild(newFillerBar);
                            
                        }
                        
                        
                    }
                    
                    break;
                    
                }
                
                
            }
            
            
        }
        
        if(this.settings.autoPad == true && this.boxPadding > 0)
        
        {
            var contentContainer = document.createElement("DIV");
            contentContainer.style.position = "relative";
            contentContainer.innerHTML = this.boxContent;
            contentContainer.className = "autoPadDiv";
            var topPadding = Math.abs(topMaxRadius - this.boxPadding);
            var botPadding = Math.abs(botMaxRadius - this.boxPadding);
            if(topMaxRadius < this.boxPadding)
            contentContainer.style.paddingTop = topPadding + "px";
            if(botMaxRadius < this.boxPadding)
            contentContainer.style.paddingBottom = botMaxRadius + "px";
            contentContainer.style.paddingLeft = this.boxPadding + "px";
            contentContainer.style.paddingRight = this.boxPadding + "px";
            this.contentDIV = this.box.appendChild(contentContainer);
            
        }
        
        
    }
    
    this.drawPixel = function(intx, inty, colour, transAmount, height, newCorner, image, cornerRadius)
    
    {
        var pixel = document.createElement("DIV");
        pixel.style.height = height + "px";
        pixel.style.width = "1px";
        pixel.style.position = "absolute";
        pixel.style.fontSize = "1px";
        pixel.style.overflow = "hidden";
        var topMaxRadius = Math.max(this.settings["tr"].radius, this.settings["tl"].radius);
        if(image == -1 && this.backgroundImage != "")
        
        {
            pixel.style.backgroundImage = this.backgroundImage;
            pixel.style.backgroundPosition = "-" + (this.boxWidth - (cornerRadius - intx) + this.borderWidth) + "px -" + ((this.boxHeight + topMaxRadius + inty) -this.borderWidth) + "px";
            
        }
        
        else
        
        {
            pixel.style.backgroundColor = colour;
            
        }
        
        if (transAmount != 100)
        setOpacity(pixel, transAmount);
        pixel.style.top = inty + "px";
        pixel.style.left = intx + "px";
        newCorner.appendChild(pixel);
        
    }
    
    
}

function insertAfter(parent, node, referenceNode)

{
    parent.insertBefore(node, referenceNode.nextSibling);
    
}

function BlendColour(Col1, Col2, Col1Fraction)

{
    var red1 = parseInt(Col1.substr(1,2),16);
    var green1 = parseInt(Col1.substr(3,2),16);
    var blue1 = parseInt(Col1.substr(5,2),16);
    var red2 = parseInt(Col2.substr(1,2),16);
    var green2 = parseInt(Col2.substr(3,2),16);
    var blue2 = parseInt(Col2.substr(5,2),16);
    if(Col1Fraction > 1 || Col1Fraction < 0) Col1Fraction = 1;
    var endRed = Math.round((red1 * Col1Fraction) + (red2 * (1 - Col1Fraction)));
    if(endRed > 255) endRed = 255;
    if(endRed < 0) endRed = 0;
    var endGreen = Math.round((green1 * Col1Fraction) + (green2 * (1 - Col1Fraction)));
    if(endGreen > 255) endGreen = 255;
    if(endGreen < 0) endGreen = 0;
    var endBlue = Math.round((blue1 * Col1Fraction) + (blue2 * (1 - Col1Fraction)));
    if(endBlue > 255) endBlue = 255;
    if(endBlue < 0) endBlue = 0;
    return "#" + IntToHex(endRed)+ IntToHex(endGreen)+ IntToHex(endBlue);
    
}

function IntToHex(strNum)

{
    base = strNum / 16;
    rem = strNum % 16;
    base = base - (rem / 16);
    baseS = MakeHex(base);
    remS = MakeHex(rem);
    return baseS + '' + remS;
    
}

function MakeHex(x)

{
    if((x >= 0) && (x <= 9))
    
    {
        return x;
        
    }
    
    else
    
    {
        switch(x)
        
        {
            case 10: return "A";
            case 11: return "B";
            case 12: return "C";
            case 13: return "D";
            case 14: return "E";
            case 15: return "F";
            
        }
        
        
    }
    
    
}

function pixelFraction(x, y, r)

{
    var pixelfraction = 0;
    var xvalues = new Array(1);
    var yvalues = new Array(1);
    var point = 0;
    var whatsides = "";
    var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x,2)));
    if ((intersect >= y) && (intersect < (y+1)))
    
    {
        whatsides = "Left";
        xvalues[point] = 0;
        yvalues[point] = intersect - y;
        point = point + 1;
        
    }
    
    var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y+1,2)));
    if ((intersect >= x) && (intersect < (x+1)))
    
    {
        whatsides = whatsides + "Top";
        xvalues[point] = intersect - x;
        yvalues[point] = 1;
        point = point + 1;
        
    }
    
    var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(x+1,2)));
    if ((intersect >= y) && (intersect < (y+1)))
    
    {
        whatsides = whatsides + "Right";
        xvalues[point] = 1;
        yvalues[point] = intersect - y;
        point = point + 1;
        
    }
    
    var intersect = Math.sqrt((Math.pow(r,2) - Math.pow(y,2)));
    if ((intersect >= x) && (intersect < (x+1)))
    
    {
        whatsides = whatsides + "Bottom";
        xvalues[point] = intersect - x;
        yvalues[point] = 0;
        
    }
    
    switch (whatsides)
    
    {
        case "LeftRight":
        pixelfraction = Math.min(yvalues[0],yvalues[1]) + ((Math.max(yvalues[0],yvalues[1]) - Math.min(yvalues[0],yvalues[1]))/2);
        break;
        case "TopRight":
        pixelfraction = 1-(((1-xvalues[0])*(1-yvalues[1]))/2);
        break;
        case "TopBottom":
        pixelfraction = Math.min(xvalues[0],xvalues[1]) + ((Math.max(xvalues[0],xvalues[1]) - Math.min(xvalues[0],xvalues[1]))/2);
        break;
        case "LeftBottom":
        pixelfraction = (yvalues[0]*xvalues[1])/2;
        break;
        default:
        pixelfraction = 1;
        
    }
    
    return pixelfraction;
    
}

function rgb2Hex(rgbColour)

{
    try
    {
        var rgbArray = rgb2Array(rgbColour);
        var red = parseInt(rgbArray[0]);
        var green = parseInt(rgbArray[1]);
        var blue = parseInt(rgbArray[2]);
        var hexColour = "#" + IntToHex(red) + IntToHex(green) + IntToHex(blue);
        
    }
    
    catch(e)
    {
        alert("There was an error converting the RGB value to Hexadecimal in function rgb2Hex");
        
    }
    
    return hexColour;
    
}

function rgb2Array(rgbColour)

{
    var rgbValues = rgbColour.substring(4, rgbColour.indexOf(")"));
    var rgbArray = rgbValues.split(", ");
    return rgbArray;
    
}

function setOpacity(obj, opacity)

{
    var isSafari = ((navigator.userAgent.toLowerCase().indexOf('safari')!=-1)&&(navigator.userAgent.toLowerCase().indexOf('mac')!=-1))?true:false;
    opacity = (opacity == 100)?99.999:opacity;
    if(isSafari && obj.tagName != "IFRAME")
    
    {
        var rgbArray = rgb2Array(obj.style.backgroundColor);
        var red = parseInt(rgbArray[0]);
        var green = parseInt(rgbArray[1]);
        var blue = parseInt(rgbArray[2]);
        obj.style.backgroundColor = "rgba(" + red + ", " + green + ", " + blue + ", " + opacity/100 + ")";
        
    }
    
    else if(typeof(obj.style.opacity) != "undefined")
    
    {
        obj.style.opacity = opacity/100;
        
    }
    
    else if(typeof(obj.style.MozOpacity) != "undefined")
    
    {
        obj.style.MozOpacity = opacity/100;
        
    }
    
    else if(typeof(obj.style.filter) != "undefined")
    
    {
        obj.style.filter = "alpha(opacity:" + opacity + ")";
        
    }
    
    else if(typeof(obj.style.KHTMLOpacity) != "undefined")
    
    {
        obj.style.KHTMLOpacity = opacity/100;
        
    }
    
    
}

function inArray(array, value)

{
    for(var i = 0;
    i < array.length;
    i++)
    {
        if (array[i] === value) return i;
        
    }
    
    return false;
    
}

function inArrayKey(array, value)

{
    for(key in array)
    {
        if(key === value) return true;
        
    }
    
    return false;
    
}

function format_colour(colour)

{
    var returnColour = "#ffffff";
    if(colour != "" && colour != "transparent")
    
    {
        if(colour.substr(0, 3) == "rgb")
        
        {
            returnColour = rgb2Hex(colour);
            
        }
        
        else if(colour.length == 4)
        
        {
            returnColour = "#" + colour.substring(1, 2) + colour.substring(1, 2) + colour.substring(2, 3) + colour.substring(2, 3) + colour.substring(3, 4) + colour.substring(3, 4);
            
        }
        
        else
        
        {
            returnColour = colour;
            
        }
        
        
    }
    
    return returnColour;
    
}

function get_style(obj, property, propertyNS)

{
    var isSafari = ((navigator.userAgent.toLowerCase().indexOf('safari')!=-1)&&(navigator.userAgent.toLowerCase().indexOf('mac')!=-1))?true:false;
    try
    
    {
        if(obj.currentStyle)
        
        {
            var returnVal = eval("obj.currentStyle." + property);
            
        }
        
        else
        
        {
            if(isSafari && obj.style.display == "none")
            
            {
                obj.style.display = "";
                var wasHidden = true;
                
            }
            
            var returnVal = document.defaultView.getComputedStyle(obj, '').getPropertyValue(propertyNS);
            if(isSafari && wasHidden)
            
            {
                obj.style.display = "none";
                
            }
            
            
        }
        
        
    }
    
    catch(e)
    
    {
        
    }
    
    return returnVal;
    
}

function newCurvyError(errorMessage)

{
    return new Error("curvyCorners Error:\n" + errorMessage)
    
}

/*
 * Copyright 2007 by Tobia Conforto <tobia.conforto@linux.it>
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General
 * Public License as published by the Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Versions: 0.1    2007-08-19  Initial release
 *                  2008-08-21  Re-released under GPL v2
 *           0.1.1  2008-09-18  Compatibility with prototype.js
 */

jQuery.fn.crossSlide = function(opts, plan, divtagname) {
	var self = this,
			self_width = this.width(),
			self_height = this.height();

	// generic utilities
	function format(str) {
		for (var i = 1; i < arguments.length; i++)
			str = str.replace(new RegExp('\\{' + (i-1) + '}', 'g'), arguments[i]);
		return str;
	}

	function dump_obj(o) {
		var s = '{ ';
		for (var n in o)
			s += n + ': ' + o[n] + ', ';
		return (s == '{ ' ? '{}' : s.slice(0, -2) + ' }');
	}
	

	// first preload all the images, while getting their actual width and height
	(function(proceed) {
			  
	    //Intercalate images from page
		var arrDirections = ["up","down","left","right"];
		var intDirLength = arrDirections.length + 1;
		$(divtagname).children().each(function() {
			var intRandom = Math.floor(Math.random()*intDirLength);
			//alert(arrDirections[0]);
			var tmpItem = {
				src : $(this).attr("src"),
				dir : arrDirections[intRandom]
			}
			plan.push(tmpItem);
		});

		var n_loaded = 0;
		function loop(i, img) {
			// for (i = 0; i < plan.length; i++) but with independent var i, img (for the closures)
			img.onload = function(e) {
				n_loaded++;
				plan[i].width = img.width;
				plan[i].height = img.height;
				if (n_loaded == plan.length)
					proceed();
			}
			img.src = plan[i].src;
			if (i + 1 < plan.length)
				loop(i + 1, new Image());
		}
		loop(0, new Image());

	})(function() {  // then proceed

		// utility to parse "from" and "to" parameters
		function parse_position_param(param) {
			var zoom = 1;
			var tokens = param.replace(/^\s*|\s*$/g, '').split(/\s+/);
			if (tokens.length > 3) throw new Error();
			if (tokens[0] == 'center')
				if (tokens.length == 1)
					tokens = ['center', 'center'];
				else if (tokens.length == 2 && tokens[1].match(/^[\d.]+x$/i))
					tokens = ['center', 'center', tokens[1]];
			if (tokens.length == 3)
				zoom = parseFloat(tokens[2].match(/^([\d.]+)x$/i)[1]);
			var pos = tokens[0] + ' ' + tokens[1];
			if (pos == 'left top'      || pos == 'top left')      return { xrel:  0, yrel:  0, zoom: zoom };
			if (pos == 'left center'   || pos == 'center left')   return { xrel:  0, yrel: .5, zoom: zoom };
			if (pos == 'left bottom'   || pos == 'bottom left')   return { xrel:  0, yrel:  1, zoom: zoom };
			if (pos == 'center top'    || pos == 'top center')    return { xrel: .5, yrel:  0, zoom: zoom };
			if (pos == 'center center')                           return { xrel: .5, yrel: .5, zoom: zoom };
			if (pos == 'center bottom' || pos == 'bottom center') return { xrel: .5, yrel:  1, zoom: zoom };
			if (pos == 'right top'     || pos == 'top right')     return { xrel:  1, yrel:  0, zoom: zoom };
			if (pos == 'right center'  || pos == 'center right')  return { xrel:  1, yrel: .5, zoom: zoom };
			if (pos == 'right bottom'  || pos == 'bottom right')  return { xrel:  1, yrel:  1, zoom: zoom };
			return {
				xrel: parseInt(tokens[0].match(/^(\d+)%$/)[1]) / 100,
				yrel: parseInt(tokens[1].match(/^(\d+)%$/)[1]) / 100,
				zoom: zoom
			};
		}

		// utility to compute the css for a given phase between p.from and p.to
		// phase = 1: begin fade-in,  2: end fade-in,  3: begin fade-out,  4: end fade-out
		function position_to_css(p, phase) {
			switch (phase) {
				case 1:
					var pos = 0;
					break;
				case 2:
					var pos = fade_ms / (p.time_ms + 2 * fade_ms);
					break;
				case 3:
					var pos = 1 - fade_ms / (p.time_ms + 2 * fade_ms);
					break;
				case 4:
					var pos = 1;
					break;
			}
			return {
				left:   Math.round(p.from.left   + pos * (p.to.left   - p.from.left  )),
				top:    Math.round(p.from.top    + pos * (p.to.top    - p.from.top   )),
				width:  Math.round(p.from.width  + pos * (p.to.width  - p.from.width )),
				height: Math.round(p.from.height + pos * (p.to.height - p.from.height))
			};
		}

		// check global params
		if (! opts.fade)
			throw 'Missing fade parameter.';
		if (opts.speed && opts.sleep)
			throw 'You cannot set both speed and sleep at the same time.';
		// conversion from sec to ms; from px/sec to px/ms
		var fade_ms = Math.round(opts.fade * 1000);
		if (opts.sleep)
			var sleep = Math.round(opts.sleep * 1000);
		if (opts.speed)
			var speed = opts.speed / 1000,
					fade_px = Math.round(fade_ms * speed);

		// a debug: true option may be added to get a dump of the generated JavaScript code
		if (opts.debug)
			var debug = jQuery('<pre><hr/></pre>');

		// set container css
		self.empty().css({
			overflow: 'hidden',
			padding: 0
		});
		if (! self.css('position').match(/absolute|relative|fixed/))
			self.css({ position: 'relative' })

		// prepare each image
		for (var i = 0; i < plan.length; ++i) {

			var p = plan[i];
			if (! p.src)
				throw format('Missing src parameter in picture {0}.', i + 1);

			if (speed) { // speed/dir mode

				// check parameters and translate speed/dir mode into full mode (from/to/time)
				switch (p.dir) {
					case 'up':
						p.from = { xrel: .5, yrel: 0, zoom: 1 };
						p.to   = { xrel: .5, yrel: 1, zoom: 1 };
						var slide_px = p.height - self_height - 2 * fade_px;
						break;
					case 'down':
						p.from = { xrel: .5, yrel: 1, zoom: 1 };
						p.to   = { xrel: .5, yrel: 0, zoom: 1 };
						var slide_px = p.height - self_height - 2 * fade_px;
						break;
					case 'left':
						p.from = { xrel: 0, yrel: .5, zoom: 1 };
						p.to   = { xrel: 1, yrel: .5, zoom: 1 };
						var slide_px = p.width - self_width - 2 * fade_px;
						break;
					case 'right':
						p.from = { xrel: 1, yrel: .5, zoom: 1 };
						p.to   = { xrel: 0, yrel: .5, zoom: 1 };
						var slide_px = p.width - self_width - 2 * fade_px;
						break;
					default:
						//throw format('Missing or malformed "dir" parameter in picture {0}.', i + 1);
						p.from = { xrel: .5, yrel: 1, zoom: 1 };
						p.to   = { xrel: .5, yrel: 0, zoom: 1 };
						var slide_px = p.height - self_height - 2 * fade_px;
						break;
				}
				if (slide_px <= 0)
					throw format('Picture number {0} is too short for the desired fade duration.', i + 1);
				p.time_ms = Math.round(slide_px / speed);

			} else if (! sleep) { // full mode

				// check and parse parameters
				if (! p.from || ! p.to || ! p.time)
					throw format('Missing either speed/sleep option, or from/to/time params in picture {0}.', i + 1);
				try {
					p.from = parse_position_param(p.from)
				} catch (e) {
					throw format('Malformed "from" parameter in picture {0}.', i + 1);
				}
				try {
					p.to = parse_position_param(p.to)
				} catch (e) {
					throw format('Malformed "to" parameter in picture {0}.', i + 1);
				}
				if (! p.time)
					throw format('Missing "time" parameter in picture {0}.', i + 1);
				p.time_ms = Math.round(p.time * 1000)
			}

			// precalculate left/top/width/height bounding values
			if (p.from)
				jQuery.each([ p.from, p.to ], function(i, from_to) {
					from_to.width  = Math.round(p.width  * from_to.zoom);
					from_to.height = Math.round(p.height * from_to.zoom);
					from_to.left   = Math.round((self_width  - from_to.width)  * from_to.xrel);
					from_to.top    = Math.round((self_height - from_to.height) * from_to.yrel);
				});

			// append the image element to the container
			jQuery(format('<img src="{0}"/>', p.src)).appendTo(self).css({
				position: 'absolute',
				visibility: 'hidden'
			});
		}
		speed = undefined;  // speed mode has now been translated to full mode

		var imgs = self.children();

		// show first image
		imgs.eq(0).css({ visibility: 'visible' });
		if (! sleep)
			imgs.eq(0).css(position_to_css(plan[0], 2));

		// create animation chain
		function create_chain(i, chainf) {
			// building the chain backwards, or inside out

			if (i % 2 == 0) {
				if (sleep) {

					// still image sleep

					var i_sleep = i / 2,
							i_hide = (i_sleep - 1 + plan.length) % plan.length,
							img_sleep = imgs.eq(i_sleep),
							img_hide = imgs.eq(i_hide);

					var newf = function() {
						img_hide.css('visibility', 'hidden');
						setTimeout(chainf, sleep);
					};

					if (debug)
						debug.prepend('<hr/>'
							+ format("img[{0}].css(visibility, hidden)\n", i_hide)
							+ format("setTimeout(&#9660;, {0})", sleep));

				} else {

					// single image slide

					var i_slide = i / 2,
							i_hide = (i_slide - 1 + plan.length) % plan.length,
							img_slide = imgs.eq(i_slide),
							img_hide = imgs.eq(i_hide),
							time = plan[i_slide].time_ms,
							slide_anim = position_to_css(plan[i_slide], 3);

					var newf = function() {
						img_hide.css('visibility', 'hidden');
						img_slide.animate(slide_anim, time, 'linear', chainf);
					};

					if (debug)
						debug.prepend('<hr/>'
							+ format("img[{0}].css(visibility, hidden)\n", i_hide)
							+ format("img[{0}].animate({1}, {2}, linear, &#9660;)", i_slide, dump_obj(slide_anim), time));

				}
			} else {
				if (sleep) {

					// still image cross-fade

					var i_from = Math.floor(i / 2),
							i_to = Math.ceil(i / 2) % plan.length,
							img_from = imgs.eq(i_from),
							img_to = imgs.eq(i_to),
							from_anim = {},
							to_init = { visibility: 'visible' },
							to_anim = {};

					if (i_to > i_from) {
						to_init.opacity = 0;
						to_anim.opacity = 1;
					} else {
						from_anim.opacity = 0;
					}

					var newf = function() {
						img_to.css(to_init);
						if (from_anim.opacity != undefined)
							img_from.animate(from_anim, fade_ms, 'linear', chainf);
						else
							img_to.animate(to_anim, fade_ms, 'linear', chainf);
					};

					if (debug)
						debug.prepend('<hr/>'
							+ format("img[{0}].css({1})\n", i_to, dump_obj(to_init))
							+ (from_anim.opacity != undefined
								? format("img[{0}].animate({1}, {2}, linear, &#9660;)", i_from, dump_obj(from_anim), fade_ms)
								: format("img[{0}].animate({1}, {2}, linear, &#9660;)", i_to, dump_obj(to_anim), fade_ms)));

				} else {

					// cross-slide + cross-fade

					var i_from = Math.floor(i / 2),
							i_to = Math.ceil(i / 2) % plan.length,
							img_from = imgs.eq(i_from),
							img_to = imgs.eq(i_to),
							from_anim = position_to_css(plan[i_from], 4),
							to_init = position_to_css(plan[i_to], 1),
							to_anim = position_to_css(plan[i_to], 2);

					if (i_to > i_from) {
						to_init.opacity = 0;
						to_anim.opacity = 1;
					} else {
						from_anim.opacity = 0;
					}
					to_init.visibility = 'visible';

					var newf = function() {
						img_from.animate(from_anim, fade_ms, 'linear');
						img_to.css(to_init);
						img_to.animate(to_anim, fade_ms, 'linear', chainf);
					};

					if (debug)
						debug.prepend('<hr/>'
							+ format("img[{0}].animate({1}, {2}, linear)\n", i_from, dump_obj(from_anim), fade_ms)
							+ format("img[{0}].css({1})\n", i_to, dump_obj(to_init))
							+ format("img[{0}].animate({1}, {2}, linear, &#9660;)", i_to, dump_obj(to_anim), fade_ms));

				}
			}
			if (i > 0)
				return create_chain(i - 1, newf);
			else
				return newf;
		}
		var animation = create_chain(plan.length * 2 - 1, function() { return animation(); });

		// show debug window, if enabled
		if (debug)
			jQuery(window.open('', 'debug', 'width=600,height=500,menubar=no,toolbar=no,directories=no,'
					+ 'location=no,status=no,scrollbars=yes,resizable=yes').document.body)
				.empty()
				.append(debug);

		// start animation
		animation();

	});

	return self;
};


/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox() 
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.facebox('some html')
 *
 *  The above will open a facebox with "some html" as the content.
 *    
 *    jQuery.facebox(function($) { 
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page or image:
 *  
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ image: 'dude.jpg' })
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax)
    else if (data.image) fillFaceboxFromImage(data.image)
    else if (data.div) fillFaceboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage : '/myImages/loading.gif',
      closeImage   : '/myImages/closelabel.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
                <div class="content"> \
                </div> \
                <div class="footer"> \
                  <a href="#" class="close"> \
                    <img alt="close" src="/myImages/closelabel.gif" title="close" class="close_image" /> \
                  </a> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img alt="bpm" src="'+$.facebox.settings.loadingImage+'"/></div>')

      $('#facebox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	385.5
      }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.facebox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img alt="bpm" src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('facebox_overlay').length == 0) 
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide") 
      $("#facebox_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })

})(jQuery);






