//sexy-combo 2.1.3 | Authors: Kadalashvili.Vladimir@gmail.com - Vladimir Kadalashvili, thetoolman@gmail.com | http://code.google.com/p/sexy-combo/ | licensed under the GPL license
;(function($){$.fn.sexyCombo=function(config){return this.each(function(){if("SELECT"!=this.tagName.toUpperCase()){return;}new $sc(this,config);});};var defaults={skin:"sexy",suffix:"__sexyCombo",hiddenSuffix:"__sexyComboHidden",renameOriginal:false,initialHiddenValue:"",emptyText:"",autoFill:false,triggerSelected:true,filterFn:null,dropUp:false,separator:",",key:"value",value:"text",showListCallback:null,hideListCallback:null,initCallback:null,initEventsCallback:null,changeCallback:null,textChangeCallback:null,checkWidth:true};$.sexyCombo=function(selectbox,config){if(selectbox.tagName.toUpperCase()!="SELECT")return;this.config=$.extend({},defaults,config||{});this.selectbox=$(selectbox);this.options=this.selectbox.children().filter("option");this.wrapper=this.selectbox.wrap("<div>").hide().parent().addClass("combo").addClass(this.config.skin);this.input=$("<input type='text' />").appendTo(this.wrapper).attr("autocomplete","off").attr("value","").attr("name",this.selectbox.attr("name")+this.config.suffix);var origName=this.selectbox.attr("name");var newName=origName+this.config.hiddenSuffix;if(this.config.renameOriginal){this.selectbox.attr("name",newName);}this.hidden=$("<input type='hidden' />").appendTo(this.wrapper).attr("autocomplete","off").attr("value",this.config.initialHiddenValue).attr("name",this.config.renameOriginal?origName:newName);this.icon=$("<div />").appendTo(this.wrapper).addClass("icon");this.listWrapper=$("<div />").appendTo(this.wrapper).addClass("list-wrapper");this.updateDrop();this.list=$("<ul />").appendTo(this.listWrapper);var self=this;var optWidths=[];this.options.each(function(){var optionText=$.trim($(this).text());if(self.config.checkWidth){optWidths.push($("<li />").appendTo(self.list).html("<span>"+optionText+"</span>").addClass("visible").find("span").outerWidth());}else{$("<li />").appendTo(self.list).html("<span>"+optionText+"</span>").addClass("visible");}});this.listItems=this.list.children();if(optWidths.length){optWidths=optWidths.sort(function(a,b){return a-b;});var maxOptionWidth=optWidths[optWidths.length-1];}this.singleItemHeight=this.listItems.outerHeight();this.listWrapper.addClass("invisible");if($.browser.opera){this.wrapper.css({position:"relative",left:"0",top:"0"});}this.filterFn=("function"==typeof(this.config.filterFn))?this.config.filterFn:this.filterFn;this.lastKey=null;this.multiple=this.selectbox.attr("multiple");var self=this;this.wrapper.data("sc:lastEvent","click");this.overflowCSS="overflowY";if((this.config.checkWidth)&&(this.listWrapper.innerWidth()<maxOptionWidth)){this.overflowCSS="overflow";}this.notify("init");this.initEvents();};var $sc=$.sexyCombo;$sc.fn=$sc.prototype={};$sc.fn.extend=$sc.extend=$.extend;$sc.fn.extend({initEvents:function(){var self=this;this.icon.bind("click",function(e){if(!self.wrapper.data("sc:positionY")){self.wrapper.data("sc:positionY",e.pageY);}});this.input.bind("click",function(e){if(!self.wrapper.data("sc:positionY")){self.wrapper.data("sc:positionY",e.pageY);}});this.wrapper.bind("click",function(e){if(!self.wrapper.data("sc:positionY")){self.wrapper.data("sc:positionY",e.pageY);}});this.icon.bind("click",function(){if(self.input.attr("disabled")){self.input.attr("disabled",false);}self.wrapper.data("sc:lastEvent","click");self.filter();self.iconClick();});this.listItems.bind("mouseover",function(e){if("LI"==e.target.nodeName.toUpperCase()){self.highlight(e.target);}else{self.highlight($(e.target).parent());}});this.listItems.bind("click",function(e){self.listItemClick($(e.target));});this.input.bind("keyup",function(e){self.wrapper.data("sc:lastEvent","key");self.keyUp(e);});this.input.bind("keypress",function(e){if($sc.KEY.RETURN==e.keyCode){e.preventDefault();}if($sc.KEY.TAB==e.keyCode)e.preventDefault();});$(document).bind("click",function(e){if((self.icon.get(0)==e.target)||(self.input.get(0)==e.target))return;self.hideList();});this.triggerSelected();this.applyEmptyText();this.input.bind("click",function(e){self.wrapper.data("sc:lastEvent","click");self.icon.trigger("click");});this.wrapper.bind("click",function(){self.wrapper.data("sc:lastEvent","click");});this.input.bind("keydown",function(e){if(9==e.keyCode){e.preventDefault();}});this.wrapper.bind("keyup",function(e){var k=e.keyCode;for(key in $sc.KEY){if($sc.KEY[key]==k){return;}}self.wrapper.data("sc:lastEvent","key");});this.input.bind("click",function(){self.wrapper.data("sc:lastEvent","click");});this.icon.bind("click",function(e){if(!self.wrapper.data("sc:positionY")){self.wrapper.data("sc:positionY",e.pageY);}});this.input.bind("click",function(e){if(!self.wrapper.data("sc:positionY")){self.wrapper.data("sc:positionY",e.pageY);}});this.wrapper.bind("click",function(e){if(!self.wrapper.data("sc:positionY")){self.wrapper.data("sc:positionY",e.pageY);}});this.notify("initEvents");},getTextValue:function(){return this.__getValue("input");},getCurrentTextValue:function(){return this.__getCurrentValue("input");},getHiddenValue:function(){return this.__getValue("hidden");},getCurrentHiddenValue:function(){return this.__getCurrentValue("hidden");},__getValue:function(prop){prop=this[prop];if(!this.multiple)return $.trim(prop.val());var tmpVals=prop.val().split(this.config.separator);var vals=[];for(var i=0,len=tmpVals.length;i<len;++i){vals.push($.trim(tmpVals[i]));}vals=$sc.normalizeArray(vals);return vals;},__getCurrentValue:function(prop){prop=this[prop];if(!this.multiple)return $.trim(prop.val());return $.trim(prop.val().split(this.config.separator).pop());},iconClick:function(){if(this.listVisible()){this.hideList();this.input.blur();}else{this.showList();this.input.focus();if(this.input.val().length){this.selection(this.input.get(0),0,this.input.val().length);}}},listVisible:function(){return this.listWrapper.hasClass("visible");},showList:function(){if(!this.listItems.filter(".visible").length)return;this.listWrapper.removeClass("invisible").addClass("visible");this.wrapper.css("zIndex","99999");this.listWrapper.css("zIndex","99999");this.setListHeight();var listHeight=this.listWrapper.height();var inputHeight=this.wrapper.height();var bottomPos=parseInt(this.wrapper.data("sc:positionY"))+inputHeight+listHeight;var maxShown=$(window).height()+$(document).scrollTop();if(bottomPos>maxShown){this.setDropUp(true);}else{this.setDropUp(false);}if(""==$.trim(this.input.val())){this.highlightFirst();this.listWrapper.scrollTop(0);}else{this.highlightSelected();}this.notify("showList");},hideList:function(){if(this.listWrapper.hasClass("invisible"))return;this.listWrapper.removeClass("visible").addClass("invisible");this.wrapper.css("zIndex","0");this.listWrapper.css("zIndex","99999");this.notify("hideList");},getListItemsHeight:function(){var itemHeight=this.singleItemHeight;return itemHeight*this.liLen();},setOverflow:function(){var maxHeight=this.getListMaxHeight();if(this.getListItemsHeight()>maxHeight)this.listWrapper.css(this.overflowCSS,"scroll");else
this.listWrapper.css(this.overflowCSS,"hidden");},highlight:function(activeItem){if(($sc.KEY.DOWN==this.lastKey)||($sc.KEY.UP==this.lastKey))return;this.listItems.removeClass("active");$(activeItem).addClass("active");},setComboValue:function(val,pop,hideList){var oldVal=this.input.val();var v="";if(this.multiple){v=this.getTextValue();if(pop)v.pop();v.push($.trim(val));v=$sc.normalizeArray(v);v=v.join(this.config.separator)+this.config.separator;}else{v=$.trim(val);}this.input.val(v);this.setHiddenValue(val);this.filter();if(hideList)this.hideList();this.input.removeClass("empty");if(this.multiple)this.input.focus();if(this.input.val()!=oldVal)this.notify("textChange");},setHiddenValue:function(val){var set=false;val=$.trim(val);var oldVal=this.hidden.val();if(!this.multiple){for(var i=0,len=this.options.length;i<len;++i){if(val==this.options.eq(i).text()){this.hidden.val(this.options.eq(i).val());set=true;break;}}}else{var comboVals=this.getTextValue();var hiddenVals=[];for(var i=0,len=comboVals.length;i<len;++i){for(var j=0,len1=this.options.length;j<len1;++j){if(comboVals[i]==this.options.eq(j).text()){hiddenVals.push(this.options.eq(j).val());}}}if(hiddenVals.length){set=true;this.hidden.val(hiddenVals.join(this.config.separator));}}if(!set){this.hidden.val(this.config.initialHiddenValue);}if(oldVal!=this.hidden.val())this.notify("change");this.selectbox.val(this.hidden.val());this.selectbox.trigger("change");},listItemClick:function(item){this.setComboValue(item.text(),true,true);this.inputFocus();},filter:function(){if("yes"==this.wrapper.data("sc:optionsChanged")){var self=this;this.listItems.remove();this.options=this.selectbox.children().filter("option");this.options.each(function(){var optionText=$.trim($(this).text());$("<li />").appendTo(self.list).text(optionText).addClass("visible");});this.listItems=this.list.children();this.listItems.bind("mouseover",function(e){self.highlight(e.target);});this.listItems.bind("click",function(e){self.listItemClick($(e.target));});self.wrapper.data("sc:optionsChanged","");}var comboValue=this.input.val();var self=this;this.listItems.each(function(){var $this=$(this);var itemValue=$this.text();if(self.filterFn.call(self,self.getCurrentTextValue(),itemValue,self.getTextValue())){$this.removeClass("invisible").addClass("visible");}else{$this.removeClass("visible").addClass("invisible");}});this.setOverflow();this.setListHeight();},filterFn:function(currentComboValue,itemValue,allComboValues){if("click"==this.wrapper.data("sc:lastEvent")){return true;}if(!this.multiple){return itemValue.toLowerCase().indexOf(currentComboValue.toLowerCase())==0;}else{for(var i=0,len=allComboValues.length;i<len;++i){if(itemValue==allComboValues[i]){return false;}}return itemValue.toLowerCase().search(currentComboValue.toLowerCase())==0;}},getListMaxHeight:function(){var result=parseInt(this.listWrapper.css("maxHeight"),10);if(isNaN(result)){result=this.singleItemHeight*10;}return result;},setListHeight:function(){var liHeight=this.getListItemsHeight();var maxHeight=this.getListMaxHeight();var listHeight=this.listWrapper.height();if(liHeight<listHeight){this.listWrapper.height(liHeight);return liHeight;}else if(liHeight>listHeight){this.listWrapper.height(Math.min(maxHeight,liHeight));return Math.min(maxHeight,liHeight);}},getActive:function(){return this.listItems.filter(".active");},keyUp:function(e){this.lastKey=e.keyCode;var k=$sc.KEY;switch(e.keyCode){case k.RETURN:case k.TAB:this.setComboValue(this.getActive().text(),true,true);if(!this.multiple)break;case k.DOWN:this.highlightNext();break;case k.UP:this.highlightPrev();break;case k.ESC:this.hideList();break;default:this.inputChanged();break;}},liLen:function(){return this.listItems.filter(".visible").length;},inputChanged:function(){this.filter();if(this.liLen()){this.showList();this.setOverflow();this.setListHeight();}else{this.hideList();}this.setHiddenValue(this.input.val());this.notify("textChange");},highlightFirst:function(){this.listItems.removeClass("active").filter(".visible:eq(0)").addClass("active");this.autoFill();},highlightSelected:function(){this.listItems.removeClass("active");var val=$.trim(this.input.val());try{this.listItems.each(function(){var $this=$(this);if($this.text()==val){$this.addClass("active");self.listWrapper.scrollTop(0);self.scrollDown();}});this.highlightFirst();}catch(e){}},highlightNext:function(){var $next=this.getActive().next();while($next.hasClass("invisible")&&$next.length){$next=$next.next();}if($next.length){this.listItems.removeClass("active");$next.addClass("active");this.scrollDown();}},scrollDown:function(){if("scroll"!=this.listWrapper.css(this.overflowCSS))return;var beforeActive=this.getActiveIndex()+1;var minScroll=this.listItems.outerHeight()*beforeActive-this.listWrapper.height();if($.browser.msie)minScroll+=beforeActive;if(this.listWrapper.scrollTop()<minScroll)this.listWrapper.scrollTop(minScroll);},highlightPrev:function(){var $prev=this.getActive().prev();while($prev.length&&$prev.hasClass("invisible"))$prev=$prev.prev();if($prev.length){this.getActive().removeClass("active");$prev.addClass("active");this.scrollUp();}},getActiveIndex:function(){return $.inArray(this.getActive().get(0),this.listItems.filter(".visible").get());},scrollUp:function(){if("scroll"!=this.listWrapper.css(this.overflowCSS))return;var maxScroll=this.getActiveIndex()*this.listItems.outerHeight();if(this.listWrapper.scrollTop()>maxScroll){this.listWrapper.scrollTop(maxScroll);}},applyEmptyText:function(){if(!this.config.emptyText.length)return;var self=this;this.input.bind("focus",function(){self.inputFocus();}).bind("blur",function(){self.inputBlur();});if(""==this.input.val()){this.input.addClass("empty").val(this.config.emptyText);}},inputFocus:function(){if(this.input.hasClass("empty")){this.input.removeClass("empty").val("");}},inputBlur:function(){if(""==this.input.val()){this.input.addClass("empty").val(this.config.emptyText);}},triggerSelected:function(){if(!this.config.triggerSelected)return;var self=this;try{this.options.each(function(){if($(this).attr("selected")){self.setComboValue($(this).text(),false,true);throw new Error();}});}catch(e){return;}self.setComboValue(this.options.eq(0).text(),false,false);},autoFill:function(){if(!this.config.autoFill||($sc.KEY.BACKSPACE==this.lastKey)||this.multiple)return;var curVal=this.input.val();var newVal=this.getActive().text();this.input.val(newVal);this.selection(this.input.get(0),curVal.length,newVal.length);},selection:function(field,start,end){if(field.createTextRange){var selRange=field.createTextRange();selRange.collapse(true);selRange.moveStart("character",start);selRange.moveEnd("character",end);selRange.select();}else if(field.setSelectionRange){field.setSelectionRange(start,end);}else{if(field.selectionStart){field.selectionStart=start;field.selectionEnd=end;}}},updateDrop:function(){if(this.config.dropUp)this.listWrapper.addClass("list-wrapper-up");else
this.listWrapper.removeClass("list-wrapper-up");},setDropUp:function(drop){this.config.dropUp=drop;this.updateDrop();},notify:function(evt){if(!$.isFunction(this.config[evt+"Callback"]))return;this.config[evt+"Callback"].call(this);}});$sc.extend({KEY:{UP:38,DOWN:40,DEL:46,TAB:9,RETURN:13,ESC:27,COMMA:188,PAGEUP:33,PAGEDOWN:34,BACKSPACE:8},log:function(msg){var $log=$("#log");$log.html($log.html()+msg+"<br />");},createSelectbox:function(config){var $selectbox=$("<select />").appendTo(config.container).attr({name:config.name,id:config.id,size:"1"});if(config.multiple)$selectbox.attr("multiple",true);var data=config.data;var selected=false;for(var i=0,len=data.length;i<len;++i){selected=data[i].selected||false;$("<option />").appendTo($selectbox).attr("value",data[i][config.key]).text(data[i][config.value]).attr("selected",selected);}return $selectbox.get(0);},create:function(config){var defaults={name:"",id:"",data:[],multiple:false,key:"value",value:"text",container:$(document),url:"",ajaxData:{}};config=$.extend({},defaults,config||{});if(config.url){return $.getJSON(config.url,config.ajaxData,function(data){delete config.url;delete config.ajaxData;config.data=data;return $sc.create(config);});}config.container=$(config.container);var selectbox=$sc.createSelectbox(config);return new $sc(selectbox,config);},deactivate:function($select){$select=$($select);$select.each(function(){if("SELECT"!=this.tagName.toUpperCase()){return;}var $this=$(this);if(!$this.parent().is(".combo")){return;}});},activate:function($select){$select=$($select);$select.each(function(){if("SELECT"!=this.tagName.toUpperCase()){return;}var $this=$(this);if(!$this.parent().is(".combo")){return;}$this.parent().find("input[type='text']").attr("disabled",false);});},changeOptions:function($select){$select=$($select);$select.each(function(){if("SELECT"!=this.tagName.toUpperCase()){return;}var $this=$(this);var $wrapper=$this.parent();var $input=$wrapper.find("input[type='text']");var $listWrapper=$wrapper.find("ul").parent();$listWrapper.removeClass("visible").addClass("invisible");$wrapper.css("zIndex","0");$listWrapper.css("zIndex","99999");$input.val("");$wrapper.data("sc:optionsChanged","yes");var $selectbox=$this;$selectbox.parent().find("input[type='text']").val($selectbox.find("option:eq(0)").text());$selectbox.parent().data("sc:lastEvent","click");$selectbox.find("option:eq(0)").attr('selected','selected');});},normalizeArray:function(arr){var result=[];for(var i=0,len=arr.length;i<len;++i){if(""==arr[i])continue;result.push(arr[i]);}return result;}});})(jQuery);

//In-Field Label jQuery Plugin | Copyright (c) 2009 Doug Neiner | Dual licensed under the MIT and GPL licenses. @version 0.1
(function($){$.InFieldLabels=function(label,field,options){var base=this;base.$label=$(label);base.$field=$(field);base.$label.data("InFieldLabels",base);base.showing=true;base.init=function(){base.options=$.extend({},$.InFieldLabels.defaultOptions,options);base.$label.css('position','absolute');var fieldPosition=base.$field.position();base.$label.css({'left':fieldPosition.left,'top':fieldPosition.top}).addClass(base.options.labelClass);if(base.$field.val()!=""){base.$label.hide();base.showing=false;};base.$field.focus(function(){base.fadeOnFocus();}).blur(function(){base.checkForEmpty(true);}).bind('keydown.infieldlabel',function(e){base.hideOnChange(e);}).change(function(e){base.checkForEmpty();}).bind('onPropertyChange',function(){base.checkForEmpty();});};base.fadeOnFocus=function(){if(base.showing){base.setOpacity(base.options.fadeOpacity);};};base.setOpacity=function(opacity){base.$label.stop().animate({opacity:opacity},base.options.fadeDuration);base.showing=(opacity>0.0);};base.checkForEmpty=function(blur){if(base.$field.val()==""){base.prepForShow();base.setOpacity(blur?1.0:base.options.fadeOpacity);}else{base.setOpacity(0.0);};};base.prepForShow=function(e){if(!base.showing){base.$label.css({opacity:0.0}).show();base.$field.bind('keydown.infieldlabel',function(e){base.hideOnChange(e);});};};base.hideOnChange=function(e){if((e.keyCode==16)||(e.keyCode==9))return;if(base.showing){base.$label.hide();base.showing=false;};base.$field.unbind('keydown.infieldlabel');};base.init();};$.InFieldLabels.defaultOptions={fadeOpacity:0.5,fadeDuration:300,labelClass:'infield'};$.fn.inFieldLabels=function(options){return this.each(function(){var for_attr=$(this).attr('for');if(!for_attr)return;var $field=$("input#"+for_attr+"[type='text'],"+"input#"+for_attr+"[type='password'],"+"textarea#"+for_attr);if($field.length==0)return;(new $.InFieldLabels(this,$field[0],options));});};})(jQuery);

//hoverIntent by Brian Cherne
(function(a){a.fn.hoverIntent=function(k,j){var l={sensitivity:7,interval:100,timeout:0};l=a.extend(l,j?{over:k,out:j}:k);var n,m,h,d;var e=function(f){n=f.pageX;m=f.pageY};var c=function(g,f){f.hoverIntent_t=clearTimeout(f.hoverIntent_t);if((Math.abs(h-n)+Math.abs(d-m))<l.sensitivity){a(f).unbind("mousemove",e);f.hoverIntent_s=1;return l.over.apply(f,[g])}else{h=n;d=m;f.hoverIntent_t=setTimeout(function(){c(g,f)},l.interval)}};var i=function(g,f){f.hoverIntent_t=clearTimeout(f.hoverIntent_t);f.hoverIntent_s=0;return l.out.apply(f,[g])};var b=function(q){var o=(q.type=="mouseover"?q.fromElement:q.toElement)||q.relatedTarget;while(o&&o!=this){try{o=o.parentNode}catch(q){o=this}}if(o==this){return false}var g=jQuery.extend({},q);var f=this;if(f.hoverIntent_t){f.hoverIntent_t=clearTimeout(f.hoverIntent_t)}if(q.type=="mouseover"){h=g.pageX;d=g.pageY;a(f).bind("mousemove",e);if(f.hoverIntent_s!=1){f.hoverIntent_t=setTimeout(function(){c(g,f)},l.interval)}}else{a(f).unbind("mousemove",e);if(f.hoverIntent_s==1){f.hoverIntent_t=setTimeout(function(){i(g,f)},l.timeout)}}};return this.mouseover(b).mouseout(b)}})(jQuery);

//Superfish v1.4.8 - jQuery menu widget Copyright (c) 2008 Joel Birch licensed under the MIT and GPL licenses
(function(b){b.fn.superfish=function(k){var g=b.fn.superfish,j=g.c,f=b(['<span class="',j.arrowClass,'"> &#187;</span>'].join("")),i=function(){var c=b(this),l=d(c);clearTimeout(l.sfTimer);c.showSuperfishUl().siblings().hideSuperfishUl()},e=function(){var c=b(this),m=d(c),l=g.op;clearTimeout(m.sfTimer);m.sfTimer=setTimeout(function(){l.retainPath=(b.inArray(c[0],l.$path)>-1);c.hideSuperfishUl();if(l.$path.length&&c.parents(["li.",l.hoverClass].join("")).length<1){i.call(l.$path)}},l.delay)},d=function(c){var l=c.parents(["ul.",j.menuClass,":first"].join(""))[0];g.op=g.o[l.serial];return l},h=function(c){c.addClass(j.anchorClass).append(f.clone())};return this.each(function(){var c=this.serial=g.o.length;var m=b.extend({},g.defaults,k);m.$path=b("li."+m.pathClass,this).slice(0,m.pathLevels).each(function(){b(this).addClass([m.hoverClass,j.bcClass].join(" ")).filter("li:has(ul)").removeClass(m.pathClass)});g.o[c]=g.op=m;b("li:has(ul)",this)[(b.fn.hoverIntent&&!m.disableHI)?"hoverIntent":"hover"](i,e).each(function(){if(m.autoArrows){h(b(">a:first-child",this))}}).not("."+j.bcClass).hideSuperfishUl();var l=b("a",this);l.each(function(n){var o=l.eq(n).parents("li");l.eq(n).focus(function(){i.call(o)}).blur(function(){e.call(o)})});m.onInit.call(this)}).each(function(){var c=[j.menuClass];if(g.op.dropShadows&&!(b.browser.msie&&b.browser.version<7)){c.push(j.shadowClass)}b(this).addClass(c.join(" "))})};var a=b.fn.superfish;a.o=[];a.op={};a.IE7fix=function(){var c=a.op;if(b.browser.msie&&b.browser.version>6&&c.dropShadows&&c.animation.opacity!=undefined){this.toggleClass(a.c.shadowClass+"-off")}};a.c={bcClass:"sf-breadcrumb",menuClass:"sf-js-enabled",anchorClass:"sf-with-ul",arrowClass:"sf-sub-indicator",shadowClass:"sf-shadow"};a.defaults={hoverClass:"sfHover",pathClass:"overideThisToUse",pathLevels:1,delay:800,animation:{opacity:"show"},speed:"normal",autoArrows:true,dropShadows:true,disableHI:false,onInit:function(){},onBeforeShow:function(){},onShow:function(){},onHide:function(){}};b.fn.extend({hideSuperfishUl:function(){var e=a.op,d=(e.retainPath===true)?e.$path:"";e.retainPath=false;var c=b(["li.",e.hoverClass].join(""),this).add(this).not(d).removeClass(e.hoverClass).find(">ul").hide().css("visibility","hidden");e.onHide.call(c);return this},showSuperfishUl:function(){var e=a.op,d=a.c.shadowClass+"-off",c=this.addClass(e.hoverClass).find(">ul:hidden").css("visibility","visible");a.IE7fix.call(c);e.onBeforeShow.call(c);c.animate(e.animation,e.speed,function(){a.IE7fix.call(c);e.onShow.call(c)});return this}})})(jQuery);

//Treeview 1.4 - http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ - Copyright (c) 2007 Jörn Zaefferer - Dual licensed under the MIT and GPL licenses
;(function($){$.extend($.fn,{swapClass:function(c1,c2){var c1Elements=this.filter('.'+c1);this.filter('.'+c2).removeClass(c2).addClass(c1);c1Elements.removeClass(c1).addClass(c2);return this;},replaceClass:function(c1,c2){return this.filter('.'+c1).removeClass(c1).addClass(c2).end();},hoverClass:function(className){className=className||"hover";return this.hover(function(){$(this).addClass(className);},function(){$(this).removeClass(className);});},heightToggle:function(animated,callback){animated?this.animate({height:"toggle"},animated,callback):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();if(callback)callback.apply(this,arguments);});},heightHide:function(animated,callback){if(animated){this.animate({height:"hide"},animated,callback);}else{this.hide();if(callback)this.each(callback);}},prepareBranches:function(settings){if(!settings.prerendered){this.filter(":last-child:not(ul)").addClass(CLASSES.last);this.filter((settings.collapsed?"":"."+CLASSES.closed)+":not(."+CLASSES.open+")").find(">ul").hide();}return this.filter(":has(>ul)");},applyClasses:function(settings,toggler){this.filter(":has(>ul):not(:has(>a))").find(">span").click(function(event){toggler.apply($(this).next());}).add($("a",this)).hoverClass();if(!settings.prerendered){this.filter(":has(>ul:hidden)").addClass(CLASSES.expandable).replaceClass(CLASSES.last,CLASSES.lastExpandable);this.not(":has(>ul:hidden)").addClass(CLASSES.collapsable).replaceClass(CLASSES.last,CLASSES.lastCollapsable);this.prepend("<div class=\""+CLASSES.hitarea+"\"/>").find("div."+CLASSES.hitarea).each(function(){var classes="";$.each($(this).parent().attr("class").split(" "),function(){classes+=this+"-hitarea ";});$(this).addClass(classes);});}this.find("div."+CLASSES.hitarea).click(toggler);},treeview:function(settings){settings=$.extend({cookieId:"treeview"},settings);if(settings.add){return this.trigger("add",[settings.add]);}if(settings.toggle){var callback=settings.toggle;settings.toggle=function(){return callback.apply($(this).parent()[0],arguments);};}function treeController(tree,control){function handler(filter){return function(){toggler.apply($("div."+CLASSES.hitarea,tree).filter(function(){return filter?$(this).parent("."+filter).length:true;}));return false;};}$("a:eq(0)",control).click(handler(CLASSES.collapsable));$("a:eq(1)",control).click(handler(CLASSES.expandable));$("a:eq(2)",control).click(handler());}function toggler(){$(this).parent().find(">.hitarea").swapClass(CLASSES.collapsableHitarea,CLASSES.expandableHitarea).swapClass(CLASSES.lastCollapsableHitarea,CLASSES.lastExpandableHitarea).end().swapClass(CLASSES.collapsable,CLASSES.expandable).swapClass(CLASSES.lastCollapsable,CLASSES.lastExpandable).find(">ul").heightToggle(settings.animated,settings.toggle);if(settings.unique){$(this).parent().siblings().find(">.hitarea").replaceClass(CLASSES.collapsableHitarea,CLASSES.expandableHitarea).replaceClass(CLASSES.lastCollapsableHitarea,CLASSES.lastExpandableHitarea).end().replaceClass(CLASSES.collapsable,CLASSES.expandable).replaceClass(CLASSES.lastCollapsable,CLASSES.lastExpandable).find(">ul").heightHide(settings.animated,settings.toggle);}}function serialize(){function binary(arg){return arg?1:0;}var data=[];branches.each(function(i,e){data[i]=$(e).is(":has(>ul:visible)")?1:0;});$.cookie(settings.cookieId,data.join(""));}function deserialize(){var stored=$.cookie(settings.cookieId);if(stored){var data=stored.split("");branches.each(function(i,e){$(e).find(">ul")[parseInt(data[i])?"show":"hide"]();});}}this.addClass("treeview");var branches=this.find("li").prepareBranches(settings);switch(settings.persist){case"cookie":var toggleCallback=settings.toggle;settings.toggle=function(){serialize();if(toggleCallback){toggleCallback.apply(this,arguments);}};deserialize();break;case"location":var current=this.find("a").filter(function(){return this.href.toLowerCase()==location.href.toLowerCase();});if(current.length){current.addClass("selected").parents("ul, li").add(current.next()).show();}break;}branches.applyClasses(settings,toggler);if(settings.control){treeController(this,settings.control);$(settings.control).show();}return this.bind("add",function(event,branches){$(branches).prev().removeClass(CLASSES.last).removeClass(CLASSES.lastCollapsable).removeClass(CLASSES.lastExpandable).find(">.hitarea").removeClass(CLASSES.lastCollapsableHitarea).removeClass(CLASSES.lastExpandableHitarea);$(branches).find("li").andSelf().prepareBranches(settings).applyClasses(settings,toggler);});}});var CLASSES=$.fn.treeview.classes={open:"open",closed:"closed",expandable:"expandable",expandableHitarea:"expandable-hitarea",lastExpandableHitarea:"lastExpandable-hitarea",collapsable:"collapsable",collapsableHitarea:"collapsable-hitarea",lastCollapsableHitarea:"lastCollapsable-hitarea",lastCollapsable:"lastCollapsable",lastExpandable:"lastExpandable",last:"last",hitarea:"hitarea"};$.fn.Treeview=$.fn.treeview;})(jQuery);
 
 //jquery.validationEngine.js - Inline Form Validation Engine 1.6.4
//Copyright(c) 2009, Cedric Dugas - http://www.position-relative.net - Licenced under the MIT Licence
(function($) {
	$.fn.validationEngineLanguage = function() {};
	$.validationEngineLanguage = {
		//italiano
		newLangIta: function() {
			$.validationEngineLanguage.allRules = {"required":{    
						"regex":"none",
						"alertText":"Questo campo è obbligatorio",
						"alertTextCheckboxMultiple":"Scegliere un’opzione",
						"alertTextCheckboxe":"Questa checkbox è obbligatoria"},
					"length":{
						"regex":"none",
						"alertText":"Tra i ",
						"alertText2":" e i ",
						"alertText3":" caratteri richiesti"},
					"maxCheckbox":{
						"regex":"none",
						"alertText":"Numero di scelte consentite superato"},	
					"minCheckbox":{
						"regex":"none",
						"alertText":"Per favore seleziona",
						"alertText2":" opzioni"},	
					"confirm":{
						"regex":"none",
						"alertText":"I due campi devono essere identici"},		
					"telephone":{
						"regex":"/^[0-9\-./\(\)\ ]+$/",
						"alertText":"Numero di telefono non valido"},	
					"email":{
						"regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/",
						"alertText":"Indirizzo mail non valido"},	
					"date":{
                             "regex":"/^[0-9]{1,2}\[/]\[0-9]{1,2}\[/]\[0-9]{4}$/",
                         "alertText":"Data non valida, formato GG/MM/AAAA richiesto"},
					"onlyNumber":{
						"regex":"/^[0-9\ ]+$/",
						"alertText":"Accetta soltanto cifre"},	
					"noSpecialCaracters":{
						"regex":"/^[0-9a-zA-Z]+$/",
						"alertText":"Non accetta caratteri speciali"},	
					"onlyLetter":{
						"regex":"/^[a-zA-ZÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ\ \'’]+$/",
						"alertText":"Accetta soltanto lettere"},
					"ajaxUser":{
						"file":"validateUser.php",
						"alertTextOk":"Questo username è disponibile",	
						"alertTextLoad":"Caricamento, per favore attendere",
						"alertText":"Questo username è già in uso"},	
					"ajaxMail":{
						"file":"validateUser.php",
						"alertText":"Questa mail risulta già iscritta alla newsletter",
						"alertTextOk":"Mail valida",	
						"alertTextLoad":"Caricamento, per favore attendere"},
					"validateRead":{
    					"nname":"validateRead",
    					"alertText":"La presa visione dell'informativa è obbligatoria"},
					"validatePrivacy":{
    					"nname":"validatePrivacy",
    					"alertText":"Il consenso al trattamento dei dati è obbligatorio"},
					"validateCheckbox":{
    					"nname":"validateCheckbox",
    					"alertText":"Per favore seleziona almeno 1 opzione"},
					"validateCheckboxMax3":{
    					"nname":"validateCheckboxMax3",
    					"alertText":"Per favore seleziona da 1 a 3 opzioni"},
					"validateFile":{
    					"nname":"validateFile",
    					"alertText":"Per favore allega un file<br />Sono ammessi solo i formati .doc .pdf .rtf"},
					"validateFile2":{
    					"nname":"validateFile2",
    					"alertText":"Sono ammessi solo i formati .doc .pdf .jpg .zip"}	
				}	
		},
		//inglese
		newLangEng: function() {
			$.validationEngineLanguage.allRules = 	{"required":{ 
						"regex":"none",
						"alertText":"This field is required",
						"alertTextCheckboxMultiple":"Please select an option",
						"alertTextCheckboxe":"This checkbox is required"},
					"length":{
						"regex":"none",
						"alertText":"Between ",
						"alertText2":" and ",
						"alertText3": " characters allowed"},
					"maxCheckbox":{
						"regex":"none",
						"alertText":"Checks allowed Exceeded"},	
					"minCheckbox":{
						"regex":"none",
						"alertText":"Please select ",
						"alertText2":" options"},	
					"confirm":{
						"regex":"none",
						"alertText":"Your field is not matching"},		
					"telephone":{
						"regex":"/^[0-9\-\(\)\ ]+$/",
						"alertText":"Invalid phone number"},	
					"email":{
						"regex":"/^[a-zA-Z0-9_\.\-]+\@([a-zA-Z0-9\-]+\.)+[a-zA-Z0-9]{2,4}$/",
						"alertText":"Invalid email address"},	
					"date":{
                         "regex":"/^[0-9]{1,2}\[/]\[0-9]{1,2}\[/]\[0-9]{4}$/",
                         "alertText":"Invalid date, must be in DD/MM/YYYY format"},
					"onlyNumber":{
						"regex":"/^[0-9\ ]+$/",
						"alertText":"Numbers only"},	
					"noSpecialCaracters":{
						"regex":"/^[0-9a-zA-Z]+$/",
						"alertText":"No special caracters allowed"},	
					"ajaxUser":{
						"file":"validateUser.php",
						"extraData":"name=eric",
						"alertTextOk":"This user is available",	
						"alertTextLoad":"Loading, please wait",
						"alertText":"This user is already taken"},	
					"ajaxMail":{
						"file":"validateUser.php",
						"alertText":"This email is already subscribed to the newsletter",
						"alertTextOk":"Valid mail",	
						"alertTextLoad":"Loading, please wait"},		
					"onlyLetter":{
						"regex":"/^[a-zA-Z\ \']+$/",
						"alertText":"Letters only"},
					"validateRead":{
    					"nname":"validateRead",
    					"alertText":"This checkbox is required"},
					"validatePrivacy":{
    					"nname":"validatePrivacy",
    					"alertText":"Consent to the processing of personal data is required"},
					"validateCheckbox":{
    					"nname":"validateCheckbox",
    					"alertText":"Please select at least 1 option"},
					"validateCheckboxMax3":{
    					"nname":"validateCheckboxMax3",
    					"alertText":"Please select between 1 and 3 options"},	
					"validateFile":{
    					"nname":"validateFile",
    					"alertText":"Please attach a file<br />Only .doc .pdf .rtf accepted"},
					"validateFile2":{
    					"nname":"validateFile2",
    					"alertText":"Only .doc .pdf .jpg .zip accepted"}
					}	
		}
	}
})(jQuery);
//funzione specifica per validare il campo privacy
function validatePrivacy(){
	if($("#checkPrivacy input:checked").val() != 1){
		return false;
	}else{
		return true;
	}
}
//funzione specifica per validare il campo presa visione
function validateRead(){
	if($("#checkRead input:checked").val() != 1){
		return false;
	}else{
		return true;
	}
}
//funzione specifica per validare le checkbox
function validateCheckbox(caller){
	var parent = $(caller).parent('.checkCheckbox');
	if($("input:checked", parent).length < 1){
		return false;
	}else{
		return true;
	}
}
//funzione specifica per validare le checkbox (almeno 1 e non più di 3)
function validateCheckboxMax3(caller){
	var parent = $(caller).parent('.checkCheckbox');
	if(($("input:checked", parent).length < 1) || ($("input:checked", parent).length > 3)){
		return false;
	}else{
		return true;
	}
}
//funzione specifica per validare l'input di tipo file (con controllo sull'estensione)
function validateFile(caller){
	var extension = $(caller).val().slice(-4);
	if(extension != ".doc" && extension != ".pdf" && extension != ".rtf") {
		return false;
	}else{
		return true;
	}
}
function validateFile2(caller){
	var extension = $(caller).val().slice(-4);
	if(extension != ".doc" && extension != ".pdf" && extension != ".zip" && extension != ".jpg") {
		return false;
	}else{
		return true;
	}
}

/*
 * Inline Form Validation Engine 1.7, jQuery plugin
 * 
 * Copyright(c) 2010, Cedric Dugas
 * http://www.position-relative.net
 *	
 * Form validation engine allowing custom regex rules to be added.
 * Thanks to Francois Duquette and Teddy Limousin 
 * and everyone helping me find bugs on the forum
 * Licenced under the MIT Licence
 */
 
(function($) {
	
	$.fn.validationEngine = function(settings) {
		
	if($.validationEngineLanguage){				// IS THERE A LANGUAGE LOCALISATION ?
		allRules = $.validationEngineLanguage.allRules;
	}else{
		$.validationEngine.debug("Validation engine rules are not loaded check your external file");
	}
 	settings = jQuery.extend({
		allrules:allRules,
		validationEventTriggers:"focusout",					
		inlineValidation: true,	
		returnIsValid:false,
		liveEvent:false,
		openDebug: true,
		unbindEngine:true,
		containerOverflow:false,
		containerOverflowDOM:"",
		ajaxSubmit: false,
		scroll:true,
		promptPosition: "topRight",	// OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight
		success : false,
		beforeSuccess :  function() {},
		failure : function() {}
	}, settings);	
	$.validationEngine.settings = settings;
	$.validationEngine.ajaxValidArray = new Array();	// ARRAY FOR AJAX: VALIDATION MEMORY 
	
	if(settings.inlineValidation == true){ 		// Validating Inline ?
		if(!settings.returnIsValid){					// NEEDED FOR THE SETTING returnIsValid
			allowReturnIsvalid = false;
			if(settings.liveEvent){						// LIVE event, vast performance improvement over BIND
				$(this).find("[class*=validate]").live(settings.validationEventTriggers, function(caller){ 
					if($(caller).attr("type") != "checkbox") _inlinEvent(this);
				})
				$(this).find("[class*=validate][type=checkbox]").live("click", function(caller){ _inlinEvent(this); })
			}else{
				$(this).find("[class*=validate]").not("[type=checkbox]").bind(settings.validationEventTriggers, function(caller){ _inlinEvent(this); })
				$(this).find("[class*=validate][type=checkbox]").bind("click", function(caller){ _inlinEvent(this); })
			}
			firstvalid = false;
		}
			function _inlinEvent(caller){
				$.validationEngine.settings = settings;
				if($.validationEngine.intercept == false || !$.validationEngine.intercept){		// STOP INLINE VALIDATION THIS TIME ONLY
					$.validationEngine.onSubmitValid=false;
					$.validationEngine.loadValidation(caller); 
				}else{
					$.validationEngine.intercept = false;
				}
			}
	}
	if (settings.returnIsValid){		// Do validation and return true or false, it bypass everything;
		if ($.validationEngine.submitValidation(this,settings)){
			return false;
		}else{
			return true;
		}
	}
	$(this).bind("submit", function(caller){   // ON FORM SUBMIT, CONTROL AJAX FUNCTION IF SPECIFIED ON DOCUMENT READY
		$.validationEngine.onSubmitValid = true;
		$.validationEngine.settings = settings;
		if($.validationEngine.submitValidation(this,settings) == false){
			if($.validationEngine.submitForm(this,settings) == true) return false;
		}else{
			settings.failure && settings.failure(); 
			return false;
		}		
	})
	$(".formError").live("click",function(){	 // REMOVE BOX ON CLICK
		$(this).fadeOut(150,function(){		$(this).remove()	}) 
	})
};	
$.validationEngine = {
	defaultSetting : function(caller) {		// NOT GENERALLY USED, NEEDED FOR THE API, DO NOT TOUCH
		if($.validationEngineLanguage){				
			allRules = $.validationEngineLanguage.allRules;
		}else{
			$.validationEngine.debug("Validation engine rules are not loaded check your external file");
		}	
		settings = {
			allrules:allRules,
			validationEventTriggers:"blur",					
			inlineValidation: true,	
			containerOverflow:false,
			containerOverflowDOM:"",
			returnIsValid:false,
			scroll:true,
			unbindEngine:true,
			ajaxSubmit: false,
			promptPosition: "topRight",	// OPENNING BOX POSITION, IMPLEMENTED: topLeft, topRight, bottomLeft, centerRight, bottomRight
			success : false,
			failure : function() {}
		}	
		$.validationEngine.settings = settings;
	},
	loadValidation : function(caller) {		// GET VALIDATIONS TO BE EXECUTED
		if(!$.validationEngine.settings) $.validationEngine.defaultSetting()
		rulesParsing = $(caller).attr('class');
		rulesRegExp = /\[(.*)\]/;
		getRules = rulesRegExp.exec(rulesParsing);
		if(getRules == null) return false;
		str = getRules[1];
		pattern = /\[|,|\]/;
		result= str.split(pattern);	
		var validateCalll = $.validationEngine.validateCall(caller,result)
		return validateCalll;
	},
	validateCall : function(caller,rules) {	// EXECUTE VALIDATION REQUIRED BY THE USER FOR THIS FIELD
		var promptText =""	
		
		if(!$(caller).attr("id")) $.validationEngine.debug("This field have no ID attribut( name & class displayed): "+$(caller).attr("name")+" "+$(caller).attr("class"))

		caller = caller;
		ajaxValidate = false;
		var callerName = $(caller).attr("name");
		$.validationEngine.isError = false;
		$.validationEngine.showTriangle = true;
		callerType = $(caller).attr("type");

		for (i=0; i<rules.length;i++){
			switch (rules[i]){
			case "optional": 
				if(!$(caller).val()){
					$.validationEngine.closePrompt(caller);
					return $.validationEngine.isError;
				}
			break;
			case "required": 
				_required(caller,rules);
			break;
			case "custom": 
				 _customRegex(caller,rules,i);
			break;
			case "exemptString": 
				 _exemptString(caller,rules,i);
			break;
			case "ajax": 
				if(!$.validationEngine.onSubmitValid) _ajax(caller,rules,i);	
			break;
			case "length": 
				 _length(caller,rules,i);
			break;
			case "maxCheckbox": 
				_maxCheckbox(caller,rules,i);
			 	groupname = $(caller).attr("name");
			 	caller = $("input[name='"+groupname+"']");
			break;
			case "minCheckbox": 
				_minCheckbox(caller,rules,i);
				groupname = $(caller).attr("name");
			 	caller = $("input[name='"+groupname+"']");
			break;
			case "confirm": 
				 _confirm(caller,rules,i);
			break;
			case "funcCall": 
		     	_funcCall(caller,rules,i);
			break;
			default :;
			};
		};
		radioHack();
		if ($.validationEngine.isError == true){
			var linkTofieldText = "." +$.validationEngine.linkTofield(caller);
			if(linkTofieldText != "."){
				if(!$(linkTofieldText)[0]){
					$.validationEngine.buildPrompt(caller,promptText,"error")
				}else{	
					$.validationEngine.updatePromptText(caller,promptText);
				}	
			}else{
				$.validationEngine.updatePromptText(caller,promptText);
			}
		}else{
			$.validationEngine.closePrompt(caller);
		}			
		/* UNFORTUNATE RADIO AND CHECKBOX GROUP HACKS */
		/* As my validation is looping input with id's we need a hack for my validation to understand to group these inputs */
		function radioHack(){
	      if($("input[name='"+callerName+"']").size()> 1 && (callerType == "radio" || callerType == "checkbox")) {        // Hack for radio/checkbox group button, the validation go the first radio/checkbox of the group
	          caller = $("input[name='"+callerName+"'][type!=hidden]:first");     
	          $.validationEngine.showTriangle = false;
	      }      
	    }
		/* VALIDATION FUNCTIONS */
		function _required(caller,rules){   // VALIDATE BLANK FIELD
			callerType = $(caller).attr("type");
			if (callerType == "text" || callerType == "password" || callerType == "textarea"){
								
				if(!$(caller).val()){
					$.validationEngine.isError = true;
					promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}	
			}	
			if (callerType == "radio" || callerType == "checkbox" ){
				callerName = $(caller).attr("name");
		
				if($("input[name='"+callerName+"']:checked").size() == 0) {
					$.validationEngine.isError = true;
					if($("input[name='"+callerName+"']").size() ==1) {
						promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxe+"<br />"; 
					}else{
						 promptText += $.validationEngine.settings.allrules[rules[i]].alertTextCheckboxMultiple+"<br />";
					}	
				}
			}	
			if (callerType == "select-one") { // added by paul@kinetek.net for select boxes, Thank you		
				if(!$(caller).val()) {
					$.validationEngine.isError = true;
					promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}
			}
			if (callerType == "select-multiple") { // added by paul@kinetek.net for select boxes, Thank you	
				if(!$(caller).find("option:selected").val()) {
					$.validationEngine.isError = true;
					promptText += $.validationEngine.settings.allrules[rules[i]].alertText+"<br />";
				}
			}
		}
		function _customRegex(caller,rules,position){		 // VALIDATE REGEX RULES
			customRule = rules[position+1];
			pattern = eval($.validationEngine.settings.allrules[customRule].regex);
			
			if(!pattern.test($(caller).attr('value'))){
				$.validationEngine.isError = true;
				promptText += $.validationEngine.settings.allrules[customRule].alertText+"<br />";
			}
		}
		function _exemptString(caller,rules,position){		 // VALIDATE REGEX RULES
			customString = rules[position+1];
			if(customString == $(caller).attr('value')){
				$.validationEngine.isError = true;
				promptText += $.validationEngine.settings.allrules['required'].alertText+"<br />";
			}
		}
		
		function _funcCall(caller,rules,position){  		// VALIDATE CUSTOM FUNCTIONS OUTSIDE OF THE ENGINE SCOPE
			customRule = rules[position+1];
			funce = $.validationEngine.settings.allrules[customRule].nname;
			
			var fn = window[funce];
			if (typeof(fn) === 'function'){
				var fn_result = fn(caller);
				if(!fn_result){
					$.validationEngine.isError = true;
				}
				
				promptText += $.validationEngine.settings.allrules[customRule].alertText+"<br />";
			}
		}
		function _ajax(caller,rules,position){				 // VALIDATE AJAX RULES
			
			customAjaxRule = rules[position+1];
			postfile = $.validationEngine.settings.allrules[customAjaxRule].file;
			fieldValue = $(caller).val();
			ajaxCaller = caller;
			fieldId = $(caller).attr("id");
			ajaxValidate = true;
			ajaxisError = $.validationEngine.isError;
			
			if($.validationEngine.settings.allrules[customAjaxRule].extraData){
				extraData = $.validationEngine.settings.allrules[customAjaxRule].extraData;
			}else{
				extraData = "";
			}
			/* AJAX VALIDATION HAS ITS OWN UPDATE AND BUILD UNLIKE OTHER RULES */	
			if(!ajaxisError){
				$.ajax({
				   	type: "POST",
				   	url: postfile,
				   	async: true,
				   	data: "validateValue="+fieldValue+"&validateId="+fieldId+"&validateError="+customAjaxRule+"&extraData="+extraData,
				   	beforeSend: function(){		// BUILD A LOADING PROMPT IF LOAD TEXT EXIST		   			
				   		if($.validationEngine.settings.allrules[customAjaxRule].alertTextLoad){
				   		
				   			if(!$("div."+fieldId+"formError")[0]){				   				
	 			 				return $.validationEngine.buildPrompt(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");
	 			 			}else{
	 			 				$.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextLoad,"load");
	 			 			}
			   			}
			  	 	},
			  	 	error: function(data,transport){ $.validationEngine.debug("error in the ajax: "+data.status+" "+transport) },
					success: function(data){					// GET SUCCESS DATA RETURN JSON
						data = eval( "("+data+")");				// GET JSON DATA FROM PHP AND PARSE IT
						ajaxisError = data.jsonValidateReturn[2];
						customAjaxRule = data.jsonValidateReturn[1];
						ajaxCaller = $("#"+data.jsonValidateReturn[0])[0];
						fieldId = ajaxCaller;
						ajaxErrorLength = $.validationEngine.ajaxValidArray.length;
						existInarray = false;
						
			 			 if(ajaxisError == "false"){			// DATA FALSE UPDATE PROMPT WITH ERROR;
			 			 	
			 			 	_checkInArray(false)				// Check if ajax validation alreay used on this field
			 			 	
			 			 	if(!existInarray){		 			// Add ajax error to stop submit		 		
				 			 	$.validationEngine.ajaxValidArray[ajaxErrorLength] =  new Array(2);
				 			 	$.validationEngine.ajaxValidArray[ajaxErrorLength][0] = fieldId;
				 			 	$.validationEngine.ajaxValidArray[ajaxErrorLength][1] = false;
				 			 	existInarray = false;
			 			 	}
				
			 			 	$.validationEngine.ajaxValid = false;
							promptText += $.validationEngine.settings.allrules[customAjaxRule].alertText+"<br />";
							$.validationEngine.updatePromptText(ajaxCaller,promptText,"",true);				
						 }else{	 
						 	_checkInArray(true);
						 	$.validationEngine.ajaxValid = true; 			
						 	if(!customAjaxRule)	{$.validationEngine.debug("wrong ajax response, are you on a server or in xampp? if not delete de ajax[ajaxUser] validating rule from your form ")}		   
						 	if($.validationEngine.settings.allrules[customAjaxRule].alertTextOk){	// NO OK TEXT MEAN CLOSE PROMPT	 			
	 			 				 				$.validationEngine.updatePromptText(ajaxCaller,$.validationEngine.settings.allrules[customAjaxRule].alertTextOk,"pass",true);
 			 				}else{
				 			 	ajaxValidate = false;		 	
				 			 	$.validationEngine.closePrompt(ajaxCaller);
 			 				}		
			 			 }
			 			function  _checkInArray(validate){
			 				for(x=0;x<ajaxErrorLength;x++){
			 			 		if($.validationEngine.ajaxValidArray[x][0] == fieldId){
			 			 			$.validationEngine.ajaxValidArray[x][1] = validate;
			 			 			existInarray = true;
			 			 		
			 			 		}
			 			 	}
			 			}
			 		}				
				});
			}
		}
		function _confirm(caller,rules,position){		 // VALIDATE FIELD MATCH
			confirmField = rules[position+1];
			
			if($(caller).attr('value') != $("#"+confirmField).attr('value')){
				$.validationEngine.isError = true;
				promptText += $.validationEngine.settings.allrules["confirm"].alertText+"<br />";
			}
		}
		function _length(caller,rules,position){    	  // VALIDATE LENGTH
		
			startLength = eval(rules[position+1]);
			endLength = eval(rules[position+2]);
			feildLength = $(caller).attr('value').length;

			if(feildLength<startLength || feildLength>endLength){
				$.validationEngine.isError = true;
				promptText += $.validationEngine.settings.allrules["length"].alertText+startLength+$.validationEngine.settings.allrules["length"].alertText2+endLength+$.validationEngine.settings.allrules["length"].alertText3+"<br />"
			}
		}
		function _maxCheckbox(caller,rules,position){  	  // VALIDATE CHECKBOX NUMBER
		
			nbCheck = eval(rules[position+1]);
			groupname = $(caller).attr("name");
			groupSize = $("input[name='"+groupname+"']:checked").size();
			if(groupSize > nbCheck){	
				$.validationEngine.showTriangle = false;
				$.validationEngine.isError = true;
				promptText += $.validationEngine.settings.allrules["maxCheckbox"].alertText+"<br />";
			}
		}
		function _minCheckbox(caller,rules,position){  	  // VALIDATE CHECKBOX NUMBER
		
			nbCheck = eval(rules[position+1]);
			groupname = $(caller).attr("name");
			groupSize = $("input[name='"+groupname+"']:checked").size();
			if(groupSize < nbCheck){	
			
				$.validationEngine.isError = true;
				$.validationEngine.showTriangle = false;
				promptText += $.validationEngine.settings.allrules["minCheckbox"].alertText+" "+nbCheck+" "+$.validationEngine.settings.allrules["minCheckbox"].alertText2+"<br />";
			}
		}
		return ($.validationEngine.isError) ? $.validationEngine.isError : false;
	},
	submitForm : function(caller){
		if($.validationEngine.settings.ajaxSubmit){		
			if($.validationEngine.settings.ajaxSubmitExtraData){
				extraData = $.validationEngine.settings.ajaxSubmitExtraData;
			}else{
				extraData = "";
			}
			$.ajax({
			   	type: "POST",
			   	url: $.validationEngine.settings.ajaxSubmitFile,
			   	async: true,
			   	data: $(caller).serialize()+"&"+extraData,
			   	error: function(data,transport){ $.validationEngine.debug("error in the ajax: "+data.status+" "+transport) },
			   	success: function(data){
			   		if(data == "true"){			// EVERYTING IS FINE, SHOW SUCCESS MESSAGE
			   			$(caller).css("opacity",1)
			   			$(caller).animate({opacity: 0, height: 0}, function(){
			   				$(caller).css("display","none");
			   				$(caller).before("<div class='ajaxSubmit'>"+$.validationEngine.settings.ajaxSubmitMessage+"</div>");
			   				$.validationEngine.closePrompt(".formError",true); 	
			   				$(".ajaxSubmit").show("slow");
			   				if ($.validationEngine.settings.success){	// AJAX SUCCESS, STOP THE LOCATION UPDATE
								$.validationEngine.settings.success && $.validationEngine.settings.success(); 
								return false;
							}
			   			})
		   			}else{						// HOUSTON WE GOT A PROBLEM (SOMETING IS NOT VALIDATING)
			   			data = eval( "("+data+")");	
			   			if(!data.jsonValidateReturn){
			   				 $.validationEngine.debug("you are not going into the success fonction and jsonValidateReturn return nothing");
			   			}
			   			errorNumber = data.jsonValidateReturn.length	
			   			for(index=0; index<errorNumber; index++){	
			   				fieldId = data.jsonValidateReturn[index][0];
			   				promptError = data.jsonValidateReturn[index][1];
			   				type = data.jsonValidateReturn[index][2];
			   				$.validationEngine.buildPrompt(fieldId,promptError,type);
		   				}
	   				}
   				}
			})	
			return true;
		}
		// LOOK FOR BEFORE SUCCESS METHOD		
			if(!$.validationEngine.settings.beforeSuccess()){
				if ($.validationEngine.settings.success){	// AJAX SUCCESS, STOP THE LOCATION UPDATE
					if($.validationEngine.settings.unbindEngine){ $(caller).unbind("submit") }
					$.validationEngine.settings.success && $.validationEngine.settings.success(); 
					return true;
				}
			}else{
				return true;
			} 
		return false;
	},
	buildPrompt : function(caller,promptText,type,ajaxed) {			// ERROR PROMPT CREATION AND DISPLAY WHEN AN ERROR OCCUR
		if(!$.validationEngine.settings){
			$.validationEngine.defaultSetting()
		}
		deleteItself = "." + $(caller).attr("id") + "formError"
	
		if($(deleteItself)[0]){
			$(deleteItself).stop();
			$(deleteItself).remove();
		}
		var divFormError = document.createElement('div');
		var formErrorContent = document.createElement('div');
		linkTofield = $.validationEngine.linkTofield(caller)
		$(divFormError).addClass("formError")
		
		if(type == "pass") $(divFormError).addClass("greenPopup")
		if(type == "load") $(divFormError).addClass("blackPopup")
		if(ajaxed) $(divFormError).addClass("ajaxed")
		
		$(divFormError).addClass(linkTofield);
		$(formErrorContent).addClass("formErrorContent");
		
		if($.validationEngine.settings.containerOverflow){		// Is the form contained in an overflown container?
			$(caller).before(divFormError);
		}else{
			$("body").append(divFormError);
		}
		
		$(divFormError).append(formErrorContent);
			
		if($.validationEngine.showTriangle != false){		// NO TRIANGLE ON MAX CHECKBOX AND RADIO
			var arrow = document.createElement('div');
			$(arrow).addClass("formErrorArrow");
			$(divFormError).append(arrow);
			if($.validationEngine.settings.promptPosition == "bottomLeft" || $.validationEngine.settings.promptPosition == "bottomRight"){
			$(arrow).addClass("formErrorArrowBottom")
			$(arrow).html('<div class="line1"><!-- --></div><div class="line2"><!-- --></div><div class="line3"><!-- --></div><div class="line4"><!-- --></div><div class="line5"><!-- --></div><div class="line6"><!-- --></div><div class="line7"><!-- --></div><div class="line8"><!-- --></div><div class="line9"><!-- --></div><div class="line10"><!-- --></div>');
		}
			if($.validationEngine.settings.promptPosition == "topLeft" || $.validationEngine.settings.promptPosition == "topRight"){
				$(divFormError).append(arrow);
				$(arrow).html('<div class="line10"><!-- --></div><div class="line9"><!-- --></div><div class="line8"><!-- --></div><div class="line7"><!-- --></div><div class="line6"><!-- --></div><div class="line5"><!-- --></div><div class="line4"><!-- --></div><div class="line3"><!-- --></div><div class="line2"><!-- --></div><div class="line1"><!-- --></div>');
			}
		}
		$(formErrorContent).html(promptText)
		
		var calculatedPosition = $.validationEngine.calculatePosition(caller,promptText,type,ajaxed,divFormError)
		
		calculatedPosition.callerTopPosition +="px";
		calculatedPosition.callerleftPosition +="px";
		calculatedPosition.marginTopSize +="px"
		$(divFormError).css({
			"top":calculatedPosition.callerTopPosition,
			"left":calculatedPosition.callerleftPosition,
			"marginTop":calculatedPosition.marginTopSize,
			"opacity":0
		})
		return $(divFormError).animate({"opacity":0.87},function(){return true;});	
	},
	updatePromptText : function(caller,promptText,type,ajaxed) {	// UPDATE TEXT ERROR IF AN ERROR IS ALREADY DISPLAYED
		
		linkTofield = $.validationEngine.linkTofield(caller);
		var updateThisPrompt =  "."+linkTofield;
		
		if(type == "pass") { $(updateThisPrompt).addClass("greenPopup") }else{ $(updateThisPrompt).removeClass("greenPopup")};
		if(type == "load") { $(updateThisPrompt).addClass("blackPopup") }else{ $(updateThisPrompt).removeClass("blackPopup")};
		if(ajaxed) { $(updateThisPrompt).addClass("ajaxed") }else{ $(updateThisPrompt).removeClass("ajaxed")};
	
		$(updateThisPrompt).find(".formErrorContent").html(promptText);
		
		var calculatedPosition = $.validationEngine.calculatePosition(caller,promptText,type,ajaxed,updateThisPrompt)
		
		calculatedPosition.callerTopPosition +="px";
		calculatedPosition.callerleftPosition +="px";
		calculatedPosition.marginTopSize +="px"
		$(updateThisPrompt).animate({ "top":calculatedPosition.callerTopPosition,"marginTop":calculatedPosition.marginTopSize });
	},
	calculatePosition : function(caller,promptText,type,ajaxed,divFormError){
		
		if($.validationEngine.settings.containerOverflow){		// Is the form contained in an overflown container?
			callerTopPosition = 0;
			callerleftPosition = 0;
			callerWidth =  $(caller).width();
			inputHeight = $(divFormError).height();					// compasation for the triangle
			var marginTopSize = "-"+inputHeight;
		}else{
			callerTopPosition = $(caller).offset().top;
			callerleftPosition = $(caller).offset().left;
			callerWidth =  $(caller).width();
			inputHeight = $(divFormError).height();
			var marginTopSize = 0;
		}
		
		/* POSITIONNING */
		if($.validationEngine.settings.promptPosition == "topRight"){ 
			if($.validationEngine.settings.containerOverflow){		// Is the form contained in an overflown container?
				callerleftPosition += callerWidth -30;
			}else{
				callerleftPosition +=  callerWidth -30; 
				callerTopPosition += -inputHeight-5; 
			}
		}
		if($.validationEngine.settings.promptPosition == "topLeft"){ callerTopPosition += -inputHeight -10; }
		
		if($.validationEngine.settings.promptPosition == "centerRight"){ callerleftPosition +=  callerWidth +13; }
		
		if($.validationEngine.settings.promptPosition == "bottomLeft"){
			callerHeight =  $(caller).height();
			callerTopPosition = callerTopPosition + callerHeight + 15;
		}
		if($.validationEngine.settings.promptPosition == "bottomRight"){
			callerHeight =  $(caller).height();
			callerleftPosition +=  callerWidth -30;
			callerTopPosition +=  callerHeight +5;
		}
		return {
			"callerTopPosition":callerTopPosition,
			"callerleftPosition":callerleftPosition,
			"marginTopSize":marginTopSize
		}
	},
	linkTofield : function(caller){
		var linkTofield = $(caller).attr("id") + "formError";
		linkTofield = linkTofield.replace(/\[/g,""); 
		linkTofield = linkTofield.replace(/\]/g,"");
		return linkTofield;
	},
	closePrompt : function(caller,outside) {						// CLOSE PROMPT WHEN ERROR CORRECTED
		if(!$.validationEngine.settings){
			$.validationEngine.defaultSetting()
		}
		if(outside){
			$(caller).fadeTo("fast",0,function(){
				$(caller).remove();
			});
			return false;
		}
		if(typeof(ajaxValidate)=='undefined'){ajaxValidate = false}
		if(!ajaxValidate){
			linkTofield = $.validationEngine.linkTofield(caller);
			closingPrompt = "."+linkTofield;
			$(closingPrompt).fadeTo("fast",0,function(){
				$(closingPrompt).remove();
			});
		}
	},
	debug : function(error) {
		if(!$.validationEngine.settings.openDebug) return false;
		if(!$("#debugMode")[0]){
			$("body").append("<div id='debugMode'><div class='debugError'><strong>This is a debug mode, you got a problem with your form, it will try to help you, refresh when you think you nailed down the problem</strong></div></div>");
		}
		$(".debugError").append("<div class='debugerror'>"+error+"</div>");
	},			
	submitValidation : function(caller) {					// FORM SUBMIT VALIDATION LOOPING INLINE VALIDATION
		var stopForm = false;
		$.validationEngine.ajaxValid = true;
		var toValidateSize = $(caller).find("[class*=validate]").size();
		
		$(caller).find("[class*=validate]").each(function(){
			linkTofield = $.validationEngine.linkTofield(this);
			
			if(!$("."+linkTofield).hasClass("ajaxed")){	// DO NOT UPDATE ALREADY AJAXED FIELDS (only happen if no normal errors, don't worry)
				var validationPass = $.validationEngine.loadValidation(this);
				return(validationPass) ? stopForm = true : "";					
			};
		});
		ajaxErrorLength = $.validationEngine.ajaxValidArray.length;		// LOOK IF SOME AJAX IS NOT VALIDATE
		for(x=0;x<ajaxErrorLength;x++){
	 		if($.validationEngine.ajaxValidArray[x][1] == false) $.validationEngine.ajaxValid = false;
 		}
		if(stopForm || !$.validationEngine.ajaxValid){		// GET IF THERE IS AN ERROR OR NOT FROM THIS VALIDATION FUNCTIONS
			if($.validationEngine.settings.scroll){
				if(!$.validationEngine.settings.containerOverflow){
					var destination = $(".formError:not('.greenPopup'):first").offset().top;
					$(".formError:not('.greenPopup')").each(function(){
						testDestination = $(this).offset().top;
						if(destination>testDestination) destination = $(this).offset().top;
					})
					$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1100);
				}else{
					var destination = $(".formError:not('.greenPopup'):first").offset().top;
					var scrollContainerScroll = $($.validationEngine.settings.containerOverflowDOM).scrollTop();
					var scrollContainerPos = - parseInt($($.validationEngine.settings.containerOverflowDOM).offset().top);
					var destination = scrollContainerScroll + destination + scrollContainerPos -5
					var scrollContainer = $.validationEngine.settings.containerOverflowDOM+":not(:animated)"
					
					$(scrollContainer).animate({ scrollTop: destination}, 1100);
				}
			}
			return true;
		}else{
			return false;
		}
	}
}
})(jQuery);

// jquery.innerfade.js | Author: Torsten Baldes http://medienfreunde.com |based on the work of Matt Oakes and Ralf S. Engelschall
(function($){$.fn.innerfade=function(options){return this.each(function(){$.innerfade(this,options);});};$.innerfade=function(container,options){var settings={'animationtype':'fade','speed':'normal','type':'sequence','timeout':2000,'containerheight':'auto','runningclass':'innerfade','children':null};if(options)
$.extend(settings,options);if(settings.children===null)
var elements=$(container).children();else
var elements=$(container).children(settings.children);if(elements.length>1){$(container).css('position','absolute').css('height',settings.containerheight).addClass(settings.runningclass);for(var i=0;i<elements.length;i++){$(elements[i]).css('z-index',String(elements.length-i)).css('position','absolute').hide();};if(settings.type=="sequence"){setTimeout(function(){$.innerfade.next(elements,settings,1,0);},settings.timeout);$(elements[0]).show();}else if(settings.type=="random"){var last=Math.floor(Math.random()*(elements.length));setTimeout(function(){do{current=Math.floor(Math.random()*(elements.length));}while(last==current);$.innerfade.next(elements,settings,current,last);},settings.timeout);$(elements[last]).show();}else if(settings.type=='random_start'){settings.type='sequence';var current=Math.floor(Math.random()*(elements.length));setTimeout(function(){$.innerfade.next(elements,settings,(current+1)%elements.length,current);},settings.timeout);$(elements[current]).show();}else{alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');}}};$.innerfade.next=function(elements,settings,current,last){if(settings.animationtype=='slide'){$(elements[last]).slideUp(settings.speed);$(elements[current]).slideDown(settings.speed);}else if(settings.animationtype=='fade'){$(elements[last]).fadeOut(settings.speed);$(elements[current]).fadeIn(settings.speed,function(){removeFilter($(this)[0]);});}else
alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');if(settings.type=="sequence"){if((current+1)<elements.length){current=current+1;last=current-1;}else{current=0;last=elements.length-1;}}else if(settings.type=="random"){last=current;while(current==last)
current=Math.floor(Math.random()*elements.length);}else
alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');setTimeout((function(){$.innerfade.next(elements,settings,current,last);}),settings.timeout);};})(jQuery);function removeFilter(element){if(element.style.removeAttribute){element.style.removeAttribute('filter');}}

//imposta target _blank ai link esterni
linkext = function(){$("a.ext").each(function(){$(this).attr({target:"_blank",title:$(this).attr("title")+" (link esterno, si apre in una nuova finestra)"})})};

//overlay privacy, poi, artigiani e credits (richiede jquery.tools)
overlay = function(){
	$('#inf_privacy, #inf_privacy2').wrapInner('<div class="scroll" />');
	$("a.privacy, p.navigatore a, a.credits., .artigiani a").overlay({
		top: 'center',
		expose: { 
			color: '#000', 
			loadSpeed: 200, 
			opacity: 0.4 
		}
	});
	if ($('#JobsubmissionAddForm').length){
	  $('body').append('<div id="popup_profile"><div class="contentWrap scroll"></div></div>')
	  $("a.info").overlay({
		top: 'center',
		expose: { 
			color: '#000', 
			loadSpeed: 200, 
			opacity: 0.4 
		},
		onBeforeLoad: function() {
			var wrap = this.getContent().find(".contentWrap");
			wrap.load(this.getTrigger().attr("href"));
		}
	  });
	}
}
doppio_overlay = function(){
  if ($('#doppio_volantino').length){
	$('body').append('<div id="loading"><div class="overlay_doppio"></div></div>');
	$("#loading .overlay_doppio").css('opacity','0.4');

	$("a.doppio_volantino").click(function() {
		$("#loading, #doppio_volantino").fadeIn(300);
		return false;
	});
	$("#doppio_volantino div.close").click(function() {
		$("#loading, #doppio_volantino").fadeOut(300);
	});
  }
}

//overlay volantino (richiede jquery.tools)
sfoglia = function(){
  if ($('a.sfoglia').length){
	$("body").append('<div id="volantino"></div>');
	$("a.sfoglia").overlay({
		top: 'center',
		expose: { 
			color: '#000', 
			loadSpeed: 200, 
			opacity: 0.4
		},
		onBeforeLoad: function() {
			//var wrap = this.getContent().find(".contentWrap");
			var src = this.getTrigger().attr("href")
			this.getContent().append('<iframe class="contentWrap" width="100%" marginwidth="0" height="100%" marginheight="0" scrolling="auto" frameborder="0" src="'+src+'"></iframe>');
		},
		onClose: function() {
			this.getContent().find(".contentWrap").remove();
		}
	});
  }
}
//overlay automatico popup punto vendita (richiede jquery.tools)
overlay_pv = function(){
	if ($('#popup-pv').length){
	  $('#popup-pv').appendTo('body').wrapInner('<div class="scroll" />');
	  $("a.popup-pv").overlay({
		top: 'center',
		left: 'center',
		expose: { 
			color: '#000', 
			loadSpeed: 200, 
			opacity: 0.4 
		},
		onClose: function() {
		  if($("#jquery_jplayer_1").length){
			$("#jquery_jplayer_1").jPlayer("pause");
		  }
		}
	  }).trigger('click');
	}
}

//stile select e label all'interno del campo, validazione form (richiede inFieldLabels e jquery.validationEngine)
formFunctions = function(){
  //controllo se il browser è quello schifo di ie6
  if ((window.XMLHttpRequest)){var noIe6=true}
  //lingua
  if ($("body.it-it").length){
	  $.validationEngineLanguage.newLangIta();
	  var txtSelect = "Seleziona tutti";
	  var txtDeselect = "Deseleziona tutti";
  }
  else{
	  $.validationEngineLanguage.newLangEng();
	  var txtSelect = "Check all";
	  var txtDeselect = "Uncheck all";
  }
  
  //modulo candidatura
  $("#JobsubmissionAddForm").validationEngine({
    validationEventTriggers:"change blur"								   
  });
  if ($('#JobsubmissionAddForm').length){
    if (noIe6){
		//$("#JobsubmissionAddForm select.sexyCombo").sexyCombo();
		$("#tabs").tabs("#JobsubmissionAddForm > fieldset.tab",{
		  onBeforeClick: function(event, tabIndex) {
			var index= this.getIndex();
			if(!(index>2)){
			  //console.log(this.getCurrentPane().find("[class^=validate]").length)
			  var errore_form = false;
			  this.getCurrentPane().find("[class^=validate]").each(function(){
				//console.log($(this).parent().html());
				$.validationEngine.loadValidation($(this));
			    if ($.validationEngine.isError == true){
				  errore_form = true;
			    }
			  });
			  if (errore_form){
				//alert('error');
				var destination = $(".formError:not('.greenPopup'):first").offset().top;
					$(".formError:not('.greenPopup')").each(function(){
						testDestination = $(this).offset().top;
						if(destination>testDestination) destination = $(this).offset().top;
					})
				$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 1100);
				return false;
			  }
			  else{
				if(index>=0){
				  var destination = $("#tabs").offset().top;
				  $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 0);
			  }
			}
			}
		  }
		});
		$("#tabs a").unbind('click').click(function(event) {event.preventDefault()});
		$("ul.wizard a").click(function(event) {event.preventDefault()});
    }else{
	  $("#tabs, ul.wizard").hide();	
	}
  }
  //iscrizione newsletter
  $("#NewsletterAddForm").validationEngine();
  if ($('#NewsletterAddForm').length && noIe6){
    $("#NewsletterAddForm select.sexyCombo").sexyCombo();
  }
  //disiscrizione newsletter
  $("#NewsletterUnsubscribeForm").validationEngine();
  //i tuoi suggerimenti
  $("#SelfsuggestionAddForm").validationEngine();
  //dai un voto al tuo self
  $("#SelfsatisfactionAddForm").validationEngine({
    validationEventTriggers:"change blur"								   
  });
  if ($('#SelfsatisfactionAddForm').length && noIe6){
    $("#SelfsatisfactionAddForm select.sexyCombo").sexyCombo();
  }
  //assistenza acquisto
  $("#StoresupportAddForm").validationEngine();
  /*if ($('#voto-mail').length){
    $('#voto-mail').change(function() {
	  if ($(this).val()){
	   $('#checkPrivacy').show().children('#SelfsatisfactionPrivacyok').addClass('validate[optional,funcCall[validatePrivacy]]');
	  }
	  else{
	   $('#checkPrivacy').hide().children('#SelfsatisfactionPrivacyok').removeClass('validate[optional,funcCall[validatePrivacy]]');
	   $('.SelfsatisfactionPrivacyokformError').fadeOut(150,function(){$(this).remove()});
	  }
    });
  }*/
  //ricarica la validazione al cambio delle checkbox
  if ($('.checkCheckbox').length){
	  $('.checkCheckbox input').change( function() {
		$.validationEngine.loadValidation($(this).parent('.checkCheckbox').find("[class^=validate]"))
      });
  }
  //seleziona/deseleziona tutti
  $("p.tutti a").toggle(function() {
    $(this).text(txtDeselect).blur().parent().next().children('input').attr('checked', 'checked');
    return false;
  }, function() {
	$(this).text(txtSelect).blur().parent().next().children('input').removeAttr('checked');
  });
  //label nel campo cerca e newsletter
  $('#searchbox label, #newsletter label').inFieldLabels({ fadeOpacity:0.1 });
  //jump menu punti vendita
  if ($('#StoreViewForm').length){
    $("#StoreViewForm select.sexyCombo")
	.sexyCombo()
	.change(function() {
	  if($(this).val()){
		location.href='/store/' + $(this).val();
	  }
	  else{
		location.href='/stores';
	  }
	})
  }
  //jump menu video
  if ($('#videoselect').length){
    $("#videoselect select.sexyCombo")
  	.sexyCombo()
  	.change(function() {
  	  if($(this).val()){
  		location.href='/video/' + $(this).val();
  	  }
  	  else{
  		location.href='/video';
  	  }
  	})
  }
  
  //jump menu offerte
  if ($('#OfferViewForm').length){
    $("#OfferViewForm select.sexyCombo")
	.sexyCombo()
	.change(function() {
		location.href='/offers/' + $(this).val();
	})
  }

}
//scroll migliori del mese (richiede jquery.tools scrollable, mousewheel, autoscroll, circular)
miglioriMese = function(){
  if ($('#migliori_mese .scrollable ul li').length > 3){
	  $("#migliori_mese .scrollable").wrap('<div class="navigazione" />');
	  $("#migliori_mese .navigazione").prepend('<a class="prevPage">prev</a>').append('<a class="nextPage">next</a>');
	  $("#migliori_mese .scrollable").scrollable({ 
		size: 3,
		clickable: false
	  }).mousewheel().autoscroll({interval:6000,steps:3}).circular();
  }
}
//scroll offerte
offerte = function () {
  if ($('#offerte li').length > 2) {
    var txtAll = 'Mostra tutte le offerte';
    var txtFour = 'Mostra 2 offerte per pagina';
    if ($("body.en-us").length) {
      var txtAll = 'Show all offers';
      var txtFour = 'Show 2 offers per page';
    }
	$("#scrollOfferte").before('<div id="navOfferte"><a class="prevPage">prev</a> <div class="navi"></div> <a class="nextPage">next</a></div>').after('<p id="toggleOfferte"><a href="#">' + txtAll + '</a></p>');
    var apiOfferte = $("#scrollOfferte").scrollable({
      clickable: false,
      size: 2
    })
	.autoscroll({
	  interval:6000,
	  steps:2
	})
	.navigator({
	  api: true,
      indexed: true
    });
    var destination = $("#content").offset().top;
    $("#toggleOfferte a").toggle(function () {
      $('#scrollOfferte').addClass('all').find('#offerte').attr('id', 'offerte_all').removeAttr("style").end().prev().hide();
      $(this).text(txtFour).blur();
      $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 0);
    }, function () {
      $('#scrollOfferte').removeClass('all').find('#offerte_all').attr('id', 'offerte').end().prev().show();
	  apiOfferte.begin();
      $(this).text(txtAll).blur();
      $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, 0);
    });
  }
}
//mostra nascondi prodotti
showHideProducts = function(){
  $('#products h2, #consigli h2').click(function(){
	$(this).toggleClass('aperto').next().slideToggle(200);					
  });
  $('#consigli h2.attivo').click().addClass('aperto');
}

//tendina menu prodotti home (richiede Superfish)
menuTop = function(){
  $('.menu').superfish({ 
	delay:       1000,
	animation:   {height:'show'},
	autoArrows:  false,
	dropShadows: false
  });
}
disable_prodotti = function(){
	$("#header .menu ul.prodotti, #header .menu ul.offerte").siblings('a').each(function() {
	  $(this)
	  .attr('href', '#')
	  .click(function(event) {
	    event.preventDefault();
	  })
	  /*.mouseleave(function(){
        $(this).blur();
      });*/
	});
}

//anima lo sfondo dell'header (richiede jquery.innerfade)
animateHeader = function(){
	$("#header").append('<div id="sfondo"></div>');
	for(var i = 1; i<=numeroImmagini; i++)
     {
       var src = '/img/banner_header/' +  dirImmagini + '/'+i+'.jpg';
	   $("#sfondo").append('<div style="background-image:url('+src+')"></div>')
     }
	if(numeroImmagini>1){
	  $('#sfondo').innerfade({
		  speed: 2000,
		  timeout: 6000,
		  type: 'random_start',
		  containerheight: '275px'
	  });
	}
}
//anima le offerte in home page (richiede jquery.innerfade)
promoHome = function(){
  if ($('#banner_promo').length){
	$('#banner_promo').innerfade({
		speed: 2000,
		timeout: 4500,
		type: 'random_start',
		containerheight: '297px'
	});
  }
}
//anima le offerte negli eventi (richiede jquery.innerfade)
promoEvent = function(){
  if ($('#slide_evento').length){
	$('#slide_evento').innerfade({
		speed: 2000,
		timeout: 4500,
		type: 'random_start',
		containerheight: '320px'
	});
  }
}
//apri/chiudi sitemap (richiede Treeview)
sitemap = function(){
  if ($('#sitemap').length){
    if ($("body.it-it").length){
	  var txtCollapse = "Riduci tutti";
	  var txtExpand = "Espandi tutti";
    }
    else{
	  var txtCollapse = "Collapse all";
	  var txtExpand = "Expand all";
    }
	$("#sitemap").before('<ul id="treecontrol"><li class="collapse"><a href="#"><span></span>'+txtCollapse+'</a></li><li><a href="#"><span></span>'+txtExpand+'</a></li></ul>')
	.treeview({
		collapsed: true,
		control:"#treecontrol",
		animated: "medium"
	});
  }
}
//inserisce mappa flash in punti vendita e virtual tour
embedSwf = function(){
  if ($('#flash_map').length){
	$("#flash_map div").flashembed({ 
        src: '/swf/punti_vendita.swf',  
		version: [10, 0],
		expressInstall: "/swf/expressinstall.swf",
        wmode: 'opaque'
    }, { 
		path_xml:'/stores/index.xml'
    });
	  
  }
  if ($('#virtual_tour').length){
	$("#virtual_tour").flashembed({ 
        src: '/swf/self_reparti_servizi.swf',  
		version: [10, 0],
		expressInstall: "/swf/expressinstall.swf",
        wmode: 'opaque'
    }, { 
		path_servizi:'/services/index.xml',
		path_reparti:'/departments/index.xml'
    });
	  
  }
}
//YOUTUBE

//faccio partire il video appena è pronto (http://code.google.com/intl/it-IT/apis/youtube/js_api_reference.html)
function onYouTubePlayerReady(playerId) {
    var ytplayer = document.getElementById(playerId);
    ytplayer.playVideo();
}

//estrae l'id del video da un link (http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367)
extractVideoId = function(url){
	id = url.match(/^.*((youtu.be\/)|(v\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/i)[6];
	return id;
}

//Convert number of seconds into time object
secondsToTime = function(secs){
	var hours = Math.floor(secs / (60 * 60));
	var divisor_for_minutes = secs % (60 * 60);
	var minutes = Math.floor(divisor_for_minutes / 60);
	var divisor_for_seconds = divisor_for_minutes % 60;
	var seconds = ( Math.ceil(divisor_for_seconds) < 10 ? "0" : "" ) + Math.ceil(divisor_for_seconds);
	var time = '';
	if(hours){
		time = hours+':';
		minutes = ( minutes < 10 ? "0" : "" ) + minutes;
	}
	time += minutes+':'+seconds;
	return time;
}
//carica i video di youtube
videoYouTube = function(){
	if ($('#video-list').length){
		
		//variabili del form che invia la mail
		var $mailForm = $('#send form');
		var url = $mailForm.attr('action');
		var $esito = $('<div id="esito"></div>');
		var $loading = $('<div id="send-loading"></div>');
		$mailForm
		.find('fieldset').append($loading).append($esito);
		
		//invio del form in ajax
		sendVideo = function(){
			var formData = $mailForm.serialize();
			$mailForm
			.find('input, textarea').attr('disabled','true');
			//show the loading sign
			$loading .fadeTo(300,0.8);
			//start the ajax
			$.post( url, formData,
				function(data) {
					if (data==1) {					
						$esito.html('<p>Messaggio inviato correttamente.</p>');
					} else {
						$esito.html('<p class="errore">Siamo spiacenti, si &egrave; verificato un errore. Per favore riprova più tardi.</p>');
					}
					$esito.fadeIn(300, function() {
						$loading.hide(0);
					});
					$mailForm.find('input, textarea').removeAttr('disabled').val('');
				}
			);
		}//fine sendVideo()
		//api key (http://code.google.com/intl/it-IT/apis/youtube/2.0/developers_guide_protocol.html#Developer_Key)
		var apiKey ='AI39si5f6Be9g5e670Q7dTFM607RJKNZeMwL0uT4X-hRyYe8yc53FCDU7dP31-IyJ1m4UUixcCxFoDi5YAopvZDSCjCz5vQc2A';
		//per ogni link ai video
		$('#video-list .video-item')
		.each(function(index){
			var videoItem = $(this);
			var videoID = extractVideoId($('a.video-link',this).attr('href'));
			$('a.video-link',this).remove();
			
			// Recupero i dati dalle API di YouTube
			//var youtubeAPI = 'http://gdata.youtube.com/feeds/api/videos?v=2&key='+apiKey+'&alt=jsonc&callback=?';
			$.get('http://gdata.youtube.com/feeds/api/users/selfitalia/uploads/'+videoID+'?v=2&alt=jsonc&callback=?',{'key':apiKey},function(response){
				var data = response.data;
				// Se il video non è stato trovato, o non è consentito l'embedding
				if(!data || data.accessControl.embed!="allowed"){
					videoItem.html('<p>Video non trovato o incorporamento non consentito</p><p><a href="http://youtu.be/'+videoID+'" target="_blank">Guarda su YouTube</p>')
					return false;
				}
				// Recupero le informazioni del video
				//data = data.items[0];
				//imposto la larghezza del video
				var videoWidth = 620
				var videoRatio = 3/4;
				if(data.aspectRatio == "widescreen"){
					videoRatio = 9/16;
				}
				//imposto l'altezza del video in base alla ratio
				var videoHeight = Math.round(videoWidth*videoRatio);
				//titolo durata e thumbnail
				var videoTitle = data.title;
				var videoDuration = secondsToTime(data.duration);
				var videoThumbnail = data.thumbnail.sqDefault;
				
				//creo il div che contiene il video
				jQuery('<div/>', {
					id: 'video'+index,
					'class': 'video-overlay',
					css: {
						width: videoWidth
					}
				})
				.appendTo($('body'))
				.flashembed({ 
					src: 'http://www.youtube.com/v/'+videoID+'&enablejsapi=1&playerapiid=player'+index,  
					version: [10, 0],
					expressInstall: "/swf/expressinstall.swf",
					wmode: 'transparent',
					width: videoWidth,
					height: videoHeight,
					id:'player'+index
				});
				
				var videoIndex = index;
				
				$('#video'+index)
				.append('<div class="condividi">'
				+'<iframe src="http://www.facebook.com/plugins/like.php?app_id=142953935782065&amp;href=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D'+videoID+'&amp;send=false&amp;layout=standard&amp;width='+videoWidth+'&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font=verdana&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:'+videoWidth+'px; height:35px;" allowTransparency="true"></iframe>'
				+'<div class="social">Pubblica su'
				+'<a class="twitter" href="http://twitter.com/share?url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D'+videoID+'&text=Guarda il video &ldquo;'+videoTitle+'&rdquo; sul canale di Self" title="Twitter" >Twitter</a>'
				+'<a class="delicious" href="http://www.delicious.com/save?v=5&noui&jump=close&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D'+videoID+'&title=Video &ldquo;'+videoTitle+'&rdquo; sul canale di Self" title="del.icio.us">Delicious</a>'
				+'</div>')
				//overlay social
				.find('.social a').each(function(index) {
					$(this).attr({target:"_blank",title:$(this).attr("title")+" (link esterno, si apre in una nuova finestra)"});
					
					//vedere https://dev.twitter.com/docs/intents per implementare
					/*var videoSocialId = 'video-social-'+videoIndex+'-'+$(this).attr('class');
					$('<div id="'+videoSocialId+'" class="video-social"><iframe frameborder="0" scrolling="auto" width="550" height="450" src="'+$(this).attr('href')+'"></iframe></div>').appendTo('body');
					$(this).overlay({
						mask: 'white',
						href: '#video-social',
						onBeforeLoad: function() {
							//First get the wrap
							var wrap = this.getOverlay().find(".contentWrap");
							//Get the URL from the trigger
							var link = this.getTrigger().attr("href");
							//Add the link and style attributes to the basic iframe
							$(theframe).attr({ src: link, style: 'height:550px; width:450px; border:none;' });
							//Write the iframe into the wrap
							wrap.html(theframe);
						}
					})*/
				});
				
				//link invia video via mail
				jQuery('<a/>', {
					href: '#send',
					rel: '#send',
					'class':'invia-mail',
					title: 'Invia per mail',
					html: 'Invia'
				})
				.insertBefore('#video'+index+' .social')
				.overlay({
					top: 0,
					left: 0,
					relativeToParent: true,//aggiunto a overlay per far sì che si posizioni relativamente al div che lo contiene
					oneInstance: false,
					onBeforeLoad: function(event) {
						$('#player'+index).get(0).pauseVideo();
						$('#send')
						.appendTo('#video'+index)
						.end().find('#send-link').val('http://youtu.be/'+videoID)
						.end().find('#send-titolo').val(videoTitle)
						.end().find('h3').html('Invia il video &ldquo;'+videoTitle+'&rdquo; a un amico');
						$mailForm.validationEngine({
							scroll: false,								   
							//se i campi sono validi invia la mail (ajax)
							success :  function(formData) { sendVideo() }
						});
					},
					onClose: function(event) {
						$.validationEngine.closePrompt('.formError',true)
						$esito.hide();
					}
				});
				

				
				//creo il link che punta al video
				jQuery('<a/>', {
					href: '#video'+index,
					rel: '#video'+index,
					title: videoTitle,
					html: '<img src="'+videoThumbnail+'" alt="'+videoTitle+'" /> '+videoTitle+' <span class="duration">'+videoDuration+'</span>'
				})
				.appendTo($('h2',videoItem))
				.overlay({
					top: 'center',
					expose: { 
						color: '#000', 
						loadSpeed: 200, 
						opacity: 0.4 
					},
					oneInstance: false,
					closeOnClick: false,
					//metto in pausa il video alla chiusura dell'overlay
					onBeforeClose: function(event) {
						$('#player'+index).get(0).pauseVideo();
					}
				});
			},'jsonp');
		})
		.filter('div:nth-child(3n)').after('<div class="borderbottom"></div>');
		//scroll in consigli utili
		if ($('#video-list li').length > 4){
		  $(".video-slide .scrollable").wrap('<div class="navigazione" />');
		  $(".video-slide .navigazione").prepend('<a class="prevPage">prev</a>').append('<a class="nextPage">next</a>');
		  $(".video-slide .scrollable").scrollable({ 
			size: 4,
			clickable: false
		  }).mousewheel();
		}
		
		
	}//fine if video-list
}

//init
jQuery("html").addClass('js');
jQuery(document).ready(function($){
  embedSwf();
  linkext();
  menuTop();
  disable_prodotti();
  animateHeader();
  promoHome();
  promoEvent();
  formFunctions();
  showHideProducts();
  miglioriMese();
  overlay();
  sfoglia();
  offerte();
  sitemap();
  doppio_overlay();//doppio volantino natale
  overlay_pv();
  videoYouTube();
});
