/* Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-07-21 18:44:59 -0500 (Sat, 21 Jul 2007) $
 * $Rev: 2446 $
 *
 * Version 2.1.1
 */

/*tamanys stylish select*/
var width_simple = "3em";
var width_normal = "425px";

(function($){
$.fn.bgIframe = $.fn.bgiframe = function(s) {
	// This is only for IE6
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
		s = $.extend({
			top     : 'auto', // auto == .currentStyle.borderTopWidth
			left    : 'auto', // auto == .currentStyle.borderLeftWidth
			width   : 'auto', // auto == offsetWidth
			height  : 'auto', // auto == offsetHeight
			opacity : true,
			src     : 'javascript:false;'
		}, s || {});
		var prop = function(n){return n&&n.constructor==Number?n+'px':n;},
		    html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
		               'style="display:block;position:absolute;z-index:-1;'+
			               (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+
					       'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+
					       'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+
					       'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+
					       'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+
					'"/>';
		return this.each(function() {
			if ( $('> iframe.bgiframe', this).length == 0 )
				this.insertBefore( document.createElement(html), this.firstChild );
		});
	}
	return this;
};

})(jQuery);


/*
Stylish Select 0.4.1 - $ plugin to replace a select drop down box with a stylable unordered list
http://scottdarby.com/

Requires: jQuery 1.3 or newer

Contributions from Justin Beasley: http://www.harvest.org/ & Anatoly Ressin: http://www.artazor.lv/

Dual licensed under the MIT and GPL licenses.

*/
				
(function($){

    //add class of js to html tag
    $('html').addClass('stylish-select');

    //create cross-browser indexOf
    Array.prototype.indexOf = function (obj, start) {
        for (var i = (start || 0); i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
    }
	
    //utility methods
    $.fn.extend({
        getSetSSValue: function(value){
            if (value){
                //set value and trigger change event
                $(this).val(value).change();
                return this;
            } else {
                return $(this).find(':selected').val();
            }
        },
        //added by Justin Beasley
        resetSS: function(){
            var oldOpts = $(this).data('ssOpts');
            $this = $(this);
            $this.next().remove();
            //unbind all events and redraw
            $this.unbind().sSelect(oldOpts);
        }
    });

    $.fn.sSelect = function(options) {
	
        return this.each(function(){
			
            var defaults = {
                defaultText: 'Please select',
                animationSpeed: 0, //set speed of dropdown
                ddMaxHeight: '' //set css max-height value of dropdown
            };

            //initial variables
            var opts = $.extend(defaults, options),
            $input = $(this),
            $containerDivText = $('<div class="selectedTxt"></div>'),
            $containerDiv = $('<div class="newListSelected" tabindex="0"></div>'),
            $newUl = $('<ul class="newList"></ul>'),
            itemIndex = -1,
            currentIndex = -1,
            keys = [],
            prevKey = false,
            prevented = false,
            $newLi;

            //added by Justin Beasley
            $(this).data('ssOpts',options);
			
            //build new list
            $containerDiv.insertAfter($input);
            $containerDivText.prependTo($containerDiv);
            $newUl.appendTo($containerDiv);
            $input.hide();

            //test for optgroup
            if ($input.children('optgroup').length == 0){
                indexFirst = 0;
            	$input.children().each(function(i){
                    var option = $(this).text();
                    var key = $(this).val();
                    
                    //add first letter of each word to array
                    keys.push(option.charAt(0).toLowerCase());
                    if ($(this).attr('selected') == true){
                        opts.defaultText = option;
                        currentIndex = i;
                    }
					valors=option.split("|"); //separem els camps dels valors
					$('.newList').bgiframe();
					
					classFirst = "";
					
					if (indexFirst==0) {classFirst = 'class="title"';}
                    if (valors[1]=="" && valors[2]=="") {
						$newUl.append($('<li '+classFirst+'><a href="JavaScript:void(0);"><span class="id">'+valors[0]+'</span></a></li>').data('key', key));
						$newUl.css({"width":width_simple});
						$newUl.find("li").css({"width":width_simple});
					} else if (valors[2]=="") {
						$newUl.append($('<li '+classFirst+'><a href="JavaScript:void(0);"><span class="id">'+valors[0]+'</span> <span class="exemple">'+valors[1]+'</span></a></li>').data('key', key));
						$newUl.css({"width":width_normal});
						$newUl.find("li").css({"width":width_normal});
					} else {
						$newUl.append($('<li '+classFirst+'><a href="JavaScript:void(0);"><span class="id">'+valors[0]+'</span> <span class="valor">'+valors[1]+'</span> <span class="exemple">'+valors[2]+'</span></a></li>').data('key', key));
						$newUl.css({"width":width_normal});
						$newUl.find("li").css({"width":width_normal});
					}                    
                    indexFirst++;

                });
                //cache list items object
                $newLi = $newUl.children().children();
            } else { //optgroup
                $input.children('optgroup').each(function(){
				
                    var optionTitle = $(this).attr('label'),
                    $optGroup = $('<li class="newListOptionTitle">'+optionTitle+'</li>');
						
                    $optGroup.appendTo($newUl);

                    var $optGroupList = $('<ul></ul>');

                    $optGroupList.appendTo($optGroup);

                    $(this).children().each(function(){
                        ++itemIndex;
                        var option = $(this).text();
                        var key = $(this).val();
                        //add first letter of each word to array
                        keys.push(option.charAt(0).toLowerCase());
                        if ($(this).attr('selected') == true){
                            opts.defaultText = option;
                            currentIndex = itemIndex;
                        }
                        classFirst = "";
                        if (currentIndex==0) {classFirst = 'class="title"';}
                        $optGroupList.append($('<li '+classFirst+'><a href="JavaScript:void(0);">'+option+'</a></li>').data('key',key));
                    })
                });
                //cache list items object
                $newLi = $newUl.find('ul li a');
            }
			
            //get heights of new elements for use later
            var newUlHeight = $newUl.height(),
            containerHeight = $containerDiv.height(),
            newLiLength = $newLi.length;
		
            //check if a value is selected
            if (currentIndex != -1){
                navigateList(currentIndex, true);
            } else {
                //set placeholder text
                $containerDivText.text(opts.defaultText);
            }

            //decide if to place the new list above or below the drop-down
            function newUlPos(){
                var containerPosY = $containerDiv.offset().top,
                docHeight = jQuery(window).height(),
                scrollTop = jQuery(window).scrollTop();

                //if height of list is greater then max height, set list height to max height value
                if (newUlHeight > parseInt(opts.ddMaxHeight)) {
                    newUlHeight = parseInt(opts.ddMaxHeight);
                }

                containerPosY = containerPosY-scrollTop;
                if (containerPosY+newUlHeight >= docHeight){
                    $newUl.css({
                        top: '-'+newUlHeight+'px',
                        height: newUlHeight
                    });
                    $input.onTop = true;
                } else {
                    $newUl.css({
                        top: containerHeight+'px',
                        height: newUlHeight
                    });
                    $input.onTop = false;
                }
            }

            //run function on page load
            newUlPos();
			
            //run function on browser window resize
            $(window).resize(function(){
                newUlPos();
            });
			
            $(window).scroll(function(){
                newUlPos();
            });

            //positioning
            function positionFix(){
                $containerDiv.css('position','relative');
            }

            function positionHideFix(){
                $containerDiv.css('position','static');
            }
			
            $containerDivText.click(function(event){

                event.stopPropagation();

                //hide all menus apart from this one
                $('.newList').not($(this).next()).hide().parent().removeClass('newListSelFocus');

                //show/hide this menu
                $newUl.toggle();
                positionFix();
                //scroll list to selected item
                $newLi.eq(currentIndex).focus();


            });

            $newLi.click(function(e){
				var $clickedLi = $(e.target);
				
                //update counter
                currentIndex = $newLi.index($clickedLi.parent()); //escollim el parent degut als spans
				
                //remove all hilites, then add hilite to selected item
                prevented = true;
                navigateList(currentIndex);
                $newUl.hide();
                $containerDiv.css('position','static');//ie

            });
			
            $newLi.hover(
                function(e) {
                    var $hoveredLi = $(e.target);
                    $hoveredLi.addClass('newListHover');
                },
                function(e) {
                    var $hoveredLi = $(e.target);
                    $hoveredLi.removeClass('newListHover');
                }
                );

            function navigateList(currentIndex, init){
                $newLi.removeClass('hiLite')
                .eq(currentIndex)
                .addClass('hiLite');

                /*if ($newUl.is(':visible')){
                    $newLi.eq(currentIndex).focus();
                }*/

                var text = $newLi.eq(currentIndex).text();
                var val = $newLi.eq(currentIndex).parent().data('key');
                
                //page load
                if (init == true){
                    $input.val(val);
                    $containerDivText.text(text);
                    return false;
                }
                
                $input.val(val)
                $input.change();
                $containerDivText.text(text);
            };

            $input.change(function(event){
                $targetInput = $(event.target);
                //stop change function from firing
                if (prevented == true){
                    prevented = false;
                    return false;
                }
                $currentOpt = $targetInput.find(':selected');
                
                //currentIndex = $targetInput.find('option').index($currentOpt);
                currentIndex = $targetInput.find('option').index($currentOpt);


                navigateList(currentIndex, true);
            }
            );
			
            //handle up and down keys
            function keyPress(element) {
                //when keys are pressed
                element.onkeydown = function(e){
                    var keycode;
                    if (e == null) { //ie
                        keycode = event.keyCode;
                    } else { //everything else
                        keycode = e.which;
                    }

                    //prevent change function from firing
                    prevented = true;

                    switch(keycode)
                    {
                        case 40: //down
                        case 39: //right
                            incrementList();
                            return false;
                            break;
                        case 38: //up
                        case 37: //left
                            decrementList();
                            return false;
                            break;
                        case 33: //page up
                        case 36: //home
                            gotoFirst();
                            return false;
                            break;
                        case 34: //page down
                        case 35: //end
                            gotoLast();
                            return false;
                            break;
                        case 13:
                        case 27:
                            $newUl.hide();
                            positionHideFix();
                            return false;
                            break;
                    }

                    //check for keyboard shortcuts
                    keyPressed = String.fromCharCode(keycode).toLowerCase();
                    
                    var currentKeyIndex = keys.indexOf(keyPressed);

                    if (typeof currentKeyIndex != 'undefined') { //if key code found in array
                        ++currentIndex;
                        currentIndex = keys.indexOf(keyPressed, currentIndex); //search array from current index
                        if (currentIndex == -1 || currentIndex == null || prevKey != keyPressed) currentIndex = keys.indexOf(keyPressed); //if no entry was found or new key pressed search from start of array

                        
                        navigateList(currentIndex);
                        //store last key pressed
                        prevKey = keyPressed;
                        return false;
                    }
                }
            }

            function incrementList(){
                if (currentIndex < (newLiLength-1)) {
                    ++currentIndex;
                    navigateList(currentIndex);
                }
            }

            function decrementList(){
                if (currentIndex > 0) {
                    --currentIndex;
                    navigateList(currentIndex);
                }
            }

            function gotoFirst(){
                currentIndex = 0;
                navigateList(currentIndex);
            }
			
            function gotoLast(){
                currentIndex = newLiLength-1;
                navigateList(currentIndex);
            }

            $containerDiv.click(function(){
                keyPress(this);
            });

            $containerDiv.focus(function(){
                $(this).addClass('newListSelFocus');
                keyPress(this);
            });

            $containerDiv.blur(function(){
                $(this).removeClass('newListSelFocus');
            });
			
            //hide list on blur
            $('body').click(function(){
                $containerDiv.removeClass('newListSelFocus');
                $newUl.hide();
                positionHideFix();
            });
			
            //add classes on hover
            $containerDivText.hover(function(e) {
                var $hoveredTxt = $(e.target);
                $hoveredTxt.parent().addClass('newListSelHover');
            },
            function(e) {
                var $hoveredTxt = $(e.target);
                $hoveredTxt.parent().removeClass('newListSelHover');
            }
            );

            //reset left property and hide
            $newUl.css('left','0').hide();
			
        });
	  
    };

})(jQuery);

//ColorBox v1.3.14 - a full featured, light-weight, customizable lightbox based on jQuery 1.3+
//Copyright (c) 2010 Jack Moore - jack@colorpowered.com
//Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
(function(b,ib){var t="none",M="LoadedContent",c=false,v="resize.",o="y",q="auto",e=true,L="nofollow",m="x";function f(a,c){a=a?' id="'+i+a+'"':"";c=c?' style="'+c+'"':"";return b("<div"+a+c+"/>")}function p(a,b){b=b===m?n.width():n.height();return typeof a==="string"?Math.round(/%/.test(a)?b/100*parseInt(a,10):parseInt(a,10)):a}function U(b){return a.photo||/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i.test(b)}function cb(a){for(var c in a)if(b.isFunction(a[c])&&c.substring(0,2)!=="on")a[c]=a[c].call(l);a.rel=a.rel||l.rel||L;a.href=a.href||b(l).attr("href");a.title=a.title||l.title;return a}function w(c,a){a&&a.call(l);b.event.trigger(c)}function jb(){var b,e=i+"Slideshow_",c="click."+i,f,k;if(a.slideshow&&h[1]){f=function(){F.text(a.slideshowStop).unbind(c).bind(V,function(){if(g<h.length-1||a.loop)b=setTimeout(d.next,a.slideshowSpeed)}).bind(W,function(){clearTimeout(b)}).one(c+" "+N,k);j.removeClass(e+"off").addClass(e+"on");b=setTimeout(d.next,a.slideshowSpeed)};k=function(){clearTimeout(b);F.text(a.slideshowStart).unbind([V,W,N,c].join(" ")).one(c,f);j.removeClass(e+"on").addClass(e+"off")};a.slideshowAuto?f():k()}}function db(c){if(!O){l=c;a=cb(b.extend({},b.data(l,r)));h=b(l);g=0;if(a.rel!==L){h=b("."+G).filter(function(){return (b.data(this,r).rel||this.rel)===a.rel});g=h.index(l);if(g===-1){h=h.add(l);g=h.length-1}}if(!u){u=E=e;j.show();if(a.returnFocus)try{l.blur();b(l).one(eb,function(){try{this.focus()}catch(a){}})}catch(f){}x.css({opacity:+a.opacity,cursor:a.overlayClose?"pointer":q}).show();a.w=p(a.initialWidth,m);a.h=p(a.initialHeight,o);d.position(0);X&&n.bind(v+P+" scroll."+P,function(){x.css({width:n.width(),height:n.height(),top:n.scrollTop(),left:n.scrollLeft()})}).trigger("scroll."+P);w(fb,a.onOpen);Y.add(H).add(I).add(F).add(Z).hide();ab.html(a.close).show()}d.load(e)}}var gb={transition:"elastic",speed:300,width:c,initialWidth:"600",innerWidth:c,maxWidth:c,height:c,initialHeight:"450",innerHeight:c,maxHeight:c,scalePhotos:e,scrolling:e,inline:c,html:c,iframe:c,photo:c,href:c,title:c,rel:c,opacity:.9,preloading:e,current:"image {current} of {total}",previous:"previous",next:"next",close:"close",open:c,returnFocus:e,loop:e,slideshow:c,slideshowAuto:e,slideshowSpeed:2500,slideshowStart:"start slideshow",slideshowStop:"stop slideshow",onOpen:c,onLoad:c,onComplete:c,onCleanup:c,onClosed:c,overlayClose:e,escKey:e,arrowKey:e},r="colorbox",i="cbox",fb=i+"_open",W=i+"_load",V=i+"_complete",N=i+"_cleanup",eb=i+"_closed",Q=i+"_purge",hb=i+"_loaded",A=b.browser.msie&&!b.support.opacity,X=A&&b.browser.version<7,P=i+"_IE6",x,j,B,s,bb,T,R,S,h,n,k,J,K,Z,Y,F,I,H,ab,C,D,y,z,l,g,a,u,E,O=c,d,G=i+"Element";d=b.fn[r]=b[r]=function(c,f){var a=this,d;if(!a[0]&&a.selector)return a;c=c||{};if(f)c.onComplete=f;if(!a[0]||a.selector===undefined){a=b("<a/>");c.open=e}a.each(function(){b.data(this,r,b.extend({},b.data(this,r)||gb,c));b(this).addClass(G)});d=c.open;if(b.isFunction(d))d=d.call(a);d&&db(a[0]);return a};d.init=function(){var l="hover",m="clear:left";n=b(ib);j=f().attr({id:r,"class":A?i+"IE":""});x=f("Overlay",X?"position:absolute":"").hide();B=f("Wrapper");s=f("Content").append(k=f(M,"width:0; height:0; overflow:hidden"),K=f("LoadingOverlay").add(f("LoadingGraphic")),Z=f("Title"),Y=f("Current"),I=f("Next"),H=f("Previous"),F=f("Slideshow").bind(fb,jb),ab=f("Close"));B.append(f().append(f("TopLeft"),bb=f("TopCenter"),f("TopRight")),f(c,m).append(T=f("MiddleLeft"),s,R=f("MiddleRight")),f(c,m).append(f("BottomLeft"),S=f("BottomCenter"),f("BottomRight"))).children().children().css({"float":"left"});J=f(c,"position:absolute; width:9999px; visibility:hidden; display:none");b("body").prepend(x,j.append(B,J));s.children().hover(function(){b(this).addClass(l)},function(){b(this).removeClass(l)}).addClass(l);C=bb.height()+S.height()+s.outerHeight(e)-s.height();D=T.width()+R.width()+s.outerWidth(e)-s.width();y=k.outerHeight(e);z=k.outerWidth(e);j.css({"padding-bottom":C,"padding-right":D}).hide();I.click(d.next);H.click(d.prev);ab.click(d.close);s.children().removeClass(l);b("."+G).live("click",function(a){if(!(a.button!==0&&typeof a.button!=="undefined"||a.ctrlKey||a.shiftKey||a.altKey)){a.preventDefault();db(this)}});x.click(function(){a.overlayClose&&d.close()});b(document).bind("keydown",function(b){if(u&&a.escKey&&b.keyCode===27){b.preventDefault();d.close()}if(u&&a.arrowKey&&!E&&h[1])if(b.keyCode===37&&(g||a.loop)){b.preventDefault();H.click()}else if(b.keyCode===39&&(g<h.length-1||a.loop)){b.preventDefault();I.click()}})};d.remove=function(){j.add(x).remove();b("."+G).die("click").removeData(r).removeClass(G)};d.position=function(f,d){function b(a){bb[0].style.width=S[0].style.width=s[0].style.width=a.style.width;K[0].style.height=K[1].style.height=s[0].style.height=T[0].style.height=R[0].style.height=a.style.height}var e,h=Math.max(document.documentElement.clientHeight-a.h-y-C,0)/2+n.scrollTop(),g=Math.max(n.width()-a.w-z-D,0)/2+n.scrollLeft();e=j.width()===a.w+z&&j.height()===a.h+y?0:f;B[0].style.width=B[0].style.height="9999px";j.dequeue().animate({width:a.w+z,height:a.h+y,top:h,left:g},{duration:e,complete:function(){b(this);E=c;B[0].style.width=a.w+z+D+"px";B[0].style.height=a.h+y+C+"px";d&&d()},step:function(){b(this)}})};d.resize=function(b){if(u){b=b||{};if(b.width)a.w=p(b.width,m)-z-D;if(b.innerWidth)a.w=p(b.innerWidth,m);k.css({width:a.w});if(b.height)a.h=p(b.height,o)-y-C;if(b.innerHeight)a.h=p(b.innerHeight,o);if(!b.innerHeight&&!b.height){b=k.wrapInner("<div style='overflow:auto'></div>").children();a.h=b.height();b.replaceWith(b.children())}k.css({height:a.h});d.position(a.transition===t?0:a.speed)}};d.prep=function(o){var e="hidden";function m(t){var q,f,o,e,m=h.length,s=a.loop;d.position(t,function(){if(u){A&&p&&k.fadeIn(100);k.show();w(hb);Z.show().html(a.title);if(m>1){typeof a.current==="string"&&Y.html(a.current.replace(/\{current\}/,g+1).replace(/\{total\}/,m)).show();I[s||g<m-1?"show":"hide"]().html(a.next);H[s||g?"show":"hide"]().html(a.previous);q=g?h[g-1]:h[m-1];o=g<m-1?h[g+1]:h[0];a.slideshow&&F.show();if(a.preloading){e=b.data(o,r).href||o.href;f=b.data(q,r).href||q.href;e=b.isFunction(e)?e.call(o):e;f=b.isFunction(f)?f.call(q):f;if(U(e))b("<img/>")[0].src=e;if(U(f))b("<img/>")[0].src=f}}K.hide();if(a.transition==="fade")j.fadeTo(l,1,function(){if(A)j[0].style.filter=c});else if(A)j[0].style.filter=c;n.bind(v+i,function(){d.position(0)});w(V,a.onComplete)}})}if(u){var p,l=a.transition===t?0:a.speed;n.unbind(v+i);k.remove();k=f(M).html(o);k.hide().appendTo(J.show()).css({width:function(){a.w=a.w||k.width();a.w=a.mw&&a.mw<a.w?a.mw:a.w;return a.w}(),overflow:a.scrolling?q:e}).css({height:function(){a.h=a.h||k.height();a.h=a.mh&&a.mh<a.h?a.mh:a.h;return a.h}()}).prependTo(s);J.hide();b("#"+i+"Photo").css({cssFloat:t,marginLeft:q,marginRight:q});X&&b("select").not(j.find("select")).filter(function(){return this.style.visibility!==e}).css({visibility:e}).one(N,function(){this.style.visibility="inherit"});a.transition==="fade"?j.fadeTo(l,0,function(){m(0)}):m(l)}};d.load=function(u){var n,c,s,q=d.prep;E=e;l=h[g];u||(a=cb(b.extend({},b.data(l,r))));w(Q);w(W,a.onLoad);a.h=a.height?p(a.height,o)-y-C:a.innerHeight&&p(a.innerHeight,o);a.w=a.width?p(a.width,m)-z-D:a.innerWidth&&p(a.innerWidth,m);a.mw=a.w;a.mh=a.h;if(a.maxWidth){a.mw=p(a.maxWidth,m)-z-D;a.mw=a.w&&a.w<a.mw?a.w:a.mw}if(a.maxHeight){a.mh=p(a.maxHeight,o)-y-C;a.mh=a.h&&a.h<a.mh?a.h:a.mh}n=a.href;K.show();if(a.inline){f().hide().insertBefore(b(n)[0]).one(Q,function(){b(this).replaceWith(k.children())});q(b(n))}else if(a.iframe){j.one(hb,function(){var c=b("<iframe name='"+(new Date).getTime()+"' frameborder=0"+(a.scrolling?"":" scrolling='no'")+(A?" allowtransparency='true'":"")+" style='width:100%; height:100%; border:0; display:block;'/>");c[0].src=a.href;c.appendTo(k).one(Q,function(){c[0].src='//about:blank'})});q(" ")}else if(a.html)q(a.html);else if(U(n)){c=new Image;c.onload=function(){var e;c.onload=null;c.id=i+"Photo";b(c).css({border:t,display:"block",cssFloat:"left"});if(a.scalePhotos){s=function(){c.height-=c.height*e;c.width-=c.width*e};if(a.mw&&c.width>a.mw){e=(c.width-a.mw)/c.width;s()}if(a.mh&&c.height>a.mh){e=(c.height-a.mh)/c.height;s()}}if(a.h)c.style.marginTop=Math.max(a.h-c.height,0)/2+"px";h[1]&&(g<h.length-1||a.loop)&&b(c).css({cursor:"pointer"}).click(d.next);if(A)c.style.msInterpolationMode="bicubic";setTimeout(function(){q(c)},1)};setTimeout(function(){c.src=n},1)}else n&&J.load(n,function(d,c,a){q(c==="error"?"Request unsuccessful: "+a.statusText:b(this).children())})};d.next=function(){if(!E){g=g<h.length-1?g+1:0;d.load()}};d.prev=function(){if(!E){g=g?g-1:h.length-1;d.load()}};d.close=function(){if(u&&!O){O=e;u=c;w(N,a.onCleanup);n.unbind("."+i+" ."+P);x.fadeTo("fast",0);j.stop().fadeTo("fast",0,function(){w(Q);k.remove();j.add(x).css({opacity:1,cursor:q}).hide();setTimeout(function(){O=c;w(eb,a.onClosed)},1)})}};d.element=function(){return b(l)};d.settings=gb;b(d.init)})(jQuery,this)


/*
 * 	Easy Slider 1.7 - jQuery plugin
 *	written by Alen Grakalic
 *	http://cssglobe.com/post/4004/easy-slider-15-the-easiest-jquery-plugin-for-sliding
 *
 *	Copyright (c) 2009 Alen Grakalic (http://cssglobe.com)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */

/*
 *	markup example for $("#slider").easySlider();
 *
 * 	<div id="slider">
 *		<ul>
 *			<li><img src="images/01.jpg" alt="" /></li>
 *			<li><img src="images/02.jpg" alt="" /></li>
 *			<li><img src="images/03.jpg" alt="" /></li>
 *			<li><img src="images/04.jpg" alt="" /></li>
 *			<li><img src="images/05.jpg" alt="" /></li>
 *		</ul>
 *	</div>
 *
 */

eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(7($){$.1D.1C=7(3){6 15={m:\'1B\',19:\'1A\',v:\'1E\',1a:\'1F\',16:d,1d:\'\',1e:\'\',T:d,l:\'1J\',17:\'1I\',1c:8,x:\'1H\',18:\'1G\',1g:8,M:8,o:1z,Z:8,Y:1u,q:8,E:8,r:\'1s\'};6 3=$.1r(15,3);Q.1q(7(){6 5=$(Q);6 s=$("e",5).1p;6 w=$("e",5).F();6 h=$("e",5).14();6 H=d;5.F(w);5.14(h);5.k("1t","1x");6 j=s-1;6 t=0;$("c",5).k(\'F\',s*w);4(3.q){$("c",5).1w($("c e:R-12",5).11().k("S-I","-"+w+"1v"));$("c",5).1y($("c e:1K-12(2)",5).11());$("c",5).k(\'F\',(s+1)*w)};4(!3.M)$("e",5).k(\'1X\',\'I\');4(3.16){6 9=3.1d;4(3.E){9+=\'<1f g="\'+3.r+\'"></1f>\'}n{9+=\'<1b g="1S">\';4(3.1c)9+=\'<f g="\'+3.l+\'"><a u=\\"y:z(0);\\">\'+3.17+\'</a></f>\';9+=\' <f g="\'+3.m+\'"><a u=\\"y:z(0);\\">\'+3.19+\'</a></f>\';9+=\' <f g="\'+3.v+\'"><a u=\\"y:z(0);\\">\'+3.1a+\'</a></f>\';4(3.1g)9+=\' <f g="\'+3.x+\'"><a u=\\"y:z(0);\\">\'+3.18+\'</a></f>\';9+=\'</1b>\'};9+=3.1e;$(5).1O(9)};4(3.E){1M(6 i=0;i<s;i++){$(1Y.1U("e")).13(\'g\',3.r+(i+1)).9(\'<a 1h=\'+i+\' u=\\"y:z(0);\\">\'+(i+1)+\'</a>\').1Z($("#"+3.r)).A(7(){b($("a",$(Q)).13(\'1h\'),d)})}}n{$("a","#"+3.v).A(7(){b("B",d)});$("a","#"+3.m).A(7(){b("1m",d)});$("a","#"+3.l).A(7(){b("1i",d)});$("a","#"+3.x).A(7(){b("R",d)})};7 10(i){i=1W(i)+1;$("e","#"+3.r).W("1o");$("e#"+3.r+i).K("1o")};7 X(){4(t>j)t=0;4(t<0)t=j;4(!3.M){$("c",5).k("S-I",(t*w*-1))}n{$("c",5).k("S-I",(t*h*-1))}H=d;4(3.E)10(t)};7 b(L,V){4(H){H=8;6 P=t;1V(L){G"B":t=(P>=j)?(3.q?t+1:j):t+1;D;G"1m":t=(t<=0)?(3.q?t-1:0):t-1;D;G"1i":t=0;D;G"R":t=j;D;1Q:t=L;D};6 U=1T.20(P-t);6 o=U*3.o;4(!3.M){p=(t*w*-1);$("c",5).b({1R:p},{1j:8,1k:o,1n:X})}n{p=(t*h*-1);$("c",5).b({1N:p},{1j:8,1k:o,1n:X})};4(!3.q&&3.T){4(t==j){$("a","#"+3.v).K("C");$("a","#"+3.x).O()}n{$("a","#"+3.v).W("C").N();$("a","#"+3.x).N()};4(t==0){$("a","#"+3.m).K("C");$("a","#"+3.l).O()}n{$("a","#"+3.m).W("C").N();$("a","#"+3.l).N()}};4(V)1L(J);4(3.Z&&L=="B"&&!V){;J=1l(7(){b("B",8)},U*3.o+3.Y)}}};6 J;4(3.Z){;J=1l(7(){b("B",8)},3.Y)};4(3.E)10(0);4(!3.q&&3.T){$("a","#"+3.m).K("C");$("a","#"+3.l).O()}})}})(1P);',62,125,'|||options|if|obj|var|function|false|html||animate|ul|true|li|span|id|||ts|css|firstId|prevId|else|speed||continuous|numericId|||href|nextId||lastId|javascript|void|click|next|disabled|break|numeric|width|case|clickable|left|timeout|addClass|dir|vertical|show|hide|ot|this|last|margin|controlsFade|diff|clicked|removeClass|adjust|pause|auto|setCurrent|clone|child|attr|height|defaults|controlsShow|firstText|lastText|prevText|nextText|div|firstShow|controlsBefore|controlsAfter|ol|lastShow|rel|first|queue|duration|setTimeout|prev|complete|current|length|each|extend|controls|overflow|2000|px|prepend|hidden|append|800|Previous|prevBtn|easySlider|fn|nextBtn|Next|Last|lastBtn|First|firstBtn|nth|clearTimeout|for|marginTop|after|jQuery|default|marginLeft|slider_nav|Math|createElement|switch|parseInt|float|document|appendTo|abs'.split('|'),0,{}))
//eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(5($){$.K.V=5(d){3 e={8:\'U\',v:\'M\',4:\'J\',A:\'E\',B:\'\',j:T};3 d=$.R(e,d);Q f.L(5(){2=$(f);3 s=$("n",2).I;3 w=2.k();3 h=2.D();3 b=s-1;3 t=0;3 c=(d.B==\'S\');$("i",2).z(\'k\',s*w);6(!c)$("n",2).z(\'P\',\'O\');$(2).N(\'<9 u="\'+d.8+\'"><a r=\\"m:q(0);\\">\'+d.v+\'</a></9> <9 u="\'+d.4+\'"><a r=\\"m:q(0);\\">\'+d.A+\'</a></9>\');$("a","#"+d.8).o();$("a","#"+d.4).o();$("a","#"+d.4).y(5(){7("l");6(t>=b)$(f).x();$("a","#"+d.8).g()});$("a","#"+d.8).y(5(){7("H");6(t<=0)$(f).x();$("a","#"+d.4).g()});5 7(a){6(a=="l"){t=(t>=b)?b:t+1}C{t=(t<=0)?0:t-1};6(!c){p=(t*w*-1);$("i",2).7({G:p},d.j)}C{p=(t*h*-1);$("i",2).7({F:p},d.j)}};6(s>1)$("a","#"+d.4).g()})}})(W);',59,59,'||obj|var|nextId|function|if|animate|prevId|span||||||this|fadeIn||ul|speed|width|next|javascript|li|hide||void|href|||id|prevText||fadeOut|click|css|nextText|orientation|else|height|Next|marginTop|marginLeft|prev|length|nextBtn|fn|each|Previous|after|left|float|return|extend|vertical|800|prevBtn|easySlider|jQuery'.split('|'),0,{}))

google.setOnLoadCallback(function() {
	
	//definició elements
	var select_type_search=$("select#type_search");
	
	$(".form_material fieldset:not(:last)").children(":not(legend)").slideToggle();
	$(".form_material fieldset legend").css("cursor","pointer").append("⇣");
	$(".form_material legend").click(function(){
		$(this).siblings(":not(legend)").toggle();
        //cambiar la flecha al desplegar
        legend=($(this).text().substring(0,($(this).text().length)-1));
        if ($(this).siblings(':hidden').length==0) $(this).html(legend).append("⇡");
        else $(this).html(legend).append("⇣");
	});
    
	$(".form_material_edit fieldset legend").css("cursor","pointer").append("⇡");
	$(".form_material_edit legend").click(function(){
		$(this).siblings(":not(legend)").toggle();
        //cambiar la flecha al desplegar
        legend=($(this).text().substring(0,($(this).text().length)-1));
        if ($(this).siblings(':hidden').length==0) $(this).html(legend).append("⇡");
        else $(this).html(legend).append("⇣");
	});
	

	//$(".errors").parents().children(":not(legend)").slideDown();
	
	//Mensajes "flash"	
	if($(".messages").length>0){
		$(".messages").slideDown('slow');
	    $(".messages").animate({opacity: 1.0}, 15000);
	    $(".messages").slideUp('slow', function() {
	    	$(".messages").remove();
	    });
	}
	
	$("#messages_close").click(function(){
		$(".pay_messages").slideDown('slow');
	    $(".pay_messages").animate({opacity: 1.0}, 0);
	    $(".pay_messages").slideUp('slow', function() {
	    	$(".pay_messages").remove();
	    });
	});
	
	//Stylish Select
	if ($('select.sselect').length>0) {
		$('select.sselect').sSelect();
	}
	
	//families form material	
	//controlem si hi ha inputs checked la primera vegada
	if ($('form #familias ol:not(:last) input:checkbox').is(':checked')) {
		$('form #familias ol:last label').removeClass('disabled');
		$('form #familias ol:last input:checkbox').removeAttr('disabled');
	} else {
		$('form #familias ol:last label').addClass('disabled');
		$('form #familias ol:last input:checkbox').attr('disabled',true);
		$('form #familias ol:last input:checkbox').attr('checked',false);
	}
	
	$('form #familias input:checkbox').change(function(){
		//controlem si hi ha inputs checked
		if ($('form #familias ol:not(:last) input:checkbox').is(':checked')) {
			$('form #familias ol:last label').removeClass('disabled');
			$('form #familias ol:last input:checkbox').removeAttr('disabled');
		} else {
			$('form #familias ol:last label').addClass('disabled');
			$('form #familias ol:last input:checkbox').attr('disabled',true);
			$('form #familias ol:last input:checkbox').attr('checked',false);
		}
	});
	
	//filtres caràcters propietats
	$('.numeric').keypress(function(e){
		
		var chars = new Array(43,44,45,101);
		var keys = new Array(8,9,13,35,36,37,38,39,40,43);
		
		if (jQuery.inArray(e.keyCode, keys) >= 0 || (e.which > 47 && e.which < 58) || jQuery.inArray(e.which, chars) >= 0) {
			return true;
		} else {
			alert ('Sólo se permiten números y los caracteres "+", "-", "," y "e"');
			return false;
		}
	});
		
	$('.integer').keypress(function(e) {
		
		var keys = new Array(8,9,13,35,36,37,38,39,40,43);

		if (jQuery.inArray(e.keyCode, keys) >= 0 || (e.which > 47 && e.which < 58)) {
			return true;
		} else {
			alert ('Sólo se permiten números');
			return false;
		}
	});
	
	//add_items in a add_boxes
	var count = new Array();
	$('.add_item').click(function(e){
		//comptador de camps segons el name del textarea
		if (count[$(this).prev().prev().attr('name')] == undefined) count[$(this).prev().prev().attr('name')]=0;
		else count[$(this).prev().prev().attr('name')]++;
		//funcionalitat
		
		$(this).next().append('<li><input type="hidden" name="'+$(this).parent().find('textarea').attr('name')+'['+$(this).prev().val()+']['+$(this).parent().find('input:hidden').length+']" value="'+$(this).parent().find('textarea').val()+'" />'+$(this).parent().find('textarea').val()+' ('+$(this).prev().val()+') <a href="" class="delete">eliminar</a></li>');
		//$(this).next().append('<li><input type="hidden" name="'+$(this).parent().find('textarea').attr('name')+'['+$(this).parent().find('select').attr('value')+']['+$(this).parent().find('input:hidden').length+']" value="'+$(this).parent().find('textarea').val()+'" />'+$(this).parent().find('textarea').val()+' ('+$(this).parent().find('select').val()+') <a href="" class="delete">eliminar</a></li>');
		$(this).next().after('');
		$(this).prev().prev().val('');
		return false;
	});
	
	//delete_items from add_boxes
	$(".add_box a.delete").live("click", function(e){
		e.preventDefault();
		$(this).parent().remove();
		return false;
	});
	
	//acordion multilanguage
	$('.accordion p').click(function() {
		$(this).next().slideToggle('slow');
		$(this).next().css({'margin':'0 0 10px 12px'});
		return false;
	}).next().hide();
	
	//autocomplete
    /*  
    var availableTags = ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby", "python", "c", "scala", "groovy", "haskell", "perl"];
	$(".autocomplete").autocomplete({
		source: availableTags
	});
    */

    $('.form_material_manufacturer .autocomplete').autocomplete({
        delay: 0,
        source: function(request, response) {
            $.post('/materialmanufacturersuggest',{name: $('.form_material_manufacturer .autocomplete').val()},
                    function(data){
                        //if(data!='') $(".search_autocomplete").attr('disabled', 'disabled');
                        if(data=='') {
                     	    var name = $('.autocomplete').val();
                            $('form')[0].reset();
                            $('.autocomplete').val(name);
                            $('input, textarea, select').removeAttr('disabled');
                            $('input#id').val('').attr('disabled', 'disabled');
                        }
                        //$(".search_autocomplete").removeAttr('disabled');
                        response(data);
                    }, "json");
        },
        
        close:  function (event, ui) {
            if($(".autocomplete").val().length > 0) {
           	    var name = $('.autocomplete').val();
                $('form')[0].reset();
                $('.autocomplete').val(name);
                $('input, textarea, select').removeAttr('disabled');
                $('input#id').val('').attr('disabled', 'disabled');
            }
            //$(".search_autocomplete").removeAttr('disabled');
        },

        select: function (event, ui) {
            $.ajax({
               type: "POST",
               url: "/materialmanufacturerassign",
               dataType: "json",
               data: 'name='+ui.item.value+'&id='+ui.item.id,
               success: function(data){
                  $.each(data, function(i,item){
                    if (item.value != '') {
                        $(".form_material_manufacturer #"+item.key).val(item.value); 
                    }
                  });
                  
                  $('input, textarea, select').attr('disabled', 'disabled');
                  $('input#submit, input#id, input#name, .autocomplete').removeAttr('disabled');
                  $('textarea.comment').removeAttr('disabled');
               }
            });
        }
    });     
    
    $('.form_material_retailer .autocomplete').autocomplete({
        delay: 0,
        source: function(request, response) {
            $.post('/materialretailersuggest',{name: $('.form_material_retailer .autocomplete').val()},
                    function(data){
                        //if(data!='') $(".search_autocomplete").attr('disabled', 'disabled');
                        if(data=='') {
                            var name = $('.autocomplete').val();
                            $('form')[0].reset();
                            $('.autocomplete').val(name);
                            $('input, textarea, select').removeAttr('disabled');
                            $('input#id').val('').attr('disabled', 'disabled');
                        } 
                        //$(".search_autocomplete").removeAttr('disabled');
                        response(data);
                    }, "json");
        },

        close:  function (event, ui) {
            if($(".autocomplete").val().length > 0) {
                var name = $('.autocomplete').val();
                $('form')[0].reset();
                $('.autocomplete').val(name);
                $('input, textarea, select').removeAttr('disabled');
                $('input#id').val('').attr('disabled', 'disabled');
            }
            
            //    $(".search_autocomplete").removeAttr('disabled');
        },
        
        select: function (event, ui) {
            $.ajax({
               type: "POST",
               url: "/materialretailerassign",
               dataType: "json",
               data: 'name='+ui.item.value+'&id='+ui.item.id,
               success: function(data){
                  $.each(data, function(i,item){
                    if (item.value != '') {
                      $(".form_material_retailer #"+item.key).val(item.value); 
                    }
                  });
                  
                  $('input, textarea, select').attr('disabled', 'disabled');
                  $('input#submit, input#id, input#name, .autocomplete').removeAttr('disabled');
               }
            });
        }
    });     
    	
    // habilitamos el form en el caso de que llegue desde un post con contenido
    if($(".autocomplete").length) {
    	if(($(".autocomplete").val().length > 0) && ($('input#id').val()=='')) {
            $('input, textarea, select').removeAttr('disabled');
            $('input#id').val('');
        }
        else {
            $(".search_autocomplete").attr('disabled', 'disabled');
        }
    }
	
    //textarea en tabs
    //posició elements i decoració
    $('.tabs p, .tabs ol').css({'position':'absolute'});
    $('.tabs ol').hide();
    $('.tabs :nth-child(2)').show();
    var idiomes=$('.tabs:first').children('ol').length;
    $('.tabs').find('p').each(function(index){
        $(this).addClass('tab');
        lang_index=index%idiomes
        if (lang_index==0) $(this).addClass('selected');
        $(this).css({'margin-left':(350+lang_index*80)+'px'});
    });
   
    //funcionalitat tabs
    $('.tabs p').click(function(){
        var tab_index=($(this).index())/2;
        $(this).parent().find('ol').hide();
        $(this).next().show();
        $(this).parent().find('p').removeClass('selected');
        $(this).parent().find('p:eq('+tab_index+')').addClass('selected');
    });
    
    //Ocultar/Mostrar Tips
    $('.tip').hide();
    $('a.ico-tip').html("");
    $('a.ico-tip').click(function(e){
    		e.preventDefault();
    		e.stopPropagation();
    		
    		$(".tip").slideUp('slow',function(){
                $(this).remove();        
            });
    		//construim capa
    		var title = $(this).attr("title");
    		$("body").append('<div class="tip"><a class="right"><img src="../css/images/ico-close.gif" /></a><p>'+title.replace(/:/gi, '<br />')+'</p></div>');
    		$(".tip").hide();
    		$(".tip").css({"top":e.pageY,"left":e.pageX});
    		$(".tip").slideDown();
    });
    $('.tip a').live('click',function(){
    		$(this).parent().slideUp('slow',function(){
    			$(".tip").remove();	
    		});
    		
    });

    $('.material').hover(function(){  
        $(".cover", this).stop().animate({top:'0px'},{queue:false,duration:300});  
    }, function() {  
        $(".cover", this).stop().animate({top:'157px'},{queue:false,duration:300});  
    });
    
   //sliders
    $('.slider_datos').hide();
    
    //array per guardar valors anteriors
    var prevSlider=[0,6];    
    
    $("#filter .datos_empiricos").slider({
		     range: true,
		     min: 0,
		     max: 6,
		     values: [0,6],
		     start: function(event,ui) {
		     	 
			     $(this).find('a').each(function(e){
			    	 $(this).before('<div style="position:absolute;top:-25px;border:1px solid #fc0;background:#ffc;padding:2px 3px;" class="slider_dialog"></div>');
			     });
			     
			     datos=$(this).parent().find('ul.slider_datos li');
			     dialog=$(this).find('.slider_dialog');
			     dialog.eq(0).css('left',((ui.values[0]*25)-10)+'px').html(ui.values[0]);
			     dialog.eq(1).css('left',((ui.values[1]*25)-10)+'px').html(ui.values[1]);
		     },
		     slide: function(event, ui) {
			     
			     
			     //reinici dels sliders si el primer handle es posa a 0 o el segon handler es posa a 6
			     actualSlider = $(this).closest("dd").find(".datos_empiricos");
			     
			     if (ui.values[0]==0  && prevSlider[0]!=0) {
			     		actualSlider.slider ("values",1,6);
			     		ui.values[1]=6;
			     		}
			     else if (ui.values[1]==6 && prevSlider[0]==0) {
			     		actualSlider.slider ("values",1,5);
			     		ui.values[1]=5;
			     		}
			     if (ui.values[1]==6 && prevSlider[1]!=6) {
			     		actualSlider.slider ("values",0,0);
			     		ui.values[0]=0;
			     		}
			     else if (ui.values[0]==0 && prevSlider[1]==6) {
			     		actualSlider.slider ("values",0,1);
			     		ui.values[0]=1;
			     		}
			     		
			     prevSlider=ui.values;
			     
			     datos=$(this).parent().find('ul.slider_datos li');
			     rangeMin =$(this).parent().find('.range .min');
			     rangeMax =$(this).parent().find('.range .max');
			     rangeMin.val(ui.values[0]).next().text(datos.eq(ui.values[0]).text());
			     rangeMax.val(ui.values[1]).next().text(datos.eq(ui.values[1]).text());
			     
			     dialog=$(this).find('.slider_dialog');
			     dialog.eq(0).css('left',((ui.values[0]*25)-10)+'px').html(ui.values[0]);
			     dialog.eq(1).css('left',((ui.values[1]*25)-10)+'px').html(ui.values[1]);
			     
			     
			     //Ocultar els inputs min i max quan els valors estiguin a 0 i 6.
			     if (ui.values[0]==0) rangeMin.hide();
			     else rangeMin.show();
			     
			     if (ui.values[1]==6) rangeMax.hide();
			     else rangeMax.show();
			     
		     },
		     stop: function() {
			     $(this).parent().find('.range .min').change();
			     $('.slider_dialog').remove();
			 }
	     }
    ); 
    
    //canvi estils dels primers slide-handlers
    $(".ui-slider").each(function(e){
     $(this).find(".ui-slider-handle:first").addClass("first");
     $(this).find(".ui-slider-handle:last").addClass("last");
    }); 
    
    
    $("#filter .datos_empiricos").each(function(e){
    	var range_min=$(this).parent().find('.range .min').val();
    	var range_max=$(this).parent().find('.range .max').val();
    	//alert(range_max);
    	$(this).slider ({values:[range_min,range_max]});
    	
    	//mostrem els textes al costat dels valors iniciats
    	datos=$(this).parent().find('ul.slider_datos li');
    	rangeMin =$(this).parent().find('.range .min');
		rangeMax =$(this).parent().find('.range .max');

    	rangeMin.next().text(datos.eq(range_min).text());
		rangeMax.next().text(datos.eq(range_max).text());
		
		//Ocultar els inputs min i max quan els valors estiguin a 0 i 6.
		if (rangeMin.val()==0) rangeMin.hide();
		else rangeMin.show();
			     
		if (rangeMax.val()==6) rangeMax.hide();
		else rangeMax.show();
    });

        	
    //Desplegar formularios
    $("#filter legend").siblings().not(':first').hide();
    
    //$("#b_avanzada legend").siblings().show();
    //$("fieldset dd").hide();
    $("fieldset dd.down").hide();
    
    $("#filter legend").click(function(){
    	$(this).toggleClass('up','down');
    	$(this).siblings().not(".datos_reales, .tip").slideToggle();
    });

     
    $("fieldset dt.down").click(function(){
    	$(this).toggleClass('up','down');
    	$(this).next().slideToggle();
    });
    
    //Desactivar filtres si es busca per còdig o fabricant (inicilialització)
    if (select_type_search.val()!=0) $("#filter fieldset:not(:first)").slideUp();
    
    //Desactivar o activar filtres segons es busqui per material, còdig o fabricant
   select_type_search.change(function(){
    	if (select_type_search.val()==0) $("#filter fieldset:not(:first)").slideDown();
    	else $("#filter fieldset:not(:first)").slideUp();
    	});


    //cambiar de empírico a real
    $("#filter .datos_reales").hide();

    $("#filter a.a_empirico").click(function(e) {
    	e.preventDefault();
    	if (!$(this).hasClass("a")) {
    		if (confirm ("Se perderán los datos reales al cambiar a valor empírico ¿Quieres continuar?")) {
    			//buidar camps
    			$(this).closest("dd").find(".datos_reales input").each(function(){
    				$(this).val("");
    			});
    			$(this).closest("dd").find(".datos_reales").hide();
    			$(this).closest("dd").find(".datos_empiricos").show();
    			$(this).closest("dd").find(".range").show();
    			$(this).closest("dd").find('input[name$="_type"]').val('0');
    			$(this).parent().find("a.a_real").removeClass("a");
    			$(this).addClass("a");
    			$(this).closest("dd").find("p:eq(1)").show(); //tornem a mostrar el <p>Valor [?]</p>
    		}
    	}
    	return false;
    });

    $("#filter a.a_real").click(function(e) {
    	e.preventDefault();
    	if (!$(this).hasClass("a")) {
            if (confirm ("Se perderán los datos empíricos al cambiar a valor reales ¿Quieres continuar?")) {
                //buidar camps
                datos = $(this).parent().parent().find('ul.slider_datos li');

                rangeMin =$(this).parent().parent().find('.range .min');
                rangeMax =$(this).parent().parent().find('.range .max');
                rangeMin.val(0).next().text(datos.eq(0).text());
                rangeMax.val(6).next().text(datos.eq(6).text());
                rangeMin.hide();
                rangeMax.hide();
                
                $(this).closest("dd").find(".range input.min").val("0");
                $(this).closest("dd").find(".range input.max").val("6");
                $(this).closest("dd").find(".datos_empiricos").hide();
                $(this).closest("dd").find(".datos_empiricos").slider ({values:[0,6]});
                $(this).closest("dd").find(".range").hide();
                $(this).closest("dd").find("p:not(:eq(0))").hide();
                $(this).closest("dd").find("p:last").show();
                $(this).closest("dd").find(".datos_reales").show();
                $(this).closest("dd").find('input[name$="_type"]').val('1');
                $(this).parent().find("a.a_empirico").removeClass("a");
                $(this).addClass("a");
            }
    	}
    	return false;
    }); 
    

    //mostar formulario valor real si no hay valor empírico y añadir clase "a"
    $("#filter .datos_reales").each(function(){
    	
    	if ($(this).parent().find('a.a_empirico').length==0) {
    		$(this).show();
    		$(this).prev().find("a").addClass("a");
    	}
    });
    
    //detectar si hi ha camps actius després de la cerca
    
    $('input[name^="has_"]').each(function(e){
    	if ($(this).val()==1) {
    		//desplegar filtres
    		$(this).parent().find('legend').toggleClass('up','down');
    		$(this).siblings().show();
    	}
    });

    $('input[name^="set_"]').each(function(e){
        if ($(this).val()==1) {
        //desplegar filtres
        $(this).parents().show();
        $(this).parent().next().show();
        $(this).closest('fieldset').find('legend').siblings().show();
        }
    }); 
    
    //detectar si està filtrat per valors empírics o reals després d'una cerca
    $('input[name$="_type"]').each(function(e){
    	if ($(this).val()==1) {
    		//mostrar valor real
    		$(this).parent().parent().find(".datos_empiricos").hide();
    		$(this).parent().parent().find(".datos_reales").show();
    		$(this).parent().find("a.a_empirico").removeClass("a");
    		$(this).parent().find("a.a_real").addClass("a");
    		$(this).closest("dd").find("p:not(:eq(0))").hide();
    	}
    }); 
    
    //seleccionar todos los valores
    $("#filter ol :checkbox").click(function(){
    	if ($(this).is(':checked')){
    		$(this).parent().next().find('input:checkbox').attr('checked',true);
    		if ($(this).parent().parent().parent().find('input').length == $(this).parent().parent().parent().find('input:checked').length) { //marcar checkbox pare en el cas de que estiguin tots els fills marcats
    			$(this).parent().parent().parent().parent().find('input:checkbox:first').attr('checked',true); 
    		}
    		}
    	else {
    		$(this).parent().next().find('input:checkbox').attr('checked',false);
    		if ($(this).parent().parent().parent().is('ul')) { //treure checkbox dels pares en cas de deseleccionar un fill.
    			$(this).parent().parent().parent().parent().find('input:checkbox:first').attr('checked', false);
    		}
    	}
   
    	searchMaterials();
    });

    //feedback visual "aplicar filtro"
    $('input, select').change(function(){
    	$(this).closest("fieldset").find(".aplicar").addClass("a");
    });

    //Búsqueda avanzada
    $('#b_avanzada fieldset,#b_avanzada h3,#b_avanzada h4').hide();
    var b_avanzada=$('#b_avanzada h2');
    b_avanzada.addClass("down");
    b_avanzada.click(function(){
    	$(this).toggleClass('up','down');
    	$('#b_avanzada fieldset,#b_avanzada h3').slideToggle();
    });

    //filter_more
    $('.view_more').hide();
    $('.more').click(function(){
    	$('div.view_more').slideToggle();
    });
    
    //funcionalitats thumbs llistats
    $('.material')
    	.hover(function(){  
	        $(".cover", this).stop().animate({top:'0px'},{queue:false,duration:300});  
	    	}, function() {  
        	$(".cover", this).stop().animate({top:'157px'},{queue:false,duration:300});  
		    });
    
    $(".guardar").colorbox({width:"50%", inline:true, close: "close", href:"#savesearch"});
    
    $("#recordExample").colorbox({width:"570px", inline:true, close: "close", href:"#fullrecordexample"});
    
    // funcionalidad iconos listados
    $("#thumb_container .icons img.twitt").click(function(e){ 
        e.preventDefault(); 
        var url_twitter = "http://twitter.com/share";
        var url=url_twitter+"?url="+$(this).attr("rel")+"&text="+$(this).attr("alt"); 
        window.open(url); 
    }); 
       
    $("#thumb_container .icons img.faceb").click(function(e){ 
        e.preventDefault();  
        var url_facebook= "http://www.facebook.com/sharer.php"; 
        var url=url_facebook+"?u="+$(this).attr("rel")+"&t="+$(this).attr("alt"); 
        window.open(url); 
    });
    
  //submenús
    $('ul#submenu').hide();
    $('a#menu_administracion').mouseover (function(){
     $('ul#submenu').slideDown();
    });
    $('#menu_administracion').closest('li').mouseleave (function(){
     $('ul#submenu').slideUp();
     $('a#menu_administracion').removeClass('current');
    }); 
    $('ul#submenu').mouseover (function(){
    	$('a#menu_administracion').addClass('current');
    });
    
    $('a#menu_servicios').mouseover (function(){
        $('ul#submenu_servicios').slideDown();
       });
       $('#menu_servicios').closest('li').mouseleave (function(){
        $('ul#submenu_servicios').slideUp();
        $('a#menu_servicios').removeClass('current');
       }); 
       $('ul#submenu_servicios').mouseover (function(){
       	$('a#menu_servicios').addClass('current');
       });
       
    //alerta cerca deshabilitada
    var type_search=$('#type_search');
    //detectem si està logat
    if ($('p#userbox span:first').text().indexOf(",")=="-1") {
    	$('#type_search option[value="2"]').prepend('*');
    	$('#type_search option[value="2"]').css('color','#cacaca');
	    
	    type_search.change(function(){
	    	if (type_search.val()==2){
		    	type_search.val("0");
		    	$('form#search p:last').slideDown();
		    	$('li.message_logged').slideDown();
	    	}
	    	return false;
	    });
    }
    
    //definició elements
    var select_type_search=$("select#type_search");

    //Desactivar filtres si es busca per còdig o fabricant (inicilialització)
    if (select_type_search.val()!=0) $("#filter fieldset:not(:first)").slideUp();

    //Desactivar o activar filtres segons es busqui per material, còdig o fabricant
    select_type_search.change(function(){
     if (select_type_search.val()==0) $("#filter fieldset:not(:first)").slideDown();
     else $("#filter fieldset:not(:first)").slideUp();
    });

    
    //control desplegables fitxa material
    $('div.mat_details_box').hide();
    $('#layout_mat a.minimized').live('click',function(e){
    	e.preventDefault();
    	$(this).toggleClass('minimized extended');
    	
        $(this).siblings().slideDown();
    });
    
    $('#layout_mat a.extended').live('click',function(e){
	    e.preventDefault();
	    $(this).toggleClass('minimized extended');
    	
        $(this).siblings().slideUp();
    });


    $('#comments_mat').hide();
    $('#tab_comments_material').click(function(){
    	$("#content_mat").hide();
        $("#mat_images").hide();
        $('#comments_mat').show();

        $('#tab_data_material').removeClass("selected");
        $(this).addClass("selected");

    	
    });

    $('#tab_data_material').click(function(){
    	$("#comments_mat").hide();
        $('#content_mat').show();
        $("#mat_images").show();
        $('#tab_comments_material').removeClass("selected");
        $(this).addClass("selected");

    });

    // Slide de la home
    $("#slider").easySlider({
        prevText:'',
        nextText:''
    });

    return false;
});

function dropFilter(filter) {
	$('#drop_filter').attr('value', filter);
	if (($('#' + filter + 'min').attr('type') == 'text') && ($('#' + filter + 'min').attr('class') == 'min')) {
		//alert($('#' + filter + 'min').parent().parent().html());
		$('#' + filter + 'min').attr('value', 0);
		$('#' + filter + 'max').attr('value', 6);
		$('#' + filter + 'min').parent().parent().find(".datos_empiricos").slider ({values:[0,6]});
	} else if (($('#' + filter + 'min').attr('type') == 'text') && ($('#' + filter + 'min').attr('class') == 'numeric')) {
		$('#' + filter + 'min').attr('value', '');
		$('#' + filter + 'max').attr('value', '');
		//alert($('#' + filter).parent().find('input').attr('id'));
	}
	searchMaterials();
}

function rateMaterial(id_material, uri) {
	if (uri == undefined) return false;
        if (!id_material) return false;

        
	$.post(uri, { id: id_material, rate: $('#select_ratings').val() }, function(data) {

		if (data.error >= 0) {
                    $('#rate, #mat_votes').fadeOut("slow");
                    $('#rate' + data.last_rate).hide();
                    var txt_votos = 'votos';
                    if (data.votes == 1) {txt_votos = 'voto';}
                    $("#mat_votes").html(data.votes + ' ' + txt_votos);
                    $('#mat_votes, #rate' + data.rate).fadeIn("slow");
		} else {
			uri = data.redirect;
			location.href = data.redirect;
		}

	},"json");
}

function searchMaterials(action) {
	if (action) {
		$('#filter').attr('action', action);
	}
	$('#filter').submit();
}

function addToFavorites(elem, uri, hide){
	
	var id = $(elem).attr("id");
	id = id.split('_');
	id = id[1];
	
	if (uri == undefined) return false;
		
	$.post(uri,"",function(data) {
			
		if (data.error >= 0) {
			if (data.valid == 1) {
				$("#addtofavorites_"+id).hide();
				$("#delfromfavorites_"+id).show();
			} else {
				$("#delfromfavorites_"+id).hide();
				$("#addtofavorites_"+id).show();
			}
			
			$("#totalfavorites").html('(' + data.total + ')');
			
			if (hide == '1') {	
				$("#mat-"+id).fadeOut("slow");
			}
		} else {
			uri = data.redirect;
			location.href = data.redirect;
		}
	
	},"json");
}

function saveSearch() {
	if ($.trim($("#title").attr('value')) == '') {
		alert('Debes ponerle un nombre a tu búsqueda');
	} else {
		$('#savesearch').prepend('<img src="/css/images/loading.gif" />');
		$('#savesearch img').css('margin','30px 250px').siblings().hide();
		
		$.post($('#filter').attr('action'), {title: $("#title").attr('value'), filters: $("#filters").attr('value'), fdata: $("#filter").serialize()} ,function(data) {
			if (data.error == 0) {
				$('#title').attr('value', '');
				$('#savesearch').html('<div class="empty"><p class="green">La búsqueda se ha guardado correctamente.</p></div>');
				$("#totalsearches").html('(' + data.total + ')');
			} else {
				$('#savesearch').html('<div class="empty"><p class="red">Ha ocurrido un error. Por favor, vuélvelo a intentar.</p></div>'); 
			}
		},"json");
	}
}

function returnToResults() {
    $('#backform').submit();
}

function prompt(accion,cosa) {
	if (!confirm('¿Seguro quieres '+accion+' este '+cosa+'?')) return false;	
}

//scroll visor thumbnails fitxa material
$(function() {
	
	//scrollpane parts
	var scrollPane = $( ".scroll-pane" ),
		scrollContent = $( ".scroll-content" );
		
	//comptar thumbnails
	var thumbnails=scrollContent.find("img").length;
	
	//build slider
	scrollContent.width(thumbnails*105); //l'alçada del scroll depen de quants elements hi caben dins del content.
	
	var scrollbar = $( ".scroll-bar" ).slider({
		slide: function( event, ui ) {
			if ( scrollContent.width() > scrollPane.width() ) {
				scrollContent.css( "margin-left", Math.round(
					ui.value / 100 * ( scrollPane.width() - scrollContent.width() )
				) + "px" );
			} else {
				scrollContent.css( "margin-left", 0 );
			}
		}
	});
	
	//append icon to handle
	var handleHelper = scrollbar.find( ".ui-slider-handle" )
	.mousedown(function() {
		scrollbar.width( handleHelper.width() );
	})
	.mouseup(function() {
		scrollbar.width( "100%" );
	})
	.append( "<span class='ui-icon ui-icon-grip-dotted-vertical'></span>" )
	.wrap( "<div class='ui-handle-helper-parent'></div>" ).parent();
	
	//change overflow to hidden now that slider handles the scrolling
	scrollPane.css( "overflow", "hidden" );
	
	//size scrollbar and handle proportionally to scroll distance
	function sizeScrollbar() {
		var remainder = scrollContent.width() - scrollPane.width();
		var proportion = remainder / scrollContent.width();
		var handleSize = 60;
		scrollbar.find( ".ui-slider-handle" ).css({
			width: handleSize,
			"margin-left": -handleSize / 2
		});
		handleHelper.width( "" ).width( scrollbar.width() - handleSize );
	}
	
	//reset slider value based on scroll content position
	function resetValue() {
		var remainder = scrollPane.width() - scrollContent.width();
		var leftVal = scrollContent.css( "margin-left" ) === "auto" ? 0 :
			parseInt( scrollContent.css( "margin-left" ) );
		var percentage = Math.round( leftVal / remainder * 100 );
		scrollbar.slider( "value", percentage );
	}
			
	//if the slider is 100% and window gets larger, reveal content
	function reflowContent() {
			var showing = scrollContent.width() + parseInt( scrollContent.css( "margin-left" ), 10 );
			var gap = scrollPane.width() - showing;
			if ( gap > 0 ) {
				scrollContent.css( "margin-left", parseInt( scrollContent.css( "margin-left" ), 10 ) + gap );
			}
	}
			
	//change handle position on window resize
	$( window ).resize(function() {
		resetValue();
		sizeScrollbar();
		reflowContent();
	});

	//init scrollbar size
	setTimeout( sizeScrollbar, 10 );//safari wants a timeout
	
	//eliminar barra si hi ha menys de 3 imatges
	if (thumbnails<3) $(".scroll-bar-wrap").remove();
	
	//funcionalitat de carregar imatge principal
	$ (".scroll-content a").click(function(e){
		e.preventDefault();
		thumbnail=$(this).attr("href");
		$("#mat_pimage img").attr("src",thumbnail);
	});
	
	$(".procesar").click(function(event){
		$('body').css('cursor', 'wait');
		$.ajax({
			  type: 'POST',
			  url: "/procesar-pago-transferencia",
			  data: {
				  id: $(this).parent().attr('id')
			  },
			  success: function (data) {
				  if (data['status'] == 'ok'){
					  $("#pay_"+data['id']).replaceWith(data['html']);
				  }
				  $('body').css('cursor', 'auto');
			  },
			  error: function (data) {
				  alert('No se ha podido procesar la petición');
				  $('body').css('cursor', 'auto');
			  }
			});
		event.preventDefault();
	});
});
