/*
 * jQuery 1.2.6 - New Wave Javascript
 *
 * Copyright (c) 2008 John Resig (jquery.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008-05-24 14:22:17 -0400 (Sat, 24 May 2008) $
 * $Rev: 5685 $
 */
(function(){var _jQuery=window.jQuery,_$=window.$;var jQuery=window.jQuery=window.$=function(selector,context){return new jQuery.fn.init(selector,context);};var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/,isSimple=/^.[^:#\[\.]*$/,undefined;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1])selector=jQuery.clean([match[1]],context);else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3])return jQuery().find(selector);return jQuery(elem);}selector=[];}}else
return jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(jQuery.makeArray(selector));},jquery:"1.2.6",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;return jQuery.inArray(elem&&elem.jquery?elem[0]:elem,this);},attr:function(name,value,type){var options=name;if(name.constructor==String)if(value===undefined)return this[0]&&jQuery[type||"attr"](this[0],name);else{options={};options[name]=value;}return this.each(function(i){for(name in options)jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));});},css:function(key,value){if((key=='width'||key=='height')&&parseFloat(value)<0)value=undefined;return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null)return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return ret;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1)this.appendChild(elem);});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1)this.insertBefore(elem,this.firstChild);});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else
return this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){if(this.nodeType==3)return;var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String)if(isSimple.test(selector))return this.pushStack(jQuery.multiFilter(selector,this,true));else
selector=jQuery.multiFilter(selector,this);var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),typeof selector=='string'?jQuery(selector):jQuery.makeArray(selector))));},is:function(selector){return!!selector&&jQuery.multiFilter(selector,this).length>0;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i<max;i++){var option=options[i];if(option.selected){value=jQuery.browser.msie&&!option.attributes.value.specified?option.text:option.value;if(one)return value;values.push(value);}}return values;}else
return(this[0].value||"").replace(/\r/g,"");}return undefined;}if(value.constructor==Number)value+='';return this.each(function(){if(this.nodeType!=1)return;if(value.constructor==Array&&/radio|checkbox/.test(this.type))this.checked=(jQuery.inArray(this.value,value)>=0||jQuery.inArray(this.name,value)>=0);else if(jQuery.nodeName(this,"select")){var values=jQuery.makeArray(value);jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length)this.selectedIndex=-1;}else
this.value=value;});},html:function(value){return value==undefined?(this[0]?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value===undefined){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data===undefined&&this.length)data=jQuery.data(this[0],key);return data===undefined&&parts[1]?this.data(parts[0]):data;}else
return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse)elems.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script"))scripts=scripts.add(elem);else{if(elem.nodeType==1)scripts=scripts.add(jQuery("script",elem).remove());callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.fn.init.prototype=jQuery.fn;function evalScript(i,elem){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else
jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}function now(){return+new Date;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function")target={};if(length==i){target=this;--i;}for(;i<length;i++)if((options=arguments[i])!=null)for(var name in options){var src=target[name],copy=options[name];if(target===copy)continue;if(deep&&copy&&typeof copy=="object"&&!copy.nodeType)target[name]=jQuery.extend(deep,src||(copy.length!=null?[]:{}),copy);else if(copy!==undefined)target[name]=copy;}return target;};var expando="jQuery"+now(),uuid=0,windowData={},exclude=/z-?index|font-?weight|opacity|zoom|line-?height/i,defaultView=document.defaultView||{};jQuery.extend({noConflict:function(deep){window.$=_$;if(deep)window.jQuery=_jQuery;return jQuery;},isFunction:function(fn){return!!fn&&typeof fn!="string"&&!fn.nodeName&&fn.constructor!=Array&&/^[\s[]?function/.test(fn+"");},isXMLDoc:function(elem){return elem.documentElement&&!elem.body||elem.tagName&&elem.ownerDocument&&!elem.ownerDocument.body;},globalEval:function(data){data=jQuery.trim(data);if(data){var head=document.getElementsByTagName("head")[0]||document.documentElement,script=document.createElement("script");script.type="text/javascript";if(jQuery.browser.msie)script.text=data;else
script.appendChild(document.createTextNode(data));head.insertBefore(script,head.firstChild);head.removeChild(script);}},nodeName:function(elem,name){return elem.nodeName&&elem.nodeName.toUpperCase()==name.toUpperCase();},cache:{},data:function(elem,name,data){elem=elem==window?windowData:elem;var id=elem[expando];if(!id)id=elem[expando]=++uuid;if(name&&!jQuery.cache[id])jQuery.cache[id]={};if(data!==undefined)jQuery.cache[id][name]=data;return name?jQuery.cache[id][name]:id;},removeData:function(elem,name){elem=elem==window?windowData:elem;var id=elem[expando];if(name){if(jQuery.cache[id]){delete jQuery.cache[id][name];name="";for(name in jQuery.cache[id])break;if(!name)jQuery.removeData(elem);}}else{try{delete elem[expando];}catch(e){if(elem.removeAttribute)elem.removeAttribute(expando);}delete jQuery.cache[id];}},each:function(object,callback,args){var name,i=0,length=object.length;if(args){if(length==undefined){for(name in object)if(callback.apply(object[name],args)===false)break;}else
for(;i<length;)if(callback.apply(object[i++],args)===false)break;}else{if(length==undefined){for(name in object)if(callback.call(object[name],name,object[name])===false)break;}else
for(var value=object[0];i<length&&callback.call(value,i,value)!==false;value=object[++i]){}}return object;},prop:function(elem,value,type,i,name){if(jQuery.isFunction(value))value=value.call(elem,i);return value&&value.constructor==Number&&type=="curCSS"&&!exclude.test(name)?value+"px":value;},className:{add:function(elem,classNames){jQuery.each((classNames||"").split(/\s+/),function(i,className){if(elem.nodeType==1&&!jQuery.className.has(elem.className,className))elem.className+=(elem.className?" ":"")+className;});},remove:function(elem,classNames){if(elem.nodeType==1)elem.className=classNames!=undefined?jQuery.grep(elem.className.split(/\s+/),function(className){return!jQuery.className.has(classNames,className);}).join(" "):"";},has:function(elem,className){return jQuery.inArray(className,(elem.className||elem).toString().split(/\s+/))>-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options)elem.style[name]=old[name];},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible"))getWH();else
jQuery.swap(elem,props,getWH);return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret,style=elem.style;function color(elem){if(!jQuery.browser.safari)return false;var ret=defaultView.getComputedStyle(elem,null);return!ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=style.outline;style.outline="0 solid black";style.outline=save;}if(name.match(/float/i))name=styleFloat;if(!force&&style&&style[name])ret=style[name];else if(defaultView.getComputedStyle){if(name.match(/float/i))name="float";name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var computedStyle=defaultView.getComputedStyle(elem,null);if(computedStyle&&!color(elem))ret=computedStyle.getPropertyValue(name);else{var swap=[],stack=[],a=elem,i=0;for(;a&&color(a);a=a.parentNode)stack.unshift(a);for(;i<stack.length;i++)if(color(stack[i])){swap[i]=stack[i].style.display;stack[i].style.display="block";}ret=name=="display"&&swap[stack.length-1]!=null?"none":(computedStyle&&computedStyle.getPropertyValue(name))||"";for(i=0;i<swap.length;i++)if(swap[i]!=null)stack[i].style.display=swap[i];}if(name=="opacity"&&ret=="")ret="1";}else if(elem.currentStyle){var camelCase=name.replace(/\-(\w)/g,function(all,letter){return letter.toUpperCase();});ret=elem.currentStyle[name]||elem.currentStyle[camelCase];if(!/^\d+(px)?$/i.test(ret)&&/^\d/.test(ret)){var left=style.left,rsLeft=elem.runtimeStyle.left;elem.runtimeStyle.left=elem.currentStyle.left;style.left=ret||0;ret=style.pixelLeft+"px";style.left=left;elem.runtimeStyle.left=rsLeft;}}return ret;},clean:function(elems,context){var ret=[];context=context||document;if(typeof context.createElement=='undefined')context=context.ownerDocument||context[0]&&context[0].ownerDocument||document;jQuery.each(elems,function(i,elem){if(!elem)return;if(elem.constructor==Number)elem+='';if(typeof elem=="string"){elem=elem.replace(/(<(\w+)[^>]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+"></"+tag+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!tags.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!tags.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!tags.indexOf("<td")||!tags.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!tags.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||jQuery.browser.msie&&[1,"div<div>","</div>"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){var tbody=!tags.indexOf("<table")&&tags.indexOf("<tbody")<0?div.firstChild&&div.firstChild.childNodes:wrap[1]=="<table>"&&tags.indexOf("<tbody")<0?div.childNodes:[];for(var j=tbody.length-1;j>=0;--j)if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length)tbody[j].parentNode.removeChild(tbody[j]);if(/^\s/.test(elem))div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select")))return;if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options)ret.push(elem);else
ret=jQuery.merge(ret,elem);});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8)return undefined;var notxml=!jQuery.isXMLDoc(elem),set=value!==undefined,msie=jQuery.browser.msie;name=notxml&&jQuery.props[name]||name;if(elem.tagName){var special=/href|src|style/.test(name);if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(name in elem&&notxml&&!special){if(set){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem[name]=value;}if(jQuery.nodeName(elem,"form")&&elem.getAttributeNode(name))return elem.getAttributeNode(name).nodeValue;return elem[name];}if(msie&&notxml&&name=="style")return jQuery.attr(elem.style,"cssText",value);if(set)elem.setAttribute(name,""+value);var attr=msie&&notxml&&special?elem.getAttribute(name,2):elem.getAttribute(name);return attr===null?undefined:attr;}if(msie&&name=="opacity"){if(set){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(value)+''=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100)+'':"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(set&&name.indexOf('fontWeight')<0){elem[name]=value;}return elem[name];},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(array!=null){var i=array.length;if(i==null||array.split||array.setInterval||array.call)ret[0]=array;else
while(i)ret[--i]=array[i];}return ret;},inArray:function(elem,array){for(var i=0,length=array.length;i<length;i++)if(array[i]===elem)return i;return-1;},merge:function(first,second){var i=0,elem,pos=first.length;if(jQuery.browser.msie){while(elem=second[i++])if(elem.nodeType!=8)first[pos++]=elem;}else
while(elem=second[i++])first[pos++]=elem;return first;},unique:function(array){var ret=[],done={};try{for(var i=0,length=array.length;i<length;i++){var id=jQuery.data(array[i]);if(!done[id]){done[id]=true;ret.push(array[i]);}}}catch(e){ret=array;}return ret;},grep:function(elems,callback,inv){var ret=[];for(var i=0,length=elems.length;i<length;i++)if(!inv!=!callback(elems[i],i))ret.push(elems[i]);return ret;},map:function(elems,callback){var ret=[];for(var i=0,length=elems.length;i<length;i++){var value=callback(elems[i],i);if(value!=null)ret[ret.length]=value;}return ret.concat.apply([],ret);}});var userAgent=navigator.userAgent.toLowerCase();jQuery.browser={version:(userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/webkit/.test(userAgent),opera:/opera/.test(userAgent),msie:/msie/.test(userAgent)&&!/opera/.test(userAgent),mozilla:/mozilla/.test(userAgent)&&!/(compatible|webkit)/.test(userAgent)};var styleFloat=jQuery.browser.msie?"styleFloat":"cssFloat";jQuery.extend({boxModel:!jQuery.browser.msie||document.compatMode=="CSS1Compat",props:{"for":"htmlFor","class":"className","float":styleFloat,cssFloat:styleFloat,styleFloat:styleFloat,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing"}});jQuery.each({parent:function(elem){return elem.parentNode;},parents:function(elem){return jQuery.dir(elem,"parentNode");},next:function(elem){return jQuery.nth(elem,2,"nextSibling");},prev:function(elem){return jQuery.nth(elem,2,"previousSibling");},nextAll:function(elem){return jQuery.dir(elem,"nextSibling");},prevAll:function(elem){return jQuery.dir(elem,"previousSibling");},siblings:function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},children:function(elem){return jQuery.sibling(elem.firstChild);},contents:function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}},function(name,fn){jQuery.fn[name]=function(selector){var ret=jQuery.map(this,fn);if(selector&&typeof selector=="string")ret=jQuery.multiFilter(selector,ret);return this.pushStack(jQuery.unique(ret));};});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(){var args=arguments;return this.each(function(){for(var i=0,length=args.length;i<length;i++)jQuery(args[i])[original](this);});};});jQuery.each({removeAttr:function(name){jQuery.attr(this,name,"");if(this.nodeType==1)this.removeAttribute(name);},addClass:function(classNames){jQuery.className.add(this,classNames);},removeClass:function(classNames){jQuery.className.remove(this,classNames);},toggleClass:function(classNames){jQuery.className[jQuery.className.has(this,classNames)?"remove":"add"](this,classNames);},remove:function(selector){if(!selector||jQuery.filter(selector,[this]).r.length){jQuery("*",this).add(this).each(function(){jQuery.event.remove(this);jQuery.removeData(this);});if(this.parentNode)this.parentNode.removeChild(this);}},empty:function(){jQuery(">*",this).remove();while(this.firstChild)this.removeChild(this.firstChild);}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});function num(elem,prop){return elem[0]&&parseInt(jQuery.curCSS(elem[0],prop,true),10)||0;}var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return i<m[3]-0;},gt:function(a,i,m){return i>m[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return!jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return!a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return!a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&context.nodeType!=1&&context.nodeType!=9)return[];context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false,re=quickChild,m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j<rl;j++){var n=m=="~"||m=="+"?ret[j].nextSibling:ret[j].firstChild;for(;n;n=n.nextSibling)if(n.nodeType==1){var id=jQuery.data(n);if(m=="~"&&merge[id])break;if(!nodeName||n.nodeName.toUpperCase()==nodeName){if(m=="~")merge[id]=true;r.push(n);}if(m=="+")break;}}ret=r;t=jQuery.trim(t.replace(re,""));foundToken=true;}}if(t&&!foundToken){if(!t.indexOf(",")){if(context==ret[0])ret.shift();done=jQuery.merge(done,ret);r=ret=[context];t=" "+t.substr(1,t.length);}else{var re2=quickID;var m=re2.exec(t);if(m){m=[0,m[2],m[3],m[1]];}else{re2=quickClass;m=re2.exec(t);}m[2]=m[2].replace(/\\/g,"");var elem=ret[ret.length-1];if(m[1]=="#"&&elem&&elem.getElementById&&!jQuery.isXMLDoc(elem)){var oid=elem.getElementById(m[2]);if((jQuery.browser.msie||jQuery.browser.opera)&&oid&&typeof oid.id=="string"&&oid.id!=m[2])oid=jQuery('[@id="'+m[2]+'"]',elem)[0];ret=r=oid&&(!m[3]||jQuery.nodeName(oid,m[3]))?[oid]:[];}else{for(var i=0;ret[i];i++){var tag=m[1]=="#"&&m[3]?m[3]:m[1]!=""||m[0]==""?"*":m[2];if(tag=="*"&&ret[i].nodeName.toLowerCase()=="object")tag="param";r=jQuery.merge(r,ret[i].getElementsByTagName(tag));}if(m[1]==".")r=jQuery.classFilter(r,m[2]);if(m[1]=="#"){var tmp=[];for(var i=0;r[i];i++)if(r[i].getAttribute("id")==m[2]){tmp=[r[i]];break;}r=tmp;}ret=r;}t=t.replace(re2,"");}}if(t){var val=jQuery.filter(t,r);ret=r=val.r;t=jQuery.trim(val.t);}}if(t)ret=[];if(ret&&context==ret[0])ret.shift();done=jQuery.merge(done,ret);return done;},classFilter:function(r,m,not){m=" "+m+" ";var tmp=[];for(var i=0;r[i];i++){var pass=(" "+r[i].className+" ").indexOf(m)>=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i<rl;i++){var a=r[i],z=a[jQuery.props[m[2]]||m[2]];if(z==null||/href|src|selected/.test(m[2]))z=jQuery.attr(a,m[2])||'';if((type==""&&!!z||type=="="&&z==m[5]||type=="!="&&z!=m[5]||type=="^="&&z&&!z.indexOf(m[5])||type=="$="&&z.substr(z.length-m[5].length)==m[5]||(type=="*="||type=="~=")&&z.indexOf(m[5])>=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i<rl;i++){var node=r[i],parentNode=node.parentNode,id=jQuery.data(parentNode);if(!merge[id]){var c=1;for(var n=parentNode.firstChild;n;n=n.nextSibling)if(n.nodeType==1)n.nodeIndex=c++;merge[id]=true;}var add=false;if(first==0){if(node.nodeIndex==last)add=true;}else if((node.nodeIndex-last)%first==0&&(node.nodeIndex-last)/first>=0)add=true;if(add^not)tmp.push(node);}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object")fn=fn[m[2]];if(typeof fn=="string")fn=eval("false||function(a,i){return "+fn+";}");r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}return{r:r,t:t};},dir:function(elem,dir){var matched=[],cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1)matched.push(cur);cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir])if(cur.nodeType==1&&++num==result)break;return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&n!=elem)r.push(n);}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8)return;if(jQuery.browser.msie&&elem.setInterval)elem=window;if(!handler.guid)handler.guid=this.guid++;if(data!=undefined){var fn=handler;handler=this.proxy(fn,function(){return fn.apply(this,arguments);});handler.data=data;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){if(typeof jQuery!="undefined"&&!jQuery.event.triggered)return jQuery.event.handle.apply(arguments.callee.elem,arguments);});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener)elem.addEventListener(type,handle,false);else if(elem.attachEvent)elem.attachEvent("on"+type,handle);}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8)return;var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)=="."))for(var type in events)this.remove(elem,type+(types||""));else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler)delete events[type][handler.guid];else
for(handler in events[type])if(!parts[1]||events[type][handler].type==parts[1])delete events[type][handler];for(ret in events[type])break;if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener)elem.removeEventListener(type,jQuery.data(elem,"handle"),false);else if(elem.detachEvent)elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}ret=null;delete events[type];}}});}for(ret in events)break;if(!ret){var handle=jQuery.data(elem,"handle");if(handle)handle.elem=null;jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type])jQuery("*").add([window,document]).trigger(type,data);}else{if(elem.nodeType==3||elem.nodeType==8)return undefined;var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift({type:type,target:elem,preventDefault:function(){},stopPropagation:function(){},timeStamp:now()});data[0][expando]=true;}data[0].type=type;if(exclusive)data[0].exclusive=true;var handle=jQuery.data(elem,"handle");if(handle)val=handle.apply(elem,data);if((!fn||(jQuery.nodeName(elem,'a')&&type=="click"))&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false)val=false;if(event)data.shift();if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined)val=ret;}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,'a')&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val,ret,namespace,all,handlers;event=arguments[0]=jQuery.event.fix(event||window.event);namespace=event.type.split(".");event.type=namespace[0];namespace=namespace[1];all=!namespace&&!event.exclusive;handlers=(jQuery.data(this,"events")||{})[event.type];for(var j in handlers){var handler=handlers[j];if(all||handler.type==namespace){event.handler=handler;event.data=handler.data;ret=handler.apply(this,arguments);if(val!==false)val=ret;if(ret===false){event.preventDefault();event.stopPropagation();}}}return val;},fix:function(event){if(event[expando]==true)return event;var originalEvent=event;event={originalEvent:originalEvent};var props="altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target timeStamp toElement type view wheelDelta which".split(" ");for(var i=props.length;i;i--)event[props[i]]=originalEvent[props[i]];event[expando]=true;event.preventDefault=function(){if(originalEvent.preventDefault)originalEvent.preventDefault();originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation)originalEvent.stopPropagation();originalEvent.cancelBubble=true;};event.timeStamp=event.timeStamp||now();if(!event.target)event.target=event.srcElement||document;if(event.target.nodeType==3)event.target=event.target.parentNode;if(!event.relatedTarget&&event.fromElement)event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode))event.which=event.charCode||event.keyCode;if(!event.metaKey&&event.ctrlKey)event.metaKey=event.ctrlKey;if(!event.which&&event.button)event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));return event;},proxy:function(fn,proxy){proxy.guid=fn.guid=fn.guid||proxy.guid||this.guid++;return proxy;},special:{ready:{setup:function(){bindReady();return;},teardown:function(){return;}},mouseenter:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie)return false;jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie)return false;jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this))return true;event.type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){var one=jQuery.event.proxy(fn||data,function(event){jQuery(this).unbind(event,one);return(fn||data).apply(this,arguments);});return this.each(function(){jQuery.event.add(this,type,one,fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){return this[0]&&jQuery.event.trigger(type,data,this[0],false,fn);},toggle:function(fn){var args=arguments,i=1;while(i<args.length)jQuery.event.proxy(fn,args[i++]);return this.click(jQuery.event.proxy(fn,function(event){this.lastToggle=(this.lastToggle||0)%i;event.preventDefault();return args[this.lastToggle++].apply(this,arguments)||false;}));},hover:function(fnOver,fnOut){return this.bind('mouseenter',fnOver).bind('mouseleave',fnOut);},ready:function(fn){bindReady();if(jQuery.isReady)fn.call(document,jQuery);else
jQuery.readyList.push(function(){return fn.call(this,jQuery);});return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.call(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound)return;readyBound=true;if(document.addEventListener&&!jQuery.browser.opera)document.addEventListener("DOMContentLoaded",jQuery.ready,false);if(jQuery.browser.msie&&window==top)(function(){if(jQuery.isReady)return;try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return;}jQuery.ready();})();if(jQuery.browser.opera)document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady)return;for(var i=0;i<document.styleSheets.length;i++)if(document.styleSheets[i].disabled){setTimeout(arguments.callee,0);return;}jQuery.ready();},false);if(jQuery.browser.safari){var numStyles;(function(){if(jQuery.isReady)return;if(document.readyState!="loaded"&&document.readyState!="complete"){setTimeout(arguments.callee,0);return;}if(numStyles===undefined)numStyles=jQuery("style, link[rel=stylesheet]").length;if(document.styleSheets.length!=numStyles){setTimeout(arguments.callee,0);return;}jQuery.ready();})();}jQuery.event.add(window,"load",jQuery.ready);}jQuery.each(("blur,focus,load,resize,scroll,unload,click,dblclick,"+"mousedown,mouseup,mousemove,mouseover,mouseout,change,select,"+"submit,keydown,keypress,keyup,error").split(","),function(i,name){jQuery.fn[name]=function(fn){return fn?this.bind(name,fn):this.trigger(name);};});var withinElement=function(event,elem){var parent=event.relatedTarget;while(parent&&parent!=elem)try{parent=parent.parentNode;}catch(error){parent=elem;}return parent==elem;};jQuery(window).bind("unload",function(){jQuery("*").add(document).unbind();});jQuery.fn.extend({_load:jQuery.fn.load,load:function(url,params,callback){if(typeof url!='string')return this._load(url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("<div/>").append(res.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(selector):res.responseText);self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=now();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{url:location.href,global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));var jsonp,jsre=/=\?(&|$)/g,status,data,type=s.type.toUpperCase();if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(type=="GET"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head)head.removeChild(script);};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&type=="GET"){var ts=now();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&type=="GET"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");var remote=/^(?:\w+:)?\/\/([^\/?#]+)/;if(s.dataType=="script"&&type=="GET"&&remote.test(s.url)&&remote.exec(s.url)[1]!=location.host){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset)script.charset=s.scriptCharset;if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xhr=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();if(s.username)xhr.open(type,s.url,s.async,s.username,s.password);else
xhr.open(type,s.url,s.async);try{if(s.data)xhr.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xhr.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;xhr.abort();return false;}if(s.global)jQuery.event.trigger("ajaxSend",[xhr,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xhr&&(xhr.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xhr)&&"error"||s.ifModified&&jQuery.httpNotModified(xhr,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xhr,s.dataType,s.dataFilter);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xhr.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else
jQuery.handleError(s,xhr,status);complete();if(s.async)xhr=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xhr){xhr.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xhr.send(s.data);}catch(e){jQuery.handleError(s,xhr,null,e);}if(!s.async)onreadystatechange();function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xhr,s]);}function complete(){if(s.complete)s.complete(xhr,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xhr,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}return xhr;},handleError:function(s,xhr,status,e){if(s.error)s.error(xhr,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xhr,s,e]);},active:0,httpSuccess:function(xhr){try{return!xhr.status&&location.protocol=="file:"||(xhr.status>=200&&xhr.status<300)||xhr.status==304||xhr.status==1223||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpNotModified:function(xhr,url){try{var xhrRes=xhr.getResponseHeader("Last-Modified");return xhr.status==304||xhrRes==jQuery.lastModified[url]||jQuery.browser.safari&&xhr.status==undefined;}catch(e){}return false;},httpData:function(xhr,type,filter){var ct=xhr.getResponseHeader("content-type"),xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0,data=xml?xhr.responseXML:xhr.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(filter)data=filter(data,type);if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else
for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else
s.push(encodeURIComponent(j)+"="+encodeURIComponent(jQuery.isFunction(a[j])?a[j]():a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none")this.style.display="block";elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle.apply(this,arguments):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1)return false;var opt=jQuery.extend({},optall),p,hidden=jQuery(this).is(":hidden"),self=this;for(p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return opt.complete.call(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else
e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.call(this);}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue)this.queue([]);this.each(function(){for(var i=timers.length-1;i>=0;i--)if(timers[i].elem==this){if(gotoEnd)timers[i](true);timers.splice(i,1);}});if(!gotoEnd)this.dequeue();return this;}});var queue=function(elem,type,array){if(elem){type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array)q=jQuery.data(elem,type+"queue",jQuery.makeArray(array));}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length)q[0].call(this);});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:jQuery.fx.speeds[opt.duration])||jQuery.fx.speeds.def;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false)jQuery(this).dequeue();if(jQuery.isFunction(opt.old))opt.old.call(this);};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig)options.orig={};}});jQuery.fx.prototype={update:function(){if(this.options.step)this.options.step.call(this.elem,this.now,this);(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width")this.elem.style.display="block";},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null)return this.elem[this.prop];var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=now();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;i<timers.length;i++)if(!timers[i]())timers.splice(i--,1);if(!timers.length){clearInterval(jQuery.timerId);jQuery.timerId=null;}},13);}},show:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.show=true;this.custom(0,this.cur());if(this.prop=="width"||this.prop=="height")this.elem.style[this.prop]="1px";jQuery(this.elem).show();},hide:function(){this.options.orig[this.prop]=jQuery.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0);},step:function(gotoEnd){var t=now();if(gotoEnd||t>this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done)this.options.complete.call(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.extend(jQuery.fx,{speeds:{slow:600,fast:200,def:400},step:{scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}}});jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),css=jQuery.curCSS,fixed=css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2)border(offsetParent);if(!fixed&&css(offsetParent,"position")=="fixed")fixed=true;offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if((safari2&&(fixed||css(offsetChild,"position")=="absolute"))||(mozilla&&css(offsetChild,"position")!="absolute"))add(-doc.body.offsetLeft,-doc.body.offsetTop);if(fixed)add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}results={top:top,left:left};}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l,10)||0;top+=parseInt(t,10)||0;}return results;};jQuery.fn.extend({position:function(){var left=0,top=0,results;if(this[0]){var offsetParent=this.offsetParent(),offset=this.offset(),parentOffset=/^body|html$/i.test(offsetParent[0].tagName)?{top:0,left:0}:offsetParent.offset();offset.top-=num(this,'marginTop');offset.left-=num(this,'marginLeft');parentOffset.top+=num(offsetParent,'borderTopWidth');parentOffset.left+=num(offsetParent,'borderLeftWidth');results={top:offset.top-parentOffset.top,left:offset.left-parentOffset.left};}return results;},offsetParent:function(){var offsetParent=this[0].offsetParent;while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&jQuery.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;return jQuery(offsetParent);}});jQuery.each(['Left','Top'],function(i,name){var method='scroll'+name;jQuery.fn[method]=function(val){if(!this[0])return;return val!=undefined?this.each(function(){this==window||this==document?window.scrollTo(!i?val:jQuery(window).scrollLeft(),i?val:jQuery(window).scrollTop()):this[method]=val;}):this[0]==window||this[0]==document?self[i?'pageYOffset':'pageXOffset']||jQuery.boxModel&&document.documentElement[method]||document.body[method]:this[0][method];};});jQuery.each(["Height","Width"],function(i,name){var tl=i?"Left":"Top",br=i?"Right":"Bottom";jQuery.fn["inner"+name]=function(){return this[name.toLowerCase()]()+num(this,"padding"+tl)+num(this,"padding"+br);};jQuery.fn["outer"+name]=function(margin){return this["inner"+name]()+num(this,"border"+tl+"Width")+num(this,"border"+br+"Width")+(margin?num(this,"margin"+tl)+num(this,"margin"+br):0);};});})();	/* **************** CLASSE JAVA SCRIPT FORMULAIRE **************************** #
	 	importer le code dans la page
		<script src="../js/validator.js"></script>
		
		ATTENTION : 
		* le reste du code dédié à la validation ne doit pas se placer à l'intérieur
		  de la même balise <script></script>
		
		* la déclaration d'un objet Formulaire doit se faire aprés le formulaire HTML
		
		* les méthodes sont attachés aux différents évènements liés à la manipulation des contrôles
		il est déconseillé d'affecter d'autres fonctions à ces évènements
			* onblur pour les text et select
			* onclic pour les radios et checkbox
	
	Instanciation du formulaire :
	--------------------------------------------------------------------------------------------------------------------
	
		var form_obj = NEW_Validator(id[], extra_validation]);
		* name			: attribut id d'un formulaire existant
		* extra_validation	: nom d'une fonction qui sera appellée à la fin de la validation du formulaire
							  cette fonction doit retourner obligatoirement true si aucune erreur ne s'est 
							  produite sinon un message "erreur non déterminé s'affichera"
		
		Une fonction de validation supplémentaire doit lever les erreurs qui se produisent grâce à la méthode 
		* form_obj.raiseError('mon message d\'erreur');
		
		Elle doit retourner un booléen. Si elle retourne vrai en ayant levé des erreurs, la validation globale échoue.
		Si elle retourne faux sans avoir levé d'erreur, un message indiquant une erreur inconnue sera affiché.
		
		Dans cette fonction de validation, il est possible d'accéder aux valeurs présentes dans les contrôles :
		* form_obj.field('nom_champ').value()
		
		Accéder aux nombre d'erreurs levées par la validation :
		* form_obj.errorsCount()
		
		Si une classe CSS error est déclarée, elle sera appliquée aux labels 
		correspondant aux champs mal renseignés
		
	
	Ajout de controles au formulaire :
	--------------------------------------------------------------------------------------------------------------------
		form_obj.addField(name, required, data_type, data_format)
		* name				: nom du formulaire HTML auquel s'appliquera le validateur
		* required			: 1 si le champ est obligatoire 0 sinon
		* data_type			: type de donnée requis
		* data_format 		: formatage spécifique à appliquer à un champ texte
		
	Méthode setLanguage(lang) [à implémenter]
	--------------------------------------------------------------------------------------------------------------------
		permet d'exprimer les messages en anglais. Paramètre : "fr", "en"
		
	Types de données : 
	--------------------------------------------------------------------------------------------------------------------
		* integer			: valide un entier
		* decimal			: valide un nombre décimal
		* date				: valide une date dans
		* zipcode			: valide un code postal
		* email				: valide une adresse email
		* telnum			: valide un numéro de tel 
	
	Formatages : 
	--------------------------------------------------------------------------------------------------------------------
		* lower				: passe le texte en minuscules
		* upper				: passe le texte en majuscules
		* ucfirst			: passe la première lettre du texte en majuscule
		* ucwords			: passse la première lettre de chaque mot en majuscules
		* telnum			: formate le numéro de téléphone en groupant
	
	à faire :
	--------------------------------------------------------------------------------------------------------------------
	- éviter l'affichage à la suite du même message d'erreur lors d'une erreur de format
	et immédiatement aprés le même message lors de la validation du formulaire
	- types : texte ? contraintes,  
 */

 /********** Objet utilisés pour la validation de formulaires ***************/


 /* constantes d'état */
   var SAISIE_EN_COURS		= 1;
   var VALIDATION_EN_COURS	= 2;
   var VALIDATOR_DEBUG		= false;

 /************************************************************************** #
                               Objet Formulaire                              #
 *************************************************************************** #
                       construction de l'objet formulaire					*/

 	validator_vars = new Array();
 	function NEW_Validator(name, extra_validation){
 		i = validator_vars.length;
 		validator_vars[i]	= new Validator(name, extra_validation);
 		return validator_vars[i];
 	}
 	
 	function GET_ValidatorReference(name){
 		if (VALIDATOR_DEBUG) {
 			alert('recherche une référence sur ' + name);
 		}
 		nb = validator_vars.length;
 		for (i = 0; i < nb && validator_vars[i].name != name; i++) {;}
 		if (i < nb) {
 			return validator_vars[i];
 		} else {
 			alert('impossible de trouver le validateur pour le formulaire ' + name + ' ' + typeof(name));
 			return null;
 		}
 	}
 	
 	function VALIDATE_Field(form_name, field_name){
 		//alert('112 : ' + typeof(form_name) + ' ' + form_name);
 		obj_validator = GET_ValidatorReference(form_name);
 		if (typeof(obj_validator) == 'object') {
 			nb = obj_validator.fields.length;
 			for (i = 0; i < nb && obj_validator.fields[i].name != field_name; i++) {;}
 			if (i < nb) {
 				return obj_validator.fields[i].validate(1);
 			}
 		} else {
 			alert('impossible de trouver le validateur pour le formulaire ' + form_name);
 			return false;
 		}
 	}
 	
 	function FORMAT_FieldData(form_name, field_name){ 		
 		obj_validator = GET_ValidatorReference(form_name);
 		if (typeof(obj_validator) == 'object') {
 			nb = obj_validator.fields.length;
 			for (i = 0; i < nb && obj_validator.fields[i].name != field_name; i++) {;}
 			if (i < nb) {
 				return obj_validator.fields[i].format(1);
 			}
 		} else {
 			alert('impossible de trouver le validateur pour le formulaire ' + form_name);
 			return false;
 		}
 	}
 	
 	
 	
 	function VALIDATE_Form(form_name){ 		
 		obj_validator = GET_ValidatorReference(form_name);
 		if (obj_validator != null){
 			return obj_validator.validate();
 		} else {
 			alert('formulaire introuvable ' + form_name);
 			return false;
 		}
 	}
 
	function Validator(name, extra_validation){
      // Definition des propriétés
         this.prototype				= null;
         this.name					= name;
         this.action				= "";
         this.changed				= false;
         
         this.fields 				= new Array();
         this.fieldsArray			= new Array();
         this.errorMsg	 			= ""; // message d'erreur de validité des données
         this.requiredDataMsg		= "";
         this.language				= "fr";
         this.nbErrors				= 0;
		 this.extraValidation		= (typeof(extra_validation) != 'undefined' && extra_validation != '' ? extra_validation : null);

      // définition des méthodes
         this.addField				= Validator_addField;
         this.validate				= Validator_validate;
         this.setLanguage			= Validator_setLanguage;
		 this.addCheck				= Validator_addCheck;
		 this.field					= Validator_getField;
		 this.raiseError			= Validator_raiseError;
		 this.errorsCount			= Validator_errorsCount;
		 
		 this.translations = new Array();		 
		 this.translations['fr']	= new Array();
		 this.translations['fr']['validation-fails']	= 'Le formulaire contient %s erreur(s) :\n';
		 this.translations['fr']['required']			= 'Le champ "%s" est obligatoire';
		 this.translations['fr']['data-type']			= 'Le champ "%s" doit contenir %s';
		 
		 this.translations['fr']['type-integer']		= 'un nombre entier';
		 this.translations['fr']['type-decimal']		= 'un nombre décimal';
		 this.translations['fr']['type-date']			= 'une date (jj/mm/aaaa)';
		 this.translations['fr']['type-zipcode']		= 'un code postal';
		 this.translations['fr']['type-email']			= 'une adresse email (utilisateur@domaine.com)';
		 this.translations['fr']['type-telnum']			= 'un numéro de téléphone';
		 
         if (document.getElementById(this.name) == null) {
			alert("Le formulaire specifie " + this.name + " est introuvable.");
         }
         
		if (VALIDATOR_DEBUG) {
 			alert('lie l\'évènnement onsubmit du formulaire "' + this.name + '" à la fonction de validation');
		}
		
		eval('document.getElementById("' + this.name + '").onsubmit = function (){return VALIDATE_Form(\"'+ this.name + '\");}');
		
   }
   
	function Validator_addCheck(StrFunction){
		if (StrFunction != "") {
			this.extraValidation = StrFunction;
		}
	}

	function Validator_setLanguage(lang){
		
	}
	
	function Validator_getField(name){
		nb = this.fields.length;
		for (i = 0; i < nb; i++) {
			if (this.fields[i].name == name) {
				return this.fields[i];
			}
		}
	}

	/*
	* Ajoute un contrôle dont le nom des fourni à l'objet Validator
	* @param name
	* @param required
	* @param data_type
	* @param data_type_msg
	* @param label [inutile d'indiquer un libellé si un controle <label for="name">libellé</label> existe]
	*
	*/
	function Validator_addField(name, required, data_type, data_format) {
		var added		= false;
		var i			= 0;
		
		if (document.getElementsByName(name).length == 0) {
			alert("Controle specifie non trouve : " + name);
			return false;
		}
		
		if (!(required === true || required === false)) {
			alert('paramètre "required" incorrect, booléen attendu');
			return false;
		}
		if (VALIDATOR_DEBUG) {
 			alert('ajoute le champ ' + name);
		}
		this.fields[this.fields.length]	= new FormField(this, name, required, data_type, data_format);
	}

// --------------------------------------------------------------------------- #
//                     méthodes de controle des saisies                        #
// --------------------------------------------------------------------------- #

	function Validator_validate() {
		if (VALIDATOR_DEBUG) {
 			alert('Exécute validate');
		}
		this.errorMsg = '';
		this.nbErrors	= 0;
		var nb			= this.fields.length;
		
		for (k = 0; k < nb; k++) {
			if (VALIDATOR_DEBUG) {
 				alert('appel de la méthode validate() du champ "' + this.fields[k].name + '" dans validate()');
			}
			if (!this.fields[k].validate()){
				if (VALIDATOR_DEBUG) {
 					alert('ECHEC de la méthode validate() du champ "' + this.fields[k].name + '" erreur : ' + this.fields[k].errorMsg); //this.fields[i].errorMsg
				}
				this.errorMsg	+= this.fields[k].errorMsg + "\n";
				this.nbErrors++;
			}
			if (VALIDATOR_DEBUG) {
 				alert('msg erreur Validator : ' + this.errorMsg);
			}
		}
		
		if (VALIDATOR_DEBUG) {
 			alert('nombre d\'erreurs détectées "' + this.nbErrors + '" dans validate()');
		}
		
		nb_errs_tmp = this.nbErrors;
		var res_val		= true;
		if (this.extraValidation != null) {
			eval('res_val = ' + this.extraValidation + '(this);');
		}
		
		if (!res_val) {
			/* si la validation personnalisée a retourné faux sans indiquer l'erreur */
			if (this.nbErrors == nb_errs_tmp) {
				this.nbErrors++; /* possibilité de retourner faux sans ajouter de message d'erreur */
				//this.raiseError('erreur non déterminée');
			}
		}
		
		if (this.nbErrors > 0) {
			if (this.errorMsg != '') {
				this.errorMsg = this.translations['fr']['validation-fails'].replace('%s', this.nbErrors) + this.errorMsg;
				alert(this.errorMsg);
			}
		}
		if (VALIDATOR_DEBUG) {
 			alert('validate s\'apprète à retourner la valeur "' + (ret_val ? 'true' : 'false') + '"');
		}
		return (this.nbErrors == 0);
	}
	
	function Validator_raiseError(msg){
		if (typeof(msg) != 'undefined' && msg != null && msg != '') {
			this.nbErrors++;
			this.errorMsg	+= msg + "\n";
		}
	}
	
	function Validator_errorsCount(){
		return this.nbErrors;
	}


// *************************************************************************** #
//                               Objet Champs                                  #
// *************************************************************************** #
	function FormField(frm_object, name, required, data_type, data_format){
		this.form				= frm_object;
		
		if (VALIDATOR_DEBUG) {
 			alert('instancie un objet pour le champ ' + name);
		}
		
		/* configuration des méthodes de contrôle des différents types de données */
		this.dataTypes = new Array();
		this.dataTypes['integer']	= 'field_check_integer';
		this.dataTypes['decimal']	= 'field_check_decimal';		
		this.dataTypes['date']		= 'field_check_date';
		this.dataTypes['zipcode']	= 'field_check_zipcode';
		this.dataTypes['email']		= 'field_check_email';
		this.dataTypes['telnum']	= 'field_check_telnum';
		
		this.dataFormats = new Array();
		this.dataFormats['upper']	= 'field_format_upper';
		this.dataFormats['lower']	= 'field_format_lower';
		this.dataFormats['ucfirst']	= 'field_format_ucfirst';
		this.dataFormats['ucwords']	= 'field_format_ucwords';
		this.dataFormats['telnum']	= 'field_format_telnum';
		
		this.name				= name; //, nom qui permet d'accéder à ses propriétés (prop. HTML name)
		this.required			= required; // de type booléen, obligatoire ou non
		this.dataType			= typeof(this.dataTypes[data_type]) != 'undefined' ? data_type : null;
		this.dataFormat			= typeof(this.dataFormats[data_format]) != 'undefined' ? data_format : null
		this.label				= ''; // de type texte, désignation conviviale
		this.errorMsg			= '';
		
		if (VALIDATOR_DEBUG && typeof(data_type) != 'undefined' && data_type != '' && typeof(this.dataTypes[data_type]) == 'undefined') {
			alert('type de donnée "' + data_type + '" non défini');
		}
		
		if (VALIDATOR_DEBUG && typeof(data_format) != 'undefined' && data_format != '' && typeof(this.dataFormats[data_format]) == 'undefined') {
			alert('format de donnée "' + data_format + '" non défini');
		}
		
		
		
		// définition des méthodes
		this.checkType			= Field_checkType;
		this.value				= Field_getCurrentValue;
		this.validate			= Field_validate;
		this.format				= Field_FormatData;
		
		this.controleType		= '';
		
		switch (document.getElementsByName(this.name)[0].nodeName.toLowerCase()) {
		case 'input' :
			this.controleType	= document.getElementsByName(this.name)[0].type
		break;
		case 'textarea':
		case 'select' :
			this.controleType = document.getElementsByName(this.name)[0].nodeName.toLowerCase();
		break;
		}
		
		reg = new RegExp(/_/g);
		var container_id = this.name.replace(reg, '-');
		
		/* tente d'identifier une valeur de libellé pour le contrôle */
		if (this.controleType == 'radio') {
			obj_fieldset = document.getElementById('radios-set-row-' + container_id);
			if ((obj_fieldset != null) && obj_fieldset.hasChildNodes() && obj_fieldset.getElementsByTagName('span').length > 0) {
				this.labelObject = obj_fieldset.getElementsByTagName('span')[0];
				this.label 		 += this.labelObject.childNodes[0].nodeValue;
			}
		} else {
			labels	= document.getElementsByTagName('label');
			nb		= labels.length;		
			for (i = 0; i < nb; i++){
				if (labels[i].attributes.getNamedItem('for') !== null && labels[i].attributes.getNamedItem('for').nodeValue == name) {
					if (labels[i].childNodes != 'undefined') {
						var nb_childnodes = labels[i].childNodes.length;
						for (j = 0; j < nb_childnodes; j++) {
							if (labels[i].childNodes[j].nodeType == 3) {
								this.label 			+= labels[i].childNodes[j].nodeValue;
								this.labelObject	= labels[i];
							} else {
								/* si un tag est présent dans le label */
								if (labels[i].childNodes[j].hasChildNodes() && labels[i].childNodes[j].childNodes[0].nodeType == 3) {
									this.label += labels[i].childNodes[j].childNodes[0].nodeValue;
								}
							}
						}
					}
					break;
				}
			}
		}
		
		
		
		/* affiche une erreur si aucun label n'a été trouvé pour le champ */
		if (typeof(this.labelObject) == 'undefined') {
			alert('aucun label n\'a été trouvé pour le champ ' + this.name + ' (<label for="' + this.name + '">)');
			return false;
		}
		
		if (this.controleType == '') {
			alert('type de contrôle non identifié ' + document.getElementsByName(this.name)[0].nodeName);
		}

		obj = document.getElementsByName(this.name);
		nb	= obj.length;
		if (VALIDATOR_DEBUG) {
 			alert('type de contrôle ' + this.controleType + 'trouvé ' + nb);
		}
		
		
		required_tag = document.createElement('span');
		if (this.required) {
			required_tag.appendChild(document.createTextNode('*'));
		}
		required_tag.setAttribute('class', 'required');
		required_tag.setAttribute('className', 'required');
		
		if (nb != 0) {
			for (i = 0; i < nb; i++) {
				switch (this.controleType) {
				case 'text':
				case 'select':
				case 'password':
				case 'textarea':
					if (VALIDATOR_DEBUG) {
				 		alert('ajoute les evts ');
					}
					str_onblur = 'document.getElementsByName("' + this.name + '")['+ i +'].onblur = function(){';
					str_onblur += 'VALIDATE_Field("' + this.form.name + '", "' + this.name + '");';
					str_onblur += 'FORMAT_FieldData("' + this.form.name + '", "' + this.name + '");';
					str_onblur += '}';
					eval(str_onblur);
					
					if (this.controleType == 'select') {
					document.getElementById('select-one-row-' + container_id).appendChild(required_tag);
					} else {
						if (this.controleType == 'textarea' ) {
						document.getElementById('textarea-row-' + container_id).appendChild(required_tag);
						} else {
						document.getElementById('text-row-' + container_id).appendChild(required_tag);
						}
					}					
				break;
				case 'radio':
					str_onblur	= 'document.getElementsByName("' + this.name + '")['+ i +'].onblur = function(){';
					str_onblur += 'VALIDATE_Field("' + this.form.name + '", "' + this.name + '");';				
					str_onblur += '}';
					eval(str_onblur);
					document.getElementById('radios-set-row-' + container_id).appendChild(required_tag);
				break;
				case 'checkbox':
					str_onclick	= 'document.getElementsByName("' + this.name + '")['+ i +'].onclick = function(){';
					str_onclick += 'VALIDATE_Field("' + this.form.name + '", "' + this.name + '");';				
					str_onclick += '}';
					eval(str_onclick);
					if (this.controleType == 'radio') {
						document.getElementById('radios-set-row-' + container_id).appendChild(required_tag);
					} else {
						document.getElementById('checkbox-row-' + container_id).appendChild(required_tag);
					}
				break;
				}
			}
		}
	}

// --------------------------------------------------------------------------- #
//                          méthodes de controle des saisies                   #
// --------------------------------------------------------------------------- #
	function Field_FormatData(){
		if (this.controleType == 'text' && this.dataFormat != null) {
			fct_format	= (this.dataFormats[this.dataFormat]);
			value		= this.value();
			eval('res = ' + fct_format + '("' + (value == null ? '' : value) + '");');
			document.getElementsByName(this.name)[0].value = (res == null ? '' : res);
		}
	}


	function Field_checkType(display_msg){
		if (VALIDATOR_DEBUG) {
 			alert('valide le type de données du champ : "' + this.name + '"\ntype attendu : "' + this.dataType + '" fonction appellée "'+ this.dataTypes[this.dataType] + '"');
		}
		
		if (typeof(this.dataTypes[this.dataType]) == 'undefined') {
			this.form.changed	= true;
			return true;
		}
		
		fct_check = (this.dataTypes[this.dataType]);
		eval('res = ' + fct_check + '("' + this.value() + '");');
		if (!res) {
			if (typeof(this.dataTypeMsg) != 'undefined' && this.dataTypeMsg != '') {
				msg = this.dataTypeMsg;
			} else {
				msg = this.form.translations['fr']['data-type'];
			}
			msg = msg.replace(/%s/, this.label);
			msg = msg.replace(/%s/, this.form.translations['fr']['type-' + this.dataType]);
			this.errorMsg += msg;
			if (display_msg == true) {				
				alert(msg);
			}
		}
		
		if (res) {
			$(this.labelObject).removeClass('error');
			return true;
		} else {
			$(this.labelObject).addClass('error');
			return  false;
		}
		
		if (VALIDATOR_DEBUG) {
 			alert('succès de de la validation : "' + this.name + '"');
		}
		return res;
	}
	
	function Field_validate(display_errors){
		this.errorMsg 	= '';
		value			= this.value();
		if (VALIDATOR_DEBUG) {
			alert('valide : ' + this.name + ' requis ' + this.required + ' valeur : "' + value + '" (' + typeof(value) + ') type ' + this.dataType);
		}
		if (this.required) {
			if (VALIDATOR_DEBUG) {
 				alert('champ : "' + this.name + '" obligatoire');
			}
			if (value == null) {
				//alert(this.form.translations['fr']['required'].replace(/%s/, this.label));
				this.errorMsg += this.form.translations['fr']['required'].replace(/%s/, this.label.replace(/\s*:\s*$/, '').replace(/^\s/, ''));
			}
		}
		
		if (value != null && !this.checkType(display_errors)) {;}
		
		if (VALIDATOR_DEBUG) {
 			alert('champ : "' + this.name + '" message d\'erreur : ' + this.errorMsg);
		}
		
		if (this.errorMsg == '' ) {
			$(this.labelObject).removeClass('error');
			return true;
		} else {
			$(this.labelObject).addClass('error');
			return  false;
		}
	}

	function Field_getCurrentValue(){
		switch (this.controleType) {
			case "text" :
			case "file" :
			case "textarea" :
			case "password" :
				value = (document.getElementsByName(this.name)[0].value == '' ? null : document.getElementsByName(this.name)[0].value);
				if (value != null) {
					value	= value.replace(/^\s*/, '').replace(/\s*$/, '');
					document.getElementsByName(this.name)[0].value	= value;
				}
				return value;
			break;
			case "select" :
				/* une valeur égale à 0 ou une chaine vide sont interprétées comme si l'utilisateur n'avait sélectionné aucune valeur */
				lst = document.getElementsByName(this.name)[0];
				valeur = lst[lst.selectedIndex].value;
				//alert(valeur);
				return (valeur == '' || valeur == "0" || valeur == null) ? null : valeur;
			break;
			case "radio" :
				/* une valeur égale à 0 ou une chaine vide sont interprétées comme si l'utilisateur n'avait sélectionné aucune valeur */
				ctrls	= lst = document.getElementsByName(this.name);
				nb		= ctrls.length;				
				for (i = 0; i < nb && !ctrls[i].checked; i++) {;}
				return i < nb ? ctrls[i].value : null;
			break;
			case "checkbox" :
				/* une valeur égale à 0 ou une chaine vide sont interprétées comme si l'utilisateur n'avait sélectionné aucune valeur */
				if (document.getElementsByName(this.name).length != 0) {
					return document.getElementsByName(this.name)[0].checked ? document.getElementsByName(this.name)[0].value : null;
				}
			break;
			default :
				alert("Type de controle inconnu,\nimpossible de déterminer la valeur." + this.type + this.name);
			break;
		}
	}

	function Field_toString() {
		var str = "";
		str += "FormName : " + this.FormName + "\n";
		str += "Name : " + this.Name + "\n";
		str += "Type : " + this.Type + "\n";
		str += "Required : " + this.Required + "\n";
		str += "RequiredDataType : " + this.RequiredDataType + "\n";
		str += "DataTypeErrMsg : " + this.DataTypeErrMsg + "\n";
		str += "Index : " + this.Index + "\n";
		str += "Designation : " + this.Designation + "\n";
		return str;
	}


// --------------------------------------------------------------------------- #
//                     fonction de controle des saisies                        #
// --------------------------------------------------------------------------- #
	/* vérifie que la chaine passée en paramètre es bien un cp de france métropol */
	function field_check_zipcode(cp){
		return (!isNaN(parseInt(cp.replace(/^0*/, ''))) && parseInt(cp.replace(/^0*/, '')) > 0 && cp.toString().length == 5);
	}

	function field_check_integer(Chaine){
		// vérifie que la chaine passée en param contient uniquement des entiers
		if(Chaine.match(/^[ ]*[+-]?\d+[ ]*$/)) {
			return true;
		} else {
			return false;
		}
	}

	function field_check_decimal(Chaine){
		return (Chaine.match(/^[0-9\.,]+$/) != null);
	}
   
	function field_check_email(Chaine){
		/* expression extraite de http://atranchant.developpez.com/code/validation/index.php 
		respecte les RFC 2822 et 1035
		http://www.faqs.org/rfcs/rfc2822.html */
		//if ()
		if (typeof(Chaine) != 'string') {
			return false;			
		}
		Chaine	= Chaine.replace(/(^\s|\s$)/, '');
		regex 	= '^[-a-z0-9!#$%&\'*+\/=?^_`{|}~\.]+@([a-z0-9\-]{1,63}\\.)+([a-z0-9]{2,63})$';	
		reg		= new RegExp(regex, 'i');
		return (reg.exec(Chaine) != null);
	
		//return (typeof(Chaine) != 'undefined' && Chaine != null && Chaine != '' && Chaine.match(//))
	}

	function field_check_date(Chaine){
		Chaine	= Chaine.replace(/(^\s|\s$)/, '');	
		if (typeof(Chaine) != 'string' || Chaine == null || Chaine == '' || !Chaine.match(/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/)) {
			return false
		}
		/* vérifie que la date a l'air cohérente */
		var tab_date = new Array();
		tab_date		= Chaine.split('/');
				
		if (isNaN(parseFloat(tab_date[0])) || parseFloat(tab_date[0]) > 31 || isNaN(parseFloat(tab_date[1])) || parseFloat(tab_date[1]) > 12 || isNaN(parseFloat(tab_date[2])) || tab_date[2] > 2100) {			
			return false;
		} else {
			return true;
		}
	}
	
	/* contrôle la validité d'un numéro de téléphone (10 à 13 chiffres - total != 0) */
	function field_check_telnum(tel_num){
		//alert('check '+ tel_num);
		tel_num = tel_num.replace(/\s/g,'');
		return (tel_num.match(/^[0-9]{10,13}$/) != null && !isNaN(parseInt(tel_num.replace(/^0*/, ''))) && parseInt(tel_num.replace(/^0*/, '')) > 0 && tel_num.toString().length >= 10 && tel_num.toString().length < 14);
	}
	
	/* formatage */
	
	function field_format_upper(str){
		//alert('"' + str + '"' + typeof(str) + (str == '') + str.toUpperCase());
		return (str == '' ? '' : str.toUpperCase());
	}
	
	function field_format_lower(str){
		return (str == '' ? '' : str.toLowerCase());
	}
	
	/** 
	* met en majuscule :
	* - la première lettre de la chaîne
	* - la deuxième lettre de chaque mot si un paramètre true est reçu en 2e position 
	*/
	function field_format_ucfirst(str){
		if (arguments.length > 1 && arguments[1]) {
			arr_words = str.split(/ /);
		} else {
			arr_words = new Array(str);
		}
		
		nb = arr_words.length;
		str = '';
		for (i = 0; i < nb; i++) {
			str += arr_words[i].charAt(0).toUpperCase() + arr_words[i].substring(1);
			if (i < nb - 1) {
				str += ' ';
			}
		}
		return str;
	}
	
	function field_format_ucwords(str){
		return field_format_ucfirst(str, true);
	}

	function field_format_telnum(tel_num){
		tel_num = tel_num.replace(/\s/g,'');
		return tel_num.replace(/(([0-9][^0-9]*){2})/g, "$1 ");
	}

// ------------------- INTERCEPTION DES EVENEMENTS FORMULAIRE ------------------
	function formCheckChange(obj){
		return obj.changed();
	}

	//function formValidate(obj){
	//	alert('ici');
	//	return obj.validate();
	//};
var compteur = 0;
function ajoute_enfant(id, prenom, sexe, date_naissance){
	compteur++;
	
	if (!document.getElementById('conteneur-enfant-')) {
		return false;
	}
	
	var nouv_champs = document.getElementById('conteneur-enfant-').cloneNode(true);
	nouv_champs.id += compteur;
	nouv_champs.style.display = 'block';

	var inserer_ici = document.getElementById('btn-ajouter-enfant');
	inserer_ici.parentNode.insertBefore(nouv_champs, inserer_ici);
	
	var nouv_champ = nouv_champs.getElementsByTagName("TD");	
	for(var i = 0; i < nouv_champ.length; i++) {
		/* explore le contenu des cellules de tableau */
		var contenu = nouv_champ[i].childNodes;
		//alert(contenu[0].name + ' : ' + contenu[0].type);
		
		if(contenu.length > 0 && (contenu[0].type == "text" || contenu[0].type == "hidden" || contenu[0].type == "select-one" || contenu[0].type == "button")){
			if(contenu[0].name == "prenom_enfant_" ) { contenu[0].value = prenom; }
			if(contenu[0].name == "date_naissance_enfant_" ) { contenu[0].value = date_naissance; }
			
			
			if(contenu[0].name == "sexe_enfant_" ) {
				var opt = contenu[0].childNodes;
				
				for(var j = 0; j < opt.length; j++){
					if(opt[j].value == sexe) {
						opt[j].selected = "selected";
					}
				}
			}
			
			if(contenu.length > 1 && contenu[1].name == "id_enfant_" ){
				contenu[1].value = id;
				contenu[1].name += compteur;
			}
			
			/* renomme le contrôle */
			contenu[0].name += compteur;
		}		
	}	
}

function supprime_enfant(noeud) {
	conteneur_enfant = noeud.parentNode.parentNode.parentNode.parentNode;
	conteneur_enfant.style.display = "none";
	cellule = conteneur_enfant.getElementsByTagName('TD');
	for(var i = 0; i < cellule.length; i++) {
		if(cellule[i].hasChildNodes) {
			contenu = cellule[i].childNodes;
			if(contenu.length > 0 && contenu[0].name != undefined && contenu[0].name.match(/^prenom/) == "prenom") {
				contenu[0].value = "";
			} 
		}
	}
}$(document).ready(function(){
	if ($('input[@id=page_id]').attr('value')) {
		init($('input[@id=page_id]').attr('value'));	
	} else {
		init(document.getElementsByTagName('body')[0].id);
	}
	
	$('a').bind('focus', function (){
		$(this).blur();
	});
	
});

/* remlace le contenu texte d'un tag en un équivalent image (tag_name utilise la syntaxe JQuery) */
function replace_tags(tag_name, font_size){
	var http_server = $('#http_server').val();
	$(tag_name).each(function (){
		file_url	= http_server + '/titres.php?text=' + escape($(this).html()) + '&font_size=' + font_size + '&font_family=helvetica-37-thin-condensed&color=6D6D6D';
		$(this).html('');
		$(this).append('<div></div>');
		$(this).find('div').css('background', 'url(' + file_url + ') left top no-repeat');
		$(this).find('div').css('height', (font_size + 5) + 'px');
	});	
}


var form_obj;
function init(fichier){
	var http_server = $('#http_server').val();
	
	if (fichier != 'model-info') {
		replace_tags('h1', 18);
	}
	
	replace_tags('#index #espaces-marques h2', 18);
	replace_tags('#accueil-categorie .products-list-container h2', 15);
	replace_tags('#contenu-categorie-transversale #zone-produits-categorie h2', 15);
	replace_tags('.associated-products-block h2 a', 15);
	replace_tags('#nouvelle-collection h2', 15);
	replace_tags('#shopping-cart h2', 15);
	replace_tags('#checkout-confirmation h2#paiement', 18);
	
	
	
	/* initialisation formulaire de filtrage des articles */
	$('form[@id=frm-filtre-articles] select').each(function (){
		$(this).find('option:eq(0)').text($('label[@for=' + $(this).attr('id') + ']').text());
		$('label[@for=' + $(this).attr('id') + ']').css('display', 'none');	
		$(this).bind('change', function (){
			$('form[@id=frm-filtre-articles]').submit();
		});
		$(this).show()
	});
	
	/* choisi dans la liste de recherche la bonne marque */
	if ($('input[@id=h_search_manufacturers_id]').length){
		search_box_label = 'mots clés';
		if ($('input[@id=keywords]').attr('value') == undefined) {
			$('input[@id=keywords]').attr('value', search_box_label);
		}
		
		$('input[@id=keywords]').bind('click', 
			function (){
				if (this.value == search_box_label)	{
					this.value = '';
				}			
			}
		);
	}
	
	text_votre_email = 'Votre email';
	if ($('#email-concours').val() == undefined || $('#email-concours').val() == ''){
		$('#email-concours').val(text_votre_email);
	}
	
	$('#email-concours').bind('blur', function (){
		if ($(this).val() == '') {
			$(this).val(text_votre_email);				
		}
	});
		
	$('#email-concours').bind('focus', function (){
		if ($(this).val() == text_votre_email) {
			$(this).val('');				
		}		
	});
	
	/* gère le problème de supperposition du contenu du corps par dessus le contenu du menu */
	/*
	$('#barre-ages').css('position', 'relative');		
	$('#barre-ages').css('z-index', '+100');
	$('#barre-ages *').css('z-index', '100');
	$('#barre-ages *').css('z-index', '100');
	var zindex = (($.browser.msie && parseInt($.browser.version) <= 6) ? -1 : 0);
	$('#corps').find('h1').css('z-index', zindex);
	*/
	switch (fichier){
	case 'index' :
		text_votre_email = 'Votre email';
		if ($('#email').val() == undefined || $('#email').val() == ''){
			$('#email').val(text_votre_email);
		}
		
		$('#email').bind('blur', function (){
			if ($(this).val() == '') {
				$(this).val(text_votre_email);				
			}
		});
		
		$('#email').bind('focus', function (){
			if ($(this).val() == text_votre_email) {
				$(this).val('');				
			}		
		});
	break;
	case 'accueil-categorie' :
		/* enchainement des visuels d'accueil de catégorie */
   		$('#col-home-image').cycle({ 
		    fx:    'fade',
		    pause:  1,
		    speed:  2000
		});
		
		// 		    speed:  2000,
	break;
	case 'contenu-categorie' :
		$('#breadcrumb select').bind('change', function (){
			$('#breadcrumb form').submit();
		});
	break;
	case 'espace-marque-accueil' :
		$('#breadcrumb select').bind('change', function (){
			$('#breadcrumb form').submit();
		});
	break;
	case 'model-info' :
		/* ---------------------------------------------------- zoom vignettes produits */
		/* la classe appliquée aux images img-pos (ou pos est la position de l'image dans la liste) */
		$('#image-block ul a').bind('click', function () {
			write_to_log('click agrandissement vignette', 'debug');
			try {
				$('#zoom-block a').hide();
				$('#zoom-block a.' + $(this).attr('class')).show();
				return false;
			} catch(e){
				write_to_log('échec agrandissement vignette Error name: ' + e.name + '. Error message: ' + e.message, 'debug');
			}
		});
	
		$('#zoom-block a').bind('click', function (){
			write_to_log('click agrandissement vignette moyenne', 'debug');
			try {
				$('#zoomed-div img').hide();
				$('#zoomed-div img.' + $(this).attr('class')).show();
				$('#select-one-row-products-id').hide();
				$('#zoomed-div').show();
				return false;
			} catch(e){
				write_to_log('échec agrandissement vignette moyenne Error name: ' + e.name + '. Error message: ' + e.message, 'debug');
			}
			
		});
		
		$('#zoomed-div').bind('click', function (){
			$(this).hide();
			$('#select-one-row-products-id').show();
		});		
		/* ------------------------------------------------ fin zoom vignettes produits */
		
		
		/* gère le changement de prix en fonction du choix de la taille */
		$('#products_id').bind('change', function (){
			var selected_product_id = $(this).find('option[@selected]').val();
			var nb = availlable_sizes.length;
			for (i = 0; i < nb; i++){
				if (availlable_sizes[i]['id'] == selected_product_id) {
					special_price	= parseFloat(availlable_sizes[i]['special_price']);
					price			= parseFloat(availlable_sizes[i]['price']);
					if (special_price > 0) {
						$('#prix-abikid span[@class=nouveau-prix]').html(special_price.toFixed(2) + '&nbsp;&euro;');
						if ($('#prix-abikid span[@class=ancien-prix]').length == 0) {
							$('#prix-abikid span[@class=nouveau-prix]').before('<span class="ancien-prix"></span> ')
						}
						$('#prix-abikid span[@class=ancien-prix]').html(price.toFixed(2) + '&nbsp;&euro;');
					} else {
						$('#prix-abikid span[@class=nouveau-prix]').html(price.toFixed(2) + '&nbsp;&euro;');
					}
					break;					
				}				
			}
		});
		
		/* vérification sélection d'une taille */
		$('form#frm-add-product').bind('submit', function (){
			var selected_pid = parseInt($('#products_id option[@selected]').val());
			if (isNaN(selected_pid) || !selected_pid > 0) {
				display_user_msg('Veuillez sélectionner une taille');
				return false;		
			}
			return true;
		});
	break;
	case 'create-account' :
		var form_obj = NEW_Validator('create_account', 'create_account_extra');
		form_obj.addField('gender', true);
		form_obj.addField('lastname', true);
		form_obj.addField('firstname', true);
		//form_obj.addField('dob', true, 'date');
		
		form_obj.addField('street_address', true);
		form_obj.addField('postcode', true);
		form_obj.addField('city', true);
		form_obj.addField('country', true);
		
		form_obj.addField('email_address', true, 'email');
		form_obj.addField('email_address_confirm', true, 'email');
		
		form_obj.addField('telephone', true, 'telnum');
		form_obj.addField('email_proposed_by', false, 'email');
		form_obj.addField('newsletter', true);
		form_obj.addField('password', true);
		form_obj.addField('confirmation', true);
		//form_obj.addField('id_prescripteur', true);
		form_obj.addField('accepte', true);		
			
		$('a[@class=lien-reglement-parrainages]').bind('click', function(index) { return open_popup(this.getAttribute('href'), 540, 540); });
		$('a[@class=lien-cgv]').bind('click', function(index) { return open_popup(this.getAttribute('href'), 540, 540); });
		
		$('#street_address').bind('change', create_account_check_address);
		$('#postcode').bind('change', create_account_check_address);
		$('#city').bind('change', create_account_check_address);
		$('#country').bind('change', create_account_check_address);
		
	break;
	case 'account-edit' :
		var form_obj = NEW_Validator('account_edit');
		form_obj.addField('gender', true);
		form_obj.addField('last_name', true);
		form_obj.addField('first_name', true);
		form_obj.addField('dob', false, 'date');
		form_obj.addField('email', true, 'email');
		form_obj.addField('telephone', false, 'telnum');
		//form_obj.addField('fax', false, 'telnum');
	break;	
	case 'address-book-process':
		if ($('input[@id=firstname]').length) {
			var form_obj = NEW_Validator('addressbook', 'create_account_check_address');
			form_obj.addField('gender', true);
			form_obj.addField('lastname', true);
			form_obj.addField('firstname', true);
			form_obj.addField('street_address', true);
			form_obj.addField('suburb', false);
			form_obj.addField('postcode', true);
			form_obj.addField('city', true);
			form_obj.addField('country', true);
			
			$('#street_address').bind('change', create_account_check_address);
			$('#postcode').bind('change', create_account_check_address);
			$('#city').bind('change', create_account_check_address);
			$('#country').bind('change', create_account_check_address);
		}
	break;
	case 'login':
		var form_obj = NEW_Validator('frm-login');
		form_obj.addField('email_address', true, 'email');
		form_obj.addField('password', true);
	break;
	case 'account-password' :
		var form_obj = NEW_Validator('account_password', 'account_password_extra');
		form_obj.addField('password_current', true);
		form_obj.addField('password_new', true);
		form_obj.addField('password_confirmation', true);
	break;
	case 'shopping-cart' :
		$('a[@class=lien-reglement-parrainages]').bind('click', function(index) { return open_popup(this.getAttribute('href'), 540, 540); });
		
		$('select[@name^=cart_quantity]').bind('change', function (){
			$('form[@id=cart_quantity]').submit();			
		});
		
		/* modification de la taille des articles */
		$('select[@name^=cart_size]').bind('change', function (){
			$('form[@id=cart_quantity]').submit();			
		});
	break;
	case 'checkout-shipping' :
		/*  */
		$('tr[@class^=module-row]').bind('mouseover', function (){
			if ($(this).find('input[@name=shipping][@checked]').length == 0) {
				$(this).addClass('module-row-selected');
				$(this).css('cursor', 'hand');
			}
		})
		
		$('tr[@class^=module-row]').bind('mouseout', function (){
			if ($(this).find('input[@name=shipping][@checked]').length == 0) {
				$(this).removeClass('module-row-selected');
			}
		})
		
		$('tr[@class^=module-row]').bind('click', function (){
			$('tr[@class^=module-row]').removeClass('module-row-selected');
			$(this).find('input[@name=shipping]').attr('checked', 'checked');
			$(this).addClass('module-row-selected');
			
		})
	
		/* si aucun mode d'expédition n'est coché et qu'il n'en existe qu'un, le coche */
		$('form[@id=frm-checkout-shipping]').bind('submit', function (){
			if ($('input[@name=shipping][@checked]').length == 0) {
				alert('merci de choisir un mode d\'expédition');
				return false;				
			}
			return true;
		})
	break;
	case 'checkout-payment' :
		$('tr[@class^=module-row]').bind('mouseover', function (){
			if ($(this).find('input[@name=payment][@checked]').length == 0) {
				$(this).addClass('module-row-selected');
				$(this).css('cursor', 'hand');
			}
		})
		
		$('tr[@class^=module-row]').bind('mouseout', function (){
			if ($(this).find('input[@name=payment][@checked]').length == 0) {
				$(this).removeClass('module-row-selected');
			}
		})
		
		$('tr[@class^=module-row]').bind('click', function (){
			$('tr[@class^=module-row]').removeClass('module-row-selected');
			$(this).find('input[@name=payment]').attr('checked', 'checked');
			$(this).addClass('module-row-selected');
			
		})
	
		/* si aucun mode d'expédition n'est coché et qu'il n'en existe qu'un, le coche */
		$('form[@id=frm-checkout-payment]').bind('submit', function (){
			if ($('input[@name=payment]').length > 1 && $('input[@name=payment][@checked]').length == 0) {
				alert('merci de choisir un mode de paiement');
				return false;				
			}
			return true;
		})
	break;
	case 'checkout-confirmation' :
		/* ajustement hauteur contenu des modules de paiement */
		$('#payment-modules .section').each(function(){
			$(this).find('.payment-description').css('height', ($(this).height() - 10) + 'px');
		});
	
		$('input[@id=use_proposal_reduction]').bind('click', function () {$('form[@id=frm_proposal_reduction]').submit();})
		$('a[@class=lien-reglement-parrainages]').bind('click', function(index) { return open_popup(this.getAttribute('href'), 540, 540); });
		
		/* met un fond blanc sur les lignes non essentielles des totaux */
		totals_rows_count = $('table[@id=order-totals] tr').length;
		$('table[@id=order-totals] tr').each(
		function (idx) {
			if (idx != 0 && idx != (totals_rows_count - 1))	 {
				$(this).css('background-color', '#FFF');
				$(this).find('td').css('font-weight', 'normal !important');
			}
		}
		);
		
		if ($('form[@id=frm-coupon]').length) {
			$('form[@id=frm-coupon]').bind('submit', function (){
				return check_coupon();
			})			
		}		
		
		if ($('#accepte_coupon').length > 0) {
			var form_obj = NEW_Validator('checkout_confirmation');
			$('#checkout_confirmation').bind('submit', function (){
				if (!$('#accepte_coupon').attr('checked')) {
					$('label[for=accepte_coupon]').attr('class', 'error');				
					alert('Merci de cocher la case qui indique que vous acceptez\nles conditions d\'utilisation du coupon de réduction');		
					
					return false;
				}
			})
		}
		
	break;
	case 'reglement-parrainage' :
		$('a').bind('click', function(index) { return close_popup(this.getAttribute('href')); });
	break;
	case 'contact-us' :
		/* vérifie si le contrôle name existe pour prise en compte de l'affichage aprés
		traitement qui affiche seulement un message */
		if ($('input[@name=name]').length) {
			form_obj = NEW_Validator('frm_contact', 'frm_contact_extra');
			form_obj.addField('contact_type', false);
			form_obj.addField('name', true);
			form_obj.addField('company', false);
			form_obj.addField('email', true, 'email');
			form_obj.addField('enquiry_type', true);
			form_obj.addField('enquiry', true);			
			/**
			* activation / désactivation des champs société
			*/
			$('input[@name=contact_type]').bind('click', 
				function (i){
					
					switch (parseInt($('input[@name=contact_type][@checked]').attr('value'))){
					case 0 :
						contact_display_company_fields(false);
					break;
					case 1 :
						contact_display_company_fields(true);
					break;
					default :
						
					break;		
					}
				
				}
			);
		}
	break;
	case 'password-forgotten' :
		var form_obj = NEW_Validator('password_forgotten');
		form_obj.addField('email_address', true, 'email');
	break;
	case 'parrainage' :
		if ($('form[@id=frm-parrainage]').length > 0) {
			var form_obj = NEW_Validator('frm-parrainage', 'parrainage_extra_validation');
			form_obj.addField('nom', true);
			form_obj.addField('prenom', true);
			form_obj.addField('email', true, 'email');
		}
	break;
	case 'inscription' :
	case 'desinscription' :
		text_votre_email = 'Votre email';
		if ($('#email').val() == undefined || $('#email').val() == ''){
			$('#email').val(text_votre_email);
		}
		
		$('#email-concours').bind('blur', function (){
			if ($(this).val() == '') {
				$(this).val(text_votre_email);				
			}
		});
		
		$('#email').bind('focus', function (){
			if ($(this).val() == text_votre_email) {
				$(this).val('');				
			}		
		});
	
		$('#frm-newsletter').bind('submit', function(){
			val = $('#frm-newsletter input[@name=email]').val();
			if(!field_check_email(val)){
				alert('Merci d\'entrer votre adresse email.')
				return false;
			}
			return true;
		});
	break;
	case 'page-introuvable':
		//alert(navigator.appName + ' ' + navigator.appName + ' ' + navigator.appVersion + 'referer : ' + top.document.referrer);
	break;
	}

	/** ------------------------------------------------------- met à jour l'historique */
	if (fichier == 'model-info') {
		thumb_attr 	= $('a[@id=zoom-link] img').attr('src').match(/\/([0-9]+)\-[0-9]+\.([a-z]+)$/);
		thumb_url 	= $('input[@id=http_server]').val() + '/images/products_images/vignettes/' + thumb_attr[1] + '-100.' + thumb_attr[2];
		model_name	= $('h1').text();
	} else {
		thumb_url = '';
		model_name	= $('h1 span').text();	
	}
	
	/*if (fichier == 'index' || fichier == 'product-info' || fichier == 'model-info' || fichier == 'contenu-categorie' || fichier == 'contenu-categorie-transversale' || fichier == 'promotion' || fichier == 'articles-marque' || fichier == 'espace-marque-accueil') {
		/* ajoute la page en cours à l'historique client */
	/*	$.ajax({
		   type: "GET",
		   url: $('input[@id=ajax_actions_url]').val(),
		   data: "url=" + escape(window.location.href) + "&label=" + model_name + "&thumb=" + thumb_url + "&action=navigation-history-append",
		   async: false,
		   success: function(response){
				//alert(response);
		   		//display_history();
		   }
		});
	}
	*/
	
	/* affichage de l'historique client (l'affichage sera fait ou non en fonction de la présence 
	du conteneur : <div id="navigation-history-container"></div>) */
	//display_history();
	
	
	/* onchange liste marques */
	if (document.getElementById('frm-liste-marques') && document.getElementById('manufacturers_strid')) {
		document.getElementById('manufacturers_strid').onchange = function () {
			if ($('input[@id=http_server]').length) {		
				window.location.href = $('input[@id=http_server]').attr('value') + '/vetement-enfant-marque-' + document.getElementById('manufacturers_strid')[document.getElementById('manufacturers_strid').selectedIndex].value + '.php';
			}
		}
	}
	
	/* pagination */
	ctrls_offset =  document.getElementsByName('offset');
	nb_ctrls_offset = ctrls_offset.length; 
	for (i = 0; i < nb_ctrls_offset; i++) {
		ctrls_offset[i].onchange = function () {this.parentNode.parentNode.submit();}
	}
	
	
	
	/* ------------------------------------------ actions menu "mon espace client" */
	select_action_espace_client = document.getElementById('select-action-espace-client');
	if (select_action_espace_client) {
		select_action_espace_client.onchange = function () {
			window.location.href = select_action_espace_client[select_action_espace_client.selectedIndex].value;
		}
	}
	
	$('a[@class=lien-reglement-parrainages]').bind('click', function(index) { return open_popup(this.getAttribute('href'), 540, 540); });
	
	if ($('#user_msg').val() != undefined && $('#user_msg').val() != '') {
		if ($('#user_choice').val() != undefined && $('#user_choice').val() != '') {
			var choice_array = $('#user_choice').val().split(';');
			nb = choice_array.length;
			var choice_param = new Array(nb);
			for (i = 0; i < nb; i++) {
				choice_param[i] = choice_array[i].split('=>');
				choice_param[i][1] = unescape(choice_param[i][1]);
			}
			//alert(choice_param);
		}
		display_user_msg($('#user_msg').val(), choice_param);		
	}
} // fin fontion init
	
/* ---------------------------------------------------------------------------------------
										FONCTIONS
--------------------------------------------------------------------------------------- */
		
	function check_coupon(){
		var check_ok = false;
		if ($('input[@id=coupon_id]').val() != '') {
			/* vérifie la validité du coupon avant le post */
			$.ajax({
			type: "GET",
			url: $('input[@id=ajax_actions_url]').val(),
			data: "action=check-coupon&coupon_id=" + $('input[@id=coupon_id]').val(),
			async: false,
			success: function(response){
		   		if (parseInt(response) == 1) {
		   			check_ok = true;
		   		} else {
		   			alert(response);
		   		}
			}
			});
		} else {
			// suppression du code privilège
			check_ok = true;
			//alert('Merci d\'entrer un code privilège');
		}
		return check_ok;
	}


	function display_history(){
		
		if ($('div[@id=navigation-history-container]').length == 0) {
			return;
		}
		
		if ($('div[@id=history]').length == 0) {
			/* affiche l'historique client */
			$.ajax({
			type: "GET",
			url: $('input[@id=ajax_actions_url]').val(),
			data: "action=navigation-history-display",
			async: false,
			success: function(response){
		   		$('div[@id=navigation-history-container]').append(response + '');
				$('div[@id=history] ul li:gt(5)').css('display', 'none');
			}
			});
			
			/* lien "+ d'articles" */
			if ($('div[@id=history] ul li:gt(5)').length > 0) {
				$('div[@id=history]').append('<a href="" id="display-old-history">Afficher plus d\'articles &gt;&gt;</a>');
				$('div[@id=history] a[@id=display-old-history]').bind('click', function () {
					$('div[@id=history] ul li:gt(5)').toggle();
					$(this).css('display', 'none');
					return false;
				});
			}
			
			$('div[@id=history] li a').bind('mouseover', function () {
				$('div[@id=history] li a').removeClass('active');
				$(this).addClass('active');
			});
			
			$('div[@id=history] li a').bind('mouseout', function () {
				$(this).removeClass('active');
			});
			replace_tags('#navigation-history-container h2', 14);
		}
	}
	
	function contact_display_company_fields(val) {
		var val_disabled	= val ? '' : 'disabled';
		var bg_color		= val ? '#FFF' : '#CCC';
		
		$('input[@id=company]').attr('disabled', val_disabled);
		$('input[@id=company]').css('background-color', bg_color);
		
		$('input[@id=city]').attr('disabled', val_disabled);
		$('input[@id=city]').css('background-color', bg_color);
		
		$('input[@id=siret]').attr('disabled', val_disabled);
		$('input[@id=siret]').css('background-color', bg_color);
	}
	/**
	* vérifie les adresses email des filleuls dans le formulaire de parrainage
	*/
	function parrainage_extra_validation(form_obj){
		//field_check_email
		nb_errs		= 0;
		nb_mails	= 0;
		
		/* vérifie que l'adresse que le client a indiqué correspond bien 
		à une adresse d'un client qui a déja passé commande */
		if ($('input[@id=email]').val() != '') {
		$.ajax({
		   type: "GET",
		   url: $('input[@id=ajax_actions_url]').val(),
		   data: "email=" + $('input[@id=email]').val() + "&action=check-customers-email",
		   async: false,
		   success: function(response){
		   		response = parseInt(response);
				if (isNaN(response) || response == 0) {
					nb_errs++;
					form_obj.raiseError('l\'adresse "' + $('input[@id=email]').val() + '" ne correspond pas à celle d\'un client ayant déjà passé commande. Vous ne pouvez parrainer un ami que si vous avez déjà passé commande.');
				}
		   }
		});
		}
		
		ctrls_mails_filleul = document.getElementsByName('email_filleul[]');
		nb = ctrls_mails_filleul.length;
		for (var i = 0; i < nb; i++) {
			var email	= ctrls_mails_filleul[i].value;
			email		= email.replace(/^\s/, '').replace(/\s$/, '');
			//alert(field_check_email(email));
			if (email != '') {
				if (field_check_email(email)) {
					nb_mails++;
				} else {
					nb_errs++;
					form_obj.raiseError('"' + email + '" ne correspond pas à une adresse email valide');
				}
			}
		}
		
		if (nb_mails == 0) {
			form_obj.raiseError('Vous devez au moins indiquer l\'adresse email d\'un ami');
			nb_errs++;
		}
		
		return (nb_errs == 0);
		
		str_mails	= $('input[@id=email_filleul]').attr('value');
		if (str_mails != undefined) {
			arr_mails = str_mails.split(',');
			nb = arr_mails.length;
			for (var i = 0; i < nb; i++) {
				arr_mails[i]	= arr_mails[i].replace(/^\s/, '').replace(/\s$/, '');
				if (arr_mails[i] != '' && !field_check_email(arr_mails[i])) {
					nb_errs++;
					form_obj.raiseError('"'+arr_mails[i]+'" ne correspond pas à une adresse email valide');
				}
			}
		} else {
			form_obj.raiseError('Vous devez entrer au moins une adresse email de filleul');
			nb_errs++;
			return false;
		}
		return (nb_errs == 0);
	}


/**
	* Validations complémentaire lors de la création de compte
	*/
	function frm_contact_extra(obj_form){
		var nb_errs = 0;
		var val_contact_type = parseInt($('input[@name=contact_type][@checked]').attr('value'));
		
		if (isNaN(val_contact_type)) {
			obj_form.raiseError('Merci d\'indiquer si vous êtes un particulier ou une société');
			nb_errs++;
		} else {
			if (val_contact_type == 1) {
				if ($('input[@name=company]').attr('value') == undefined) {
					obj_form.raiseError('Le champ "Société" est obligatoire');
					nb_errs++;
				}
				
				if ($('input[@name=city]').attr('value') == undefined) {
					obj_form.raiseError('Le champ "Ville" est obligatoire');
					nb_errs++;
				}
				
				if ($('input[@name=siret]').attr('value') == undefined) {
					obj_form.raiseError('Le champ "Siret" est obligatoire');
					nb_errs++;
				}
			} 
		}
		return (nb_errs == 0);
	}
	
	function account_password_extra(obj_form){
		if ($('input[@id=password_new]').attr('value') != $('input[@id=password_confirmation]').attr('value')) {
			obj_form.raiseError('La confirmation doit être identique au nouveau mot de passe renseigné');
			return false;
		}
		return true;
	}

function hide_user_msg(){
	$('#user-msg-box').css({display:'none'});
}


/**
* String user_msg
* Array user_choice array(array('libelle', ['url']))
*
* Utilise http://www.ericmmartin.com/projects/simplemodal/
*/
function display_user_msg(user_msg, user_choice){
	if (user_choice == undefined) {
		var user_choice = new Array(1);
		user_choice[0]	= new Array(2);
		user_choice[0][0] = '<img src="' + $('#http_server').val() + '/includes/languages/french/images/buttons/button_ok.gif' + '" />';
		user_choice[0][1] = '';
	}
	
	if (user_msg != ''){
		user_msg = '<p>' + user_msg + '</p><p class="boutons">';
		/* ajoute les boutons */
		nb = user_choice.length;			
		for(i = 0; i < nb; i++){
			/* si pas d'action sur le choix, bouton fermer */
			if (user_choice[i][1] == '') {
				user_msg += '<a href="javascript:$.modal.close();">' + user_choice[i][0] + '</a>';
			} else {
				user_msg += '<a href="' + user_choice[i][1] + '">' + user_choice[i][0] + '</a>';
			}
		}
		user_msg += '</p>';
		
		//$('body').append(user_msg);
		$.modal(user_msg, {overlay:30});
	}
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function client_resize(obj, dim_max){
	if (obj.height) {
		ratio = obj.width / obj.height;
		if (obj.width > obj.height) {
			obj.width = dim_max;
			obj.height = parseInt(dim_max / ratio);
		} else {
			obj.height = dim_max;
			obj.width = parseInt(dim_max * ratio);
		}		
	}
}

function popupWindow(url) {
  window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,copyhistory=no,width=800,height=800,screenX=150,screenY=150,top=150,left=150');
}


function create_account_extra(form_obj){
	var nb_errs = 0;
	/*var date_naissance = $('input[@id=dob]').attr('value');
	if (date_naissance == undefined || date_naissance == null) {
		date_naissance = '';
	}
	
	//alert($('input[@id=dob]').attr('value'));
	if (!date_naissance.match(/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/)) {
		form_obj.raiseError('Le champ "Date de naissance" est obligatoire');
		nb_errs++;
		$('label[@for=dob]').attr('class', 'error');
	} else {
		$('label[@for=dob]').attr('class', '');
	}*/
	
	/* vérifie que la confirmation de l'adresse email conrrespond à l'adresse saisie */
	if ($('input[@name=email_address_confirm]').attr('value') != $('input[@name=email_address]').attr('value')) {
		form_obj.raiseError('La confirmation de votre adresse email doit correspondre à la première adresse saisie');
		$('label[@for=email_address_confirm]').attr('class', 'error');
		nb_errs++;
	} else {
		if ($('input[@name=email_address_confirm]').attr('value') != '' && $('input[@name=email_address_confirm]').attr('value') != undefined) {	
			$('label[@for=email_address_confirm]').attr('class', '');
		}
	}
	
	//alert('ici ' + $('input[@name=email_address_confirm]').attr('value'));

	/*if ($('input[@name=newsletter][@checked]').length == 0) {
		form_obj.raiseError('Merci d\'indiquer si vous souhaitez recevoir la newsletter Abikid');
		$('div[@id=options]').attr('class', 'error');
		nb_errs++;
	} else {
		$('div[@id=options]').attr('class', '');		
	}*/
	
	var pass = $('input[@name=password]').attr('value');
	if (pass == undefined) {
		pass = '';
	}
	
	if (pass == '' || ($('input[@name=confirmation]').attr('value') != pass)) {
		form_obj.raiseError('Le champ "mot de passe" est obligatoire. La confirmation doit correspondre au mot de passe saisi.');
	}
	
	if (!create_account_check_address(form_obj)){
		nb_errs++;
	}
	
	return (nb_errs == 0);
}

/**
* ouvre une fenêtre popup
*/
function open_popup(url, width, height){
	newwindow = window.open(url,'name','height= ' + height + ',width=' + width + ',resizable=1,scrollbars=1');
	if (window.focus) {newwindow.focus()}
	return false;	
}


function close_popup(url){
	if (url != undefined && opener) {
		opener.location.href = url;		
	}
	window.close();
}

function create_account_check_address(form_obj){
	if ($('#street_address').val() == '' || $('#postcode').val() == '' || $('#city').val() == '') {
		/*  surtout ne pas retourner faux sur un onchange, sinon blocké sur le contrôle */
		return;		
	}
	
	address = $('#street_address').val();
	if ($('#suburb').val() != undefined) {
		address += ' ' + $('#suburb').val();
	}
	address += ' ' + $('#postcode').val();
	address += ' ' + $('#city').val();

	// si on n'est pas capable de vérifier, retourne faux
	if (!check_address(address, $('#postcode').val(), $('#city').val(), $('#country').val())) {
		//alert(form_obj);
		alert('Le code postal saisi ne correspond pas au pays sélectionné dans la liste.');
		return false;
	}
	
	return true;
}

/** 
* fonction utilitaire permettant d'afficher le contenu d'une structure de données 
*/

function dump(arr, level) {
	var dumped_text = "";
	if(!level) level = 0;
		
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j = 0; j < level + 1; j++) level_padding += "    ";
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				try{
					dumped_text += level_padding + "'" + item + "' ...\n";
				} catch (e) {}
				if (level < 10) {
					dumped_text += dump(value, level + 1);
				}
			} else {
				try{
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
				} catch(e){}
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

/**
* Tente de vérifier une adresse, contrôle uniquement la concordance code postal - pays
* cf : http://www.abc-lettres.com/code-postal.html
* 
*/
function check_address(address, postcode, city, country_code){
	var res_check = false;
	$.ajax({
	   type: "GET",
	   url: $('#ajax_actions_url').val(),
	   data: "action=get-country-iso-code&id=" + country_code + "",
	   async: false,
	   success: function(iso_code){
			switch(iso_code){			
			case 'FX': // france métropolitaine
				/* vérifie que le code postal a 5 chiffres
				10 et 20 corse
				puis
				jusqu'à 96999
				*/
				res_check = (postcode.match(/^([12]0|0[1-9]|[1-8][0-9]|9[0-6])[0-9]{3}$/) != null);
			break;
			case 'GP': // guadeloupe
				res_check = (postcode.match(/^(971)[0-9]{2}$/) != null);
			break;
			case 'MQ': // martinique
				res_check = (postcode.match(/^(972)[0-9]{2}$/) != null);
			break;
			case 'RE': // réunion
				res_check = (postcode.match(/^(974)[0-9]{2}$/) != null);		
			break;
			case 'GF': // guyanne française	
				res_check = (postcode.match(/^(973)[0-9]{2}$/) != null);					
			break;
			case 'YT': // mayotte
				res_check = (postcode.match(/^(976)[0-9]{2}$/) != null);
			break;
			case 'PM': // saint pierre et miquelon
				res_check = (postcode.match(/^(975)[0-9]{2}$/) != null);
			break;
			case 'TF': // Terres australes et antarctiques françaises
				res_check = (postcode.match(/^(984)[0-9]{2}$/) != null);
			break;
			case 'WF': // Wallis et Futuna
				res_check = (postcode.match(/^(986)[0-9]{2}$/) != null);
			break;
			case 'NC': // Nouvelle calédonie
				res_check = (postcode.match(/^(988)[0-9]{2}$/) != null);
			break;		
			case 'PF': // Polynesie Française
				res_check = (postcode.match(/^(987)[0-9]{2}$/) != null);
			break;
			default:
				res_check = true;
			break;
			}
	   }
	});
	return res_check;
}

/*
  $Id: general.js,v 1.3 2003/02/10 22:30:55 hpdl Exp $

  osCommerce, Open Source E-Commerce Solutions
  http://www.oscommerce.com

  Copyright (c) 2003 osCommerce

  Released under the GNU General Public License
*/

function SetFocus(TargetFormName) {
  var target = 0;
  if (TargetFormName != "") {
    for (i=0; i<document.forms.length; i++) {
      if (document.forms[i].name == TargetFormName) {
        target = i;
        break;
      }
    }
  }

  var TargetForm = document.forms[target];
    
  for (i=0; i<TargetForm.length; i++) {
    if ( (TargetForm.elements[i].type != "image") && (TargetForm.elements[i].type != "hidden") && (TargetForm.elements[i].type != "reset") && (TargetForm.elements[i].type != "submit") ) {
      TargetForm.elements[i].focus();

      if ( (TargetForm.elements[i].type == "text") || (TargetForm.elements[i].type == "password") ) {
        TargetForm.elements[i].select();
      }

      break;
    }
  }
}

function RemoveFormatString(TargetElement, FormatString) {
  if (TargetElement.value == FormatString) {
    TargetElement.value = "";
  }

  TargetElement.select();
}

function CheckDateRange(from, to) {
  if (Date.parse(from.value) <= Date.parse(to.value)) {
    return true;
  } else {
    return false;
  }
}

/*
function IsValidDate(DateToCheck, FormatString) {
  var strDateToCheck;
  var strDateToCheckArray;
  var strFormatArray;
  var strFormatString;
  var strDay;
  var strMonth;
  var strYear;
  var intday;
  var intMonth;
  var intYear;
  var intDateSeparatorIdx = -1;
  var intFormatSeparatorIdx = -1;
  var strSeparatorArray = new Array("-"," ","/",".");
  var strMonthArray = new Array("jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec");
  var intDaysArray = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

  strDateToCheck = DateToCheck.toLowerCase();
  strFormatString = FormatString.toLowerCase();
  
  if (strDateToCheck.length != strFormatString.length) {
    return false;
  }

  for (i=0; i<strSeparatorArray.length; i++) {
    if (strFormatString.indexOf(strSeparatorArray[i]) != -1) {
      intFormatSeparatorIdx = i;
      break;
    }
  }

  for (i=0; i<strSeparatorArray.length; i++) {
    if (strDateToCheck.indexOf(strSeparatorArray[i]) != -1) {
      intDateSeparatorIdx = i;
      break;
    }
  }

  if (intDateSeparatorIdx != intFormatSeparatorIdx) {
    return false;
  }

  if (intDateSeparatorIdx != -1) {
    strFormatArray = strFormatString.split(strSeparatorArray[intFormatSeparatorIdx]);
    if (strFormatArray.length != 3) {
      return false;
    }

    strDateToCheckArray = strDateToCheck.split(strSeparatorArray[intDateSeparatorIdx]);
    if (strDateToCheckArray.length != 3) {
      return false;
    }

    for (i=0; i<strFormatArray.length; i++) {
      if (strFormatArray[i] == 'mm' || strFormatArray[i] == 'mmm') {
        strMonth = strDateToCheckArray[i];
      }

      if (strFormatArray[i] == 'dd') {
        strDay = strDateToCheckArray[i];
      }

      if (strFormatArray[i] == 'yyyy') {
        strYear = strDateToCheckArray[i];
      }
    }
  } else {
    if (FormatString.length > 7) {
      if (strFormatString.indexOf('mmm') == -1) {
        strMonth = strDateToCheck.substring(strFormatString.indexOf('mm'), 2);
      } else {
        strMonth = strDateToCheck.substring(strFormatString.indexOf('mmm'), 3);
      }

      strDay = strDateToCheck.substring(strFormatString.indexOf('dd'), 2);
      strYear = strDateToCheck.substring(strFormatString.indexOf('yyyy'), 2);
    } else {
      return false;
    }
  }

  if (strYear.length != 4) {
    return false;
  }

  intday = parseInt(strDay, 10);
  if (isNaN(intday)) {
    return false;
  }
  if (intday < 1) {
    return false;
  }

  intMonth = parseInt(strMonth, 10);
  if (isNaN(intMonth)) {
    for (i=0; i<strMonthArray.length; i++) {
      if (strMonth == strMonthArray[i]) {
        intMonth = i+1;
        break;
      }
    }
    if (isNaN(intMonth)) {
      return false;
    }
  }
  if (intMonth > 12 || intMonth < 1) {
    return false;
  }

  intYear = parseInt(strYear, 10);
  if (isNaN(intYear)) {
    return false;
  }
  if (IsLeapYear(intYear) == true) {
    intDaysArray[1] = 29;
  }

  if (intday > intDaysArray[intMonth - 1]) {
    return false;
  }
  
  return true;
}
*/


function IsLeapYear(intYear) {
  if (intYear % 100 == 0) {
    if (intYear % 400 == 0) {
      return true;
    }
  } else {
    if ((intYear % 4) == 0) {
      return true;
    }
  }

  return false;
}

/** enregistre un message dans un log sur le serveur */
function write_to_log(msg, log_name){
	if (log_name == undefined) {
		log_name	= 'errors';	
	}
	
	if (!log_name.match(/^js_/)) {
		log_name = 'js_' + log_name;
	}
	
	try{
		$.ajax({
			type: "GET",
			url: $('input[@id=ajax_actions_url]').val(),
			data: "msg=" + escape(msg) + "&action=write-to-log&log_name=" + log_name,
			async: false,
			success: function(response){}
		});
	} catch(e){}
}/*
 * SimpleModal 1.1.1 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://plugins.jquery.com/project/SimpleModal
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2007 Eric Martin - http://ericmmartin.com
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Revision: $Id: jquery.simplemodal.js 93 2008-01-15 16:14:20Z emartin24 $
 *
 */
(function($){$.modal=function(data,options){return $.modal.impl.init(data,options);};$.modal.close=function(){$.modal.impl.close(true);};$.fn.modal=function(options){return $.modal.impl.init(this,options);};$.modal.defaults={overlay:50,overlayId:'modalOverlay',overlayCss:{},containerId:'modalContainer',containerCss:{},close:true,closeTitle:'Close',closeClass:'modalClose',persist:false,onOpen:null,onShow:null,onClose:null};$.modal.impl={opts:null,dialog:{},init:function(data,options){if(this.dialog.data){return false;}this.opts=$.extend({},$.modal.defaults,options);if(typeof data=='object'){data=data instanceof jQuery?data:$(data);if(data.parent().parent().size()>0){this.dialog.parentNode=data.parent();if(!this.opts.persist){this.dialog.original=data.clone(true);}}}else if(typeof data=='string'||typeof data=='number'){data=$('<div>').html(data);}else{if(console){console.log('SimpleModal Error: Unsupported data type: '+typeof data);}return false;}this.dialog.data=data.addClass('modalData');data=null;this.create();this.open();if($.isFunction(this.opts.onShow)){this.opts.onShow.apply(this,[this.dialog]);}return this;},create:function(){this.dialog.overlay=$('<div>').attr('id',this.opts.overlayId).addClass('modalOverlay').css($.extend(this.opts.overlayCss,{opacity:this.opts.overlay/100,height:'100%',width:'100%',position:'fixed',left:0,top:0,zIndex:3000})).hide().appendTo('body');this.dialog.container=$('<div>').attr('id',this.opts.containerId).addClass('modalContainer').css($.extend(this.opts.containerCss,{position:'fixed',zIndex:3100})).append(this.opts.close?'<a class="modalCloseImg '+this.opts.closeClass
+'" title="'+this.opts.closeTitle+'"></a>':'').hide().appendTo('body');if($.browser.msie&&($.browser.version<7)){this.fixIE();}this.dialog.container.append(this.dialog.data.hide());},bindEvents:function(){var modal=this;$('.'+this.opts.closeClass).click(function(e){e.preventDefault();modal.close();});},unbindEvents:function(){$('.'+this.opts.closeClass).unbind('click');},fixIE:function(){var wHeight=$(document.body).height()+'px';var wWidth=$(document.body).width()+'px';this.dialog.overlay.css({position:'absolute',height:wHeight,width:wWidth});this.dialog.container.css({position:'absolute'});this.dialog.iframe=$('<iframe src="javascript:false;">').css($.extend(this.opts.iframeCss,{opacity:0,position:'absolute',height:wHeight,width:wWidth,zIndex:1000,width:'100%',top:0,left:0})).hide().appendTo('body');},open:function(){if(this.dialog.iframe){this.dialog.iframe.show();}if($.isFunction(this.opts.onOpen)){this.opts.onOpen.apply(this,[this.dialog]);}else{this.dialog.overlay.show();this.dialog.container.show();this.dialog.data.show();}this.bindEvents();},close:function(external){if(!this.dialog.data){return false;}if($.isFunction(this.opts.onClose)&&!external){this.opts.onClose.apply(this,[this.dialog]);}else{if(this.dialog.parentNode){if(this.opts.persist){this.dialog.data.hide().appendTo(this.dialog.parentNode);}else{this.dialog.data.remove();this.dialog.original.appendTo(this.dialog.parentNode);}}else{this.dialog.data.remove();}this.dialog.container.remove();this.dialog.overlay.remove();if(this.dialog.iframe){this.dialog.iframe.remove();}this.dialog={};}this.unbindEvents();}};})(jQuery);/*
 * jQuery Cycle Plugin for light-weight slideshows
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007-2008 M. Alsup
 * Version: 2.22 (06/08/2008)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.1.3.1 or later
 *
 * Based on the work of:
 *  1) Matt Oakes (http://portfolio.gizone.co.uk/applications/slideshow/)
 *  2) Torsten Baldes (http://medienfreunde.com/lab/innerfade/)
 *  3) Benjamin Sterling (http://www.benjaminsterling.com/experiments/jqShuffle/)
 */
(function($) {

var ver = '2.22';
var ie6 = $.browser.msie && /MSIE 6.0/.test(navigator.userAgent);

function log() {
    if (window.console && window.console.log)
        window.console.log('[cycle] ' + Array.prototype.join.call(arguments,''));
};

$.fn.cycle = function(options) {
    return this.each(function() {
        options = options || {};
        if (options.constructor == String) {
            switch(options) {
            case 'stop':
                if (this.cycleTimeout) clearTimeout(this.cycleTimeout);
                this.cycleTimeout = 0;
                return;
            case 'pause':
                this.cyclePause = 1;
                return;
            case 'resume':
                this.cyclePause = 0;
                return;
            default:
                options = { fx: options };
            };
        }

        // stop existing slideshow for this container (if there is one)
        if (this.cycleTimeout) clearTimeout(this.cycleTimeout);
        this.cycleTimeout = 0;
        this.cyclePause = 0;
        
        var $cont = $(this);
        var $slides = options.slideExpr ? $(options.slideExpr, this) : $cont.children();
        var els = $slides.get();
        if (els.length < 2) {
            log('terminating; too few slides: ' + els.length);
            return; // don't bother
        }

        // support metadata plugin (v1.0 and v2.0)
        var opts = $.extend({}, $.fn.cycle.defaults, options || {}, $.metadata ? $cont.metadata() : $.meta ? $cont.data() : {});
        if (opts.autostop) 
            opts.countdown = opts.autostopCount || els.length;
            
        opts.before = opts.before ? [opts.before] : [];
        opts.after = opts.after ? [opts.after] : [];
        opts.after.unshift(function(){ opts.busy=0; });
        if (opts.continuous)
            opts.after.push(function() { go(els,opts,0,!opts.rev); });
            
        // clearType corrections
        if (ie6 && opts.cleartype && !opts.cleartypeNoBg)
            clearTypeFix($slides);

        // allow shorthand overrides of width, height and timeout
        var cls = this.className;
        opts.width = parseInt((cls.match(/w:(\d+)/)||[])[1]) || opts.width;
        opts.height = parseInt((cls.match(/h:(\d+)/)||[])[1]) || opts.height;
        opts.timeout = parseInt((cls.match(/t:(\d+)/)||[])[1]) || opts.timeout;

        if ($cont.css('position') == 'static') 
            $cont.css('position', 'relative');
        if (opts.width) 
            $cont.width(opts.width);
        if (opts.height && opts.height != 'auto') 
            $cont.height(opts.height);

        if (opts.random) {
            opts.randomMap = [];
            for (var i = 0; i < els.length; i++) 
                opts.randomMap.push(i);
            opts.randomMap.sort(function(a,b) {return Math.random() - 0.5;});
            opts.randomIndex = 0;
            opts.startingSlide = opts.randomMap[0];
        }
        else if (opts.startingSlide >= els.length)
            opts.startingSlide = 0; // catch bogus input
        var first = opts.startingSlide || 0;
        $slides.css({position: 'absolute', top:0, left:0}).hide().each(function(i) { 
            var z = first ? i >= first ? els.length - (i-first) : first-i : els.length-i;
            $(this).css('z-index', z) 
        });
        
        $(els[first]).css('opacity',1).show(); // opacity bit needed to handle reinit case
        if ($.browser.msie) els[first].style.removeAttribute('filter');

        if (opts.fit && opts.width) 
            $slides.width(opts.width);
        if (opts.fit && opts.height && opts.height != 'auto') 
            $slides.height(opts.height);
        if (opts.pause) 
            $cont.hover(function(){this.cyclePause=1;}, function(){this.cyclePause=0;});

        // run transition init fn
        var init = $.fn.cycle.transitions[opts.fx];
        if ($.isFunction(init))
            init($cont, $slides, opts);
        else if (opts.fx != 'custom')
            log('unknown transition: ' + opts.fx);
        
        $slides.each(function() {
            var $el = $(this);
            this.cycleH = (opts.fit && opts.height) ? opts.height : $el.height();
            this.cycleW = (opts.fit && opts.width) ? opts.width : $el.width();
        });

        opts.cssBefore = opts.cssBefore || {};
        opts.animIn = opts.animIn || {};
        opts.animOut = opts.animOut || {};

        $slides.not(':eq('+first+')').css(opts.cssBefore);
        if (opts.cssFirst)
            $($slides[first]).css(opts.cssFirst);

        if (opts.timeout) {
            // ensure that timeout and speed settings are sane
            if (opts.speed.constructor == String)
                opts.speed = {slow: 600, fast: 200}[opts.speed] || 400;
            if (!opts.sync)
                opts.speed = opts.speed / 2;
            while((opts.timeout - opts.speed) < 250)
                opts.timeout += opts.speed;
        }
        if (opts.easing) 
            opts.easeIn = opts.easeOut = opts.easing;
        if (!opts.speedIn) 
            opts.speedIn = opts.speed;
        if (!opts.speedOut) 
            opts.speedOut = opts.speed;

 		opts.slideCount = els.length;
        opts.currSlide = first;
        if (opts.random) {
            opts.nextSlide = opts.currSlide;
            if (++opts.randomIndex == els.length) 
                opts.randomIndex = 0;
            opts.nextSlide = opts.randomMap[opts.randomIndex];
        }
        else
            opts.nextSlide = opts.startingSlide >= (els.length-1) ? 0 : opts.startingSlide+1;

        // fire artificial events
        var e0 = $slides[first];
        if (opts.before.length)
            opts.before[0].apply(e0, [e0, e0, opts, true]);
        if (opts.after.length > 1)
            opts.after[1].apply(e0, [e0, e0, opts, true]);
        
        if (opts.click && !opts.next)
            opts.next = opts.click;
        if (opts.next)
            $(opts.next).bind('click', function(){return advance(els,opts,opts.rev?-1:1)});
        if (opts.prev)
            $(opts.prev).bind('click', function(){return advance(els,opts,opts.rev?1:-1)});
        if (opts.pager)
            buildPager(els,opts);

        // expose fn for adding slides after the show has started
        opts.addSlide = function(newSlide) {
            var $s = $(newSlide), s = $s[0];
            if (!opts.autostopCount)
                opts.countdown++;
            els.push(s);
            if (opts.els) 
                opts.els.push(s); // shuffle needs this
            opts.slideCount = els.length;
            
            $s.css('position','absolute').appendTo($cont);
            
            if (ie6 && opts.cleartype && !opts.cleartypeNoBg)
                clearTypeFix($s);

            if (opts.fit && opts.width) 
                $s.width(opts.width);
            if (opts.fit && opts.height && opts.height != 'auto') 
                $slides.height(opts.height);
            s.cycleH = (opts.fit && opts.height) ? opts.height : $s.height();
            s.cycleW = (opts.fit && opts.width) ? opts.width : $s.width();

            $s.css(opts.cssBefore);
            
            if (typeof opts.onAddSlide == 'function')
                opts.onAddSlide($s);
        };

        if (opts.timeout || opts.continuous)
            this.cycleTimeout = setTimeout(
                function(){go(els,opts,0,!opts.rev)}, 
                opts.continuous ? 10 : opts.timeout + (opts.delay||0));
    });
};

function go(els, opts, manual, fwd) {
    if (opts.busy) return;
    var p = els[0].parentNode, curr = els[opts.currSlide], next = els[opts.nextSlide];
    if (p.cycleTimeout === 0 && !manual) 
        return;

    if (!manual && !p.cyclePause && 
        ((opts.autostop && (--opts.countdown <= 0)) ||
        (opts.nowrap && !opts.random && opts.nextSlide < opts.currSlide))) {
        if (opts.end)
            opts.end(opts);
        return;
    }

    if (manual || !p.cyclePause) {
        if (opts.before.length)
            $.each(opts.before, function(i,o) { o.apply(next, [curr, next, opts, fwd]); });
        var after = function() {
            if ($.browser.msie && opts.cleartype)
                this.style.removeAttribute('filter');
            $.each(opts.after, function(i,o) { o.apply(next, [curr, next, opts, fwd]); });
        };

        if (opts.nextSlide != opts.currSlide) {
            opts.busy = 1;
            if (opts.fxFn)
                opts.fxFn(curr, next, opts, after, fwd);
            else if ($.isFunction($.fn.cycle[opts.fx]))
                $.fn.cycle[opts.fx](curr, next, opts, after);
            else
                $.fn.cycle.custom(curr, next, opts, after);
        }
        if (opts.random) {
            opts.currSlide = opts.nextSlide;
            if (++opts.randomIndex == els.length) 
                opts.randomIndex = 0;
            opts.nextSlide = opts.randomMap[opts.randomIndex];
        }
        else { // sequence
            var roll = (opts.nextSlide + 1) == els.length;
            opts.nextSlide = roll ? 0 : opts.nextSlide+1;
            opts.currSlide = roll ? els.length-1 : opts.nextSlide-1;
        }
        if (opts.pager)
            $.fn.cycle.updateActivePagerLink(opts.pager, opts.currSlide);
    }
    if (opts.timeout && !opts.continuous)
        p.cycleTimeout = setTimeout(function() { go(els,opts,0,!opts.rev) }, opts.timeout);
    else if (opts.continuous && p.cyclePause) 
        p.cycleTimeout = setTimeout(function() { go(els,opts,0,!opts.rev) }, 10);
};

$.fn.cycle.updateActivePagerLink = function(pager, currSlide) {
    $(pager).find('a').removeClass('activeSlide').filter('a:eq('+currSlide+')').addClass('activeSlide');
};

// advance slide forward or back
function advance(els, opts, val) {
    var p = els[0].parentNode, timeout = p.cycleTimeout;
    if (timeout) {
        clearTimeout(timeout);
        p.cycleTimeout = 0;
    }
    opts.nextSlide = opts.currSlide + val;
    if (opts.nextSlide < 0) {
        if (opts.nowrap) return false;
        opts.nextSlide = els.length - 1;
    }
    else if (opts.nextSlide >= els.length) {
        if (opts.nowrap) return false;
        opts.nextSlide = 0;
    }
    if (opts.prevNextClick && typeof opts.prevNextClick == 'function')
        opts.prevNextClick(val > 0, opts.nextSlide, els[opts.nextSlide]);
    go(els, opts, 1, val>=0);
    return false;
};

function buildPager(els, opts) {
    var $p = $(opts.pager);
    $.each(els, function(i,o) {
        var $a = (typeof opts.pagerAnchorBuilder == 'function')
            ? $(opts.pagerAnchorBuilder(i,o))
            : $('<a href="#">'+(i+1)+'</a>');
        // don't reparent if anchor is in the dom
        if ($a.parents('body').length == 0)
            $a.appendTo($p);
        $a.bind(opts.pagerEvent, function() {
            opts.nextSlide = i;
            var p = els[0].parentNode, timeout = p.cycleTimeout;
            if (timeout) {
                clearTimeout(timeout);
                p.cycleTimeout = 0;
            }            
            if (typeof opts.pagerClick == 'function')
                opts.pagerClick(opts.nextSlide, els[opts.nextSlide]);
            go(els,opts,1,!opts.rev);
            return false;
        });
    });
   //$p.find('a').filter('a:eq('+opts.startingSlide+')').addClass('activeSlide');
   $.fn.cycle.updateActivePagerLink(opts.pager, opts.startingSlide);
};

// this fixes clearType problems in ie6 by setting an explicit bg color
function clearTypeFix($slides) {
    function hex(s) {
        var s = parseInt(s).toString(16);
        return s.length < 2 ? '0'+s : s;
    };
    function getBg(e) {
        for ( ; e && e.nodeName.toLowerCase() != 'html'; e = e.parentNode) {
            var v = $.css(e,'background-color');
            if (v.indexOf('rgb') >= 0 ) { 
                var rgb = v.match(/\d+/g); 
                return '#'+ hex(rgb[0]) + hex(rgb[1]) + hex(rgb[2]);
            }
            if (v && v != 'transparent')
                return v;
        }
        return '#ffffff';
    };
    $slides.each(function() { $(this).css('background-color', getBg(this)); });
};


$.fn.cycle.custom = function(curr, next, opts, cb) {
    var $l = $(curr), $n = $(next);
    $n.css(opts.cssBefore);
    var fn = function() {$n.animate(opts.animIn, opts.speedIn, opts.easeIn, cb)};
    $l.animate(opts.animOut, opts.speedOut, opts.easeOut, function() {
        if (opts.cssAfter) $l.css(opts.cssAfter);
        if (!opts.sync) fn();
    });
    if (opts.sync) fn();
};

$.fn.cycle.transitions = {
    fade: function($cont, $slides, opts) {
        $slides.not(':eq('+opts.startingSlide+')').css('opacity',0);
        opts.before.push(function() { $(this).show() });
        opts.animIn    = { opacity: 1 };
        opts.animOut   = { opacity: 0 };
        opts.cssBefore = { opacity: 0 };
        opts.cssAfter  = { display: 'none' };
    }
};

$.fn.cycle.ver = function() { return ver; };

// override these globally if you like (they are all optional)
$.fn.cycle.defaults = {
    fx:           'fade', // one of: fade, shuffle, zoom, scrollLeft, etc
    timeout:       4000,  // milliseconds between slide transitions (0 to disable auto advance)
    continuous:    0,     // true to start next transition immediately after current one completes
    speed:         1000,  // speed of the transition (any valid fx speed value)
    speedIn:       null,  // speed of the 'in' transition
    speedOut:      null,  // speed of the 'out' transition
    next:          null,  // id of element to use as click trigger for next slide
    prev:          null,  // id of element to use as click trigger for previous slide
    prevNextClick: null,  // callback fn for prev/next clicks:  function(isNext, zeroBasedSlideIndex, slideElement)
    pager:         null,  // id of element to use as pager container
    pagerClick:    null,  // callback fn for pager clicks:  function(zeroBasedSlideIndex, slideElement)
    pagerEvent:   'click', // event which drives the pager navigation
    pagerAnchorBuilder: null, // callback fn for building anchor links
    before:        null,  // transition callback (scope set to element to be shown)
    after:         null,  // transition callback (scope set to element that was shown)
    end:           null,  // callback invoked when the slideshow terminates (use with autostop or nowrap options)
    easing:        null,  // easing method for both in and out transitions
    easeIn:        null,  // easing for "in" transition
    easeOut:       null,  // easing for "out" transition
    shuffle:       null,  // coords for shuffle animation, ex: { top:15, left: 200 }
    animIn:        null,  // properties that define how the slide animates in
    animOut:       null,  // properties that define how the slide animates out
    cssBefore:     null,  // properties that define the initial state of the slide before transitioning in
    cssAfter:      null,  // properties that defined the state of the slide after transitioning out
    fxFn:          null,  // function used to control the transition
    height:       'auto', // container height
    startingSlide: 0,     // zero-based index of the first slide to be displayed
    sync:          1,     // true if in/out transitions should occur simultaneously
    random:        0,     // true for random, false for sequence (not applicable to shuffle fx)
    fit:           0,     // force slides to fit container
    pause:         0,     // true to enable "pause on hover"
    autostop:      0,     // true to end slideshow after X transitions (where X == slide count)
    autostopCount: 0,     // number of transitions (optionally used with autostop to define X)
    delay:         0,     // additional delay (in ms) for first transition (hint: can be negative)
    slideExpr:     null,  // expression for selecting slides (if something other than all children is required)
    cleartype:     0,     // true if clearType corrections should be applied (for IE)
    nowrap:        0      // true to prevent slideshow from wrapping
};

})(jQuery);


/*
 * jQuery Cycle Plugin Transition Definitions
 * This script is a plugin for the jQuery Cycle Plugin
 * Examples and documentation at: http://malsup.com/jquery/cycle/
 * Copyright (c) 2007-2008 M. Alsup
 * Version:  2.22
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($) {

//
// These functions define one-time slide initialization for the named
// transitions. To save file size feel free to remove any of these that you 
// don't need.
//

// scrollUp/Down/Left/Right
$.fn.cycle.transitions.scrollUp = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.top = next.offsetHeight;
        opts.animOut.top = 0-curr.offsetHeight;
    });
    opts.cssFirst = { top: 0 };
    opts.animIn   = { top: 0 };
    opts.cssAfter = { display: 'none' };
};
$.fn.cycle.transitions.scrollDown = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.top = 0-next.offsetHeight;
        opts.animOut.top = curr.offsetHeight;
    });
    opts.cssFirst = { top: 0 };
    opts.animIn   = { top: 0 };
    opts.cssAfter = { display: 'none' };
};
$.fn.cycle.transitions.scrollLeft = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.left = next.offsetWidth;
        opts.animOut.left = 0-curr.offsetWidth;
    });
    opts.cssFirst = { left: 0 };
    opts.animIn   = { left: 0 };
};
$.fn.cycle.transitions.scrollRight = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.left = 0-next.offsetWidth;
        opts.animOut.left = curr.offsetWidth;
    });
    opts.cssFirst = { left: 0 };
    opts.animIn   = { left: 0 };
};
$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
    $cont.css('overflow','hidden').width();
//    $slides.show();
    opts.before.push(function(curr, next, opts, fwd) {
        $(this).show();
        var currW = curr.offsetWidth, nextW = next.offsetWidth;
        opts.cssBefore = fwd ? { left: nextW } : { left: -nextW };
        opts.animIn.left = 0;
        opts.animOut.left = fwd ? -currW : currW;
        $slides.not(curr).css(opts.cssBefore);
    });
    opts.cssFirst = { left: 0 };
    opts.cssAfter = { display: 'none' }
};
$.fn.cycle.transitions.scrollVert = function($cont, $slides, opts) {
    $cont.css('overflow','hidden');
//    $slides.show();
    opts.before.push(function(curr, next, opts, fwd) {
        $(this).show();
        var currH = curr.offsetHeight, nextH = next.offsetHeight;
        opts.cssBefore = fwd ? { top: -nextH } : { top: nextH };
        opts.animIn.top = 0;
        opts.animOut.top = fwd ? currH : -currH;
        $slides.not(curr).css(opts.cssBefore);
    });
    opts.cssFirst = { top: 0 };
    opts.cssAfter = { display: 'none' }
};

// slideX/slideY
$.fn.cycle.transitions.slideX = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssBefore = { zIndex: 2 };
    opts.animIn  = { width: 'show' };
    opts.animOut = { width: 'hide' };
};
$.fn.cycle.transitions.slideY = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssBefore = { zIndex: 2 };
    opts.animIn  = { height: 'show' };
    opts.animOut = { height: 'hide' };
};

// shuffle
$.fn.cycle.transitions.shuffle = function($cont, $slides, opts) {
    var w = $cont.css('overflow', 'visible').width();
    $slides.css({left: 0, top: 0});
    opts.before.push(function() { $(this).show() });
    opts.speed = opts.speed / 2; // shuffle has 2 transitions        
    opts.random = 0;
    opts.shuffle = opts.shuffle || {left:-w, top:15};
    opts.els = [];
    for (var i=0; i < $slides.length; i++)
        opts.els.push($slides[i]);

    for (var i=0; i < opts.startingSlide; i++)
        opts.els.push(opts.els.shift());

    // custom transition fn (hat tip to Benjamin Sterling for this bit of sweetness!)
    opts.fxFn = function(curr, next, opts, cb, fwd) {
        var $el = fwd ? $(curr) : $(next);
        $el.animate(opts.shuffle, opts.speedIn, opts.easeIn, function() {
            fwd ? opts.els.push(opts.els.shift()) : opts.els.unshift(opts.els.pop());
            if (fwd) 
                for (var i=0, len=opts.els.length; i < len; i++)
                    $(opts.els[i]).css('z-index', len-i);
            else {
                var z = $(curr).css('z-index');
                $el.css('z-index', parseInt(z)+1);
            }
            $el.animate({left:0, top:0}, opts.speedOut, opts.easeOut, function() {
                $(fwd ? this : curr).hide();
                if (cb) cb();
            });
        });
    };
    opts.onAddSlide = function($s) { $s.hide(); };
};

// turnUp/Down/Left/Right
$.fn.cycle.transitions.turnUp = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.top = next.cycleH;
        opts.animIn.height = next.cycleH;
    });
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssFirst  = { top: 0 };
    opts.cssBefore = { height: 0 };
    opts.animIn    = { top: 0 };
    opts.animOut   = { height: 0 };
    opts.cssAfter  = { display: 'none' };
};
$.fn.cycle.transitions.turnDown = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.animIn.height = next.cycleH;
        opts.animOut.top   = curr.cycleH;
    });
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssFirst  = { top: 0 };
    opts.cssBefore = { top: 0, height: 0 };
    opts.animOut   = { height: 0 };
    opts.cssAfter  = { display: 'none' };
};
$.fn.cycle.transitions.turnLeft = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore.left = next.cycleW;
        opts.animIn.width = next.cycleW;
    });
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssBefore = { width: 0 };
    opts.animIn    = { left: 0 };
    opts.animOut   = { width: 0 };
    opts.cssAfter  = { display: 'none' };
};
$.fn.cycle.transitions.turnRight = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.animIn.width = next.cycleW;
        opts.animOut.left = curr.cycleW;
    });
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssBefore = { left: 0, width: 0 };
    opts.animIn    = { left: 0 };
    opts.animOut   = { width: 0 };
    opts.cssAfter  = { display: 'none' };
};

// zoom
$.fn.cycle.transitions.zoom = function($cont, $slides, opts) {
    opts.cssFirst = { top:0, left: 0 }; 
    opts.cssAfter = { display: 'none' };
    
    opts.before.push(function(curr, next, opts) {
        $(this).show();
        opts.cssBefore = { width: 0, height: 0, top: next.cycleH/2, left: next.cycleW/2 };
        opts.cssAfter  = { display: 'none' };
        opts.animIn    = { top: 0, left: 0, width: next.cycleW, height: next.cycleH };
        opts.animOut   = { width: 0, height: 0, top: curr.cycleH/2, left: curr.cycleW/2 };
        $(curr).css('zIndex',2);
        $(next).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
};

// fadeZoom
$.fn.cycle.transitions.fadeZoom = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = { width: 0, height: 0, opacity: 1, left: next.cycleW/2, top: next.cycleH/2, zIndex: 1 };
        opts.animIn    = { top: 0, left: 0, width: next.cycleW, height: next.cycleH };
    });    
    opts.animOut  = { opacity: 0 };
    opts.cssAfter = { zIndex: 0 };
};

// blindX
$.fn.cycle.transitions.blindX = function($cont, $slides, opts) {
    var w = $cont.css('overflow','hidden').width();
    $slides.show();
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',1);
    });    
    opts.cssBefore = { left: w, zIndex: 2 };
    opts.cssAfter = { zIndex: 1 };
    opts.animIn = { left: 0 };
    opts.animOut  = { left: w };
};
// blindY
$.fn.cycle.transitions.blindY = function($cont, $slides, opts) {
    var h = $cont.css('overflow','hidden').height();
    $slides.show();
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',1);
    });    
    opts.cssBefore = { top: h, zIndex: 2 };
    opts.cssAfter = { zIndex: 1 };
    opts.animIn = { top: 0 };
    opts.animOut  = { top: h };
};
// blindZ
$.fn.cycle.transitions.blindZ = function($cont, $slides, opts) {
    var h = $cont.css('overflow','hidden').height();
    var w = $cont.width();
    $slides.show();
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',1);
    });    
    opts.cssBefore = { top: h, left: w, zIndex: 2 };
    opts.cssAfter = { zIndex: 1 };
    opts.animIn = { top: 0, left: 0 };
    opts.animOut  = { top: h, left: w };
};

// growX - grow horizontally from centered 0 width
$.fn.cycle.transitions.growX = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = { left: this.cycleW/2, width: 0, zIndex: 2 };
        opts.animIn = { left: 0, width: this.cycleW };
        opts.animOut = { left: 0 };
        $(curr).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide().css('zIndex',1); };
};
// growY - grow vertically from centered 0 height
$.fn.cycle.transitions.growY = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = { top: this.cycleH/2, height: 0, zIndex: 2 };
        opts.animIn = { top: 0, height: this.cycleH };
        opts.animOut = { top: 0 };
        $(curr).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide().css('zIndex',1); };
};

// curtainX - squeeze in both edges horizontally
$.fn.cycle.transitions.curtainX = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = { left: next.cycleW/2, width: 0, zIndex: 1, display: 'block' };
        opts.animIn = { left: 0, width: this.cycleW };
        opts.animOut = { left: curr.cycleW/2, width: 0 };
        $(curr).css('zIndex',2);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssAfter = { zIndex: 1, display: 'none' };
};
// curtainY - squeeze in both edges vertically
$.fn.cycle.transitions.curtainY = function($cont, $slides, opts) {
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = { top: next.cycleH/2, height: 0, zIndex: 1, display: 'block' };
        opts.animIn = { top: 0, height: this.cycleH };
        opts.animOut = { top: curr.cycleH/2, height: 0 };
        $(curr).css('zIndex',2);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssAfter = { zIndex: 1, display: 'none' };
};

// cover - curr slide covered by next slide
$.fn.cycle.transitions.cover = function($cont, $slides, opts) {
    var d = opts.direction || 'left';
    var w = $cont.css('overflow','hidden').width();
    var h = $cont.height();
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore = opts.cssBefore || {};
        opts.cssBefore.zIndex = 2;
        opts.cssBefore.display = 'block';
        
        if (d == 'right') 
            opts.cssBefore.left = -w;
        else if (d == 'up')    
            opts.cssBefore.top = h;
        else if (d == 'down')  
            opts.cssBefore.top = -h;
        else
            opts.cssBefore.left = w;
        $(curr).css('zIndex',1);
    });    
    if (!opts.animIn)  opts.animIn = { left: 0, top: 0 };
    if (!opts.animOut) opts.animOut = { left: 0, top: 0 };
    opts.cssAfter = opts.cssAfter || {};
    opts.cssAfter.zIndex = 2;
    opts.cssAfter.display = 'none';
};

// uncover - curr slide moves off next slide
$.fn.cycle.transitions.uncover = function($cont, $slides, opts) {
    var d = opts.direction || 'left';
    var w = $cont.css('overflow','hidden').width();
    var h = $cont.height();
    opts.before.push(function(curr, next, opts) {
        opts.cssBefore.display = 'block';
        if (d == 'right') 
            opts.animOut.left = w;
        else if (d == 'up')    
            opts.animOut.top = -h;
        else if (d == 'down')  
            opts.animOut.top = h;
        else
            opts.animOut.left = -w;
        $(curr).css('zIndex',2);
        $(next).css('zIndex',1);
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    if (!opts.animIn)  opts.animIn = { left: 0, top: 0 };
    opts.cssBefore = opts.cssBefore || {};
    opts.cssBefore.top = 0;
    opts.cssBefore.left = 0;
    
    opts.cssAfter = opts.cssAfter || {};
    opts.cssAfter.zIndex = 1;
    opts.cssAfter.display = 'none';
};

// toss - move top slide and fade away
$.fn.cycle.transitions.toss = function($cont, $slides, opts) {
    var w = $cont.css('overflow','visible').width();
    var h = $cont.height();
    opts.before.push(function(curr, next, opts) {
        $(curr).css('zIndex',2);
        opts.cssBefore.display = 'block'; 
        // provide default toss settings if animOut not provided
        if (!opts.animOut.left && !opts.animOut.top)
            opts.animOut = { left: w*2, top: -h/2, opacity: 0 };
        else
            opts.animOut.opacity = 0;
    });    
    opts.onAddSlide = function($s) { $s.hide(); };
    opts.cssBefore = { left: 0, top: 0, zIndex: 1, opacity: 1 };
    opts.animIn = { left: 0 };
    opts.cssAfter = { zIndex: 2, display: 'none' };
};

// wipe - clip animation
$.fn.cycle.transitions.wipe = function($cont, $slides, opts) {
    var w = $cont.css('overflow','hidden').width();
    var h = $cont.height();
    opts.cssBefore = opts.cssBefore || {};
    var clip;
    if (opts.clip) {
        if (/l2r/.test(opts.clip))
            clip = 'rect(0px 0px '+h+'px 0px)';
        else if (/r2l/.test(opts.clip))
            clip = 'rect(0px '+w+'px '+h+'px '+w+'px)';
        else if (/t2b/.test(opts.clip))
            clip = 'rect(0px '+w+'px 0px 0px)';
        else if (/b2t/.test(opts.clip))
            clip = 'rect('+h+'px '+w+'px '+h+'px 0px)';
        else if (/zoom/.test(opts.clip)) {
            var t = parseInt(h/2);
            var l = parseInt(w/2);
            clip = 'rect('+t+'px '+l+'px '+t+'px '+l+'px)';
        }
    }
    
    opts.cssBefore.clip = opts.cssBefore.clip || clip || 'rect(0px 0px 0px 0px)';
    
    var d = opts.cssBefore.clip.match(/(\d+)/g);
    var t = parseInt(d[0]), r = parseInt(d[1]), b = parseInt(d[2]), l = parseInt(d[3]);
    
    opts.before.push(function(curr, next, opts) {
        if (curr == next) return;
        var $curr = $(curr).css('zIndex',2);
        var $next = $(next).css({
            zIndex:  3,
            display: 'block'
        });
        
        var step = 1, count = parseInt((opts.speedIn / 13)) - 1;
        function f() {
            var tt = t ? t - parseInt(step * (t/count)) : 0;
            var ll = l ? l - parseInt(step * (l/count)) : 0;
            var bb = b < h ? b + parseInt(step * ((h-b)/count || 1)) : h;
            var rr = r < w ? r + parseInt(step * ((w-r)/count || 1)) : w;
            $next.css({ clip: 'rect('+tt+'px '+rr+'px '+bb+'px '+ll+'px)' });
            (step++ <= count) ? setTimeout(f, 13) : $curr.css('display', 'none');
        }
        f();
    });    
    opts.cssAfter  = { };
    opts.animIn    = { left: 0 };
    opts.animOut   = { left: 0 };
};

})(jQuery);
