
$(document).ready(function()
{
	position_site();
    
    $('.div_pesquisa_txt').bind('click',function(){ if( $("#pesquisa1").val() != '' ){ $(this).parent().parent().submit();} });
    $(".div_banner *").live({'click':function(e){e.stopPropagation();}});   
    
    if($(".selectProduct").size() > 0){
    
    	$(".selectProduct[id]").live('click',function(){
        	var flag = false;
        	$('.panelOptional').hide();
            
            var cat = $(".selectProduct:checked:first").attr('rel');
            $(".selectProduct:checked").each(function(){ if($(this).attr('rel') != cat){  flag = true;  $(this).attr('checked',false)}  });
            if(flag) { alert('Impossivel unir porque existe produtos de areas diferentes!');  }
            
        	if($(".selectProduct:checked").size() > 1){
            	
                
            	$('.panelOptional').show();
            }
        });
  
    	createOptionalPanel();
    } 
});

function createOptionalPanel(){
	var dS = $('.div_site').outerWidth(true),
    	ww = parseFloat($(window).width()),
		sw = 980,
		sobra = (ww-980)/2,
        left = sw + sobra + 20;
    
    $('.div_site').css("position","relative");
    
    var panel = $("<div/>",{'class':'panelOptional'}),
    	bound = $("<div/>",{'class':'boundaryOptional'}),
    	icon  = $("<div/>",{'class':'iconPanel'}),
        label  = $("<div/>",{'class':'labelPanel'});
    
    panel.css({
   		position:'fixed',
        top: '273px',
        left: left,
        background: '#eeeeee',
        'border': '1px solid #cccccc',
        'border-radius': '5px',
        'box-shadow': '1px 1px 6px #333333, -1px -1px 6px #333333',
        'display':'none'
    });
    
    icon.css({
        width: '40px',
        height: '40px',
        border: '1px solid #ccc',
        'border-radius': '20px',
        'background':'#DDDDDD url(../templates/sync.gif) no-repeat center'
   	}).appendTo(bound);
    
    label.css({
        'text-align': 'center'
   	})
	.html('Unir Rel.')
    .appendTo(bound);
    
    bound.css({
    	padding: '10px',
        cursor: 'pointer'
    });
    
    bound
    .attr('id','unirRelacoes')
    .bind('click', fnUnirRelacoes)
    .appendTo(panel);
    
    /* var cl = bound.clone();
    cl
    .attr('id','apagarProdutos')
    .bind('click', fnUnirRelacoes)
    .appendTo(panel);
	*/
    
    $('.div_site').append(panel);
}

function fnUnirRelacoes( event ){
	event.stopPropagation();
    
	$.ajax({
      type: "POST",
      url: site_path + 'backoffice/produtos/ajax/produtos_familias.php',
      data: $(".selectProduct:checked").serialize() + "&fo=1&Form=uneRelacoes&catalogo="+$(".selectProduct:checked:first").attr('rel'),
      dataType: 'json',
      cache: false
    }).done(function( json ) {
      if(json.success){
      	alert( json.msg );
        $(".selectProduct:checked").each(function(){
        	if( $(this).val() != json.Product) $(this).parent().parent().remove();
        });
        $(".selectProduct:checked").removeAttr('checked')
        //window.location.reload();
      }else{
      	alert( json.msg );
      }
    });

}

function updateButton(response) {
	var button = document.getElementById('fb-auth');
	
	/*if (response.authResponse) {
	    button.innerHTML = 'Logout';
	    button.onclick = function() {
	        FB.logout(function(response) { 
            	console.log("LOG OUT");
            	window.loaction = site_path; 
            });
	    };
	} else {*/
	  //user is not connected to your app or logged out
	  $("#fb-auth").bind('click', function() {
	    FB.login(function(response) {
	      if (response.authResponse) {
         	 setTimeout(window.location = site_path + "registo/registo_trata.php?do=FB", 1000);
	      }
	    }, {scope:'email,user_birthday,user_location'});  	
	  });
	//}
}

function position_site()
{
	/*SÓ É ACTIVADO QUANDO O AMBIENTE ESTIVER ACTIVO*/
    if($('.div_site').length)
    {
    	var ww = parseFloat($(window).width()),
		sw = 980,
		sobra = (ww-980)/2;
    	$("body").live({'click':function(e)
		{
			var click = e.pageX;
            
            if( ( click < sobra || click > (sw + sobra) ) && click > 0){
            	if($('.div_bg').hasClass('source')){window.open(urlaf,"_blank");}
            }
        },
        'mousemove':function(e)
		{
        	var click = e.pageX;
			if($('.div_bg').hasClass('source'))
			{
				if( click < sobra || click > (sw + sobra) )$("body").css('cursor','pointer');
				else $("body").css('cursor','auto');
			}
		}});
    }
}

function verifySearch(){
	var p = document.getElementById('pesquisa1');
    if($("#pesquisa1").val() == ""){ $("#pesquisa1").focus(); return false; }
    return true;
}

if(jQuery !== undefined){
	(function($){
		
		var methods = {
			create: function( options ){
				
				var defaults = {	
					form: '#form_login',
					formLocation: site_path + 'registo/ajax/createlogin.php'
				};
				
				if ( options ) {  $.extend( defaults, options ); }
				
				return this.each(function(){
						
					var _this = $(this);
					
					if($(defaults.form).length)
						$(defaults.form).remove(); /* Previne replicaçao de informaçao */
                     var js = '';
					if(defaults.withJS) js = '{js:1}';
					$.post(defaults.formLocation,js, function( html ){
						_this.append(html);
						_this.login('login', options);
						_this.login('forgot');
					}); 			
				});
			},
			login: function( options ){
				var defaults = {	
					form: '#form_login',
					loginButton: '#doLogin',
					urlSubmit: site_path + 'registo/ajax/doLogin.php',
					goTo: '/',
					boundary: '.login_from_boundary',
                    onComplete: function(){},
					messages: {
						required: "Campo Obrigatorio.",
						email: "Insira um email valido",
						password: {
							required: "Insira Password"
						}
					}
				};
				var _this = $(this);
				if ( options ) {  $.extend( defaults, options ); }
				
				return this.each(function(){
                	
					$(defaults.form).validate({
						messages: {
							required: defaults.messages.required,
							email:  defaults.messages.email,
							password: {
								 required: defaults.messages.password.required
							}
						},
						submitHandler: function(form) {
							$.ajax({
							   type: "POST",
							   url: defaults.urlSubmit,
							   data: $(defaults.form).serialize(),
							   cache: false,
							   dataType: 'json',
							   success: function(msg){
								   
								   if(msg == 'false' || !msg || msg == false){
									_this.login('error',{
										form: 	defaults.form,
										boundary: defaults.boundary 
									});
								   }else{
                                   		defaults.onComplete();
	                                   if(defaults.goTo != '')
										 window.location = defaults.goTo;
								   }
							   }
							 });
						},
						onkeyup:false
						
					});
					
					$( defaults.loginButton ).bind('click', function(){ $(defaults.form).submit(); })
					
				});
			},
			forgot: function( options ){
				var defaults = {	
					form: '#form_login',
					boundary: '.forgot-boundary',
					boundaryName:'forgot-boundary',
					overlay: '.forgot-overlay',
					overlayName: 'forgot-overlay',
					forgotButton: '.forgot-link',
                    goTo: site_path
					
				};
				if ( options ) { $.extend( defaults, options ); }
				
				return this.each(function(){
					var _this = $(this);
					$(defaults.forgotButton).live({
						click: function(){
							
							if(!$(defaults.overlay).length) $('body').append($('<div />',{'class':defaults.overlayName}));
							if(!$(defaults.boundary).length) $('body').append($('<div />',{'class':defaults.boundaryName}));
							
							var w = $(window).width(),
								h = $(window).height();
								
							$(defaults.overlay).width(w).height(h).show(100, function(){ $(this).animate({opacity: .5}, 2);});
	
							$(defaults.boundary)
								.append("<div class='div_img_home forgot-back-top'><!-- --></div>")
								.append("<div class='clear'></div><div class='div_img_home forgot-back-bottom'><!-- --></div>");
						
							$('.forgot-back-top')
								.append("<div class='forgot-title'>Recuperar Password</div>")
								.append("<div class='forgot-content'><!-- --></div>")
								.append("<div class='forgot-buttons'><!-- --></div>");
			
							$('.forgot-content').append('<div align="left" class="subtitle">Esqueceu a sua password</div><div class="field_boundary"><div class="left div_img_home field"><input type="text" name="forgot-email" id="forgot-email" class="required email" tabindex="2" value="" placeholder="e-Mail"/></div><div class="left div_img_home field_end"><!-- --></div><div class="clear"></div></div>');
							$('.forgot-content').append('<div class="right"><div class="left field_boundary" id="doForgot" style="margin-top:16px;" onclick="$(\'#form_forgot\').submit();"><div class="left div_img_home bt_forgot">Recuperar Password</div> <div class="left div_img_home bt_forgot_end"><!-- --></div><div class="clear"></div></div></div>');
							
							$('.forgot-content').wrap('<form method="post" enctype="multipart/form-data" id="form_forgot" name="form_forgot" />');
							
							$(".forgot-boundary")
							.css({
								top: (parseInt(h/2) - parseInt($(".forgot-boundary").height()/2)) ,
								left: parseInt(w/2) - parseInt($(".forgot-boundary").width()/2)
							})
							.show();
							
							$("#form_forgot").validate({
							   messages: {
									required: "Campo Obrigatorio.",
									email: "Insira um email valido"
								},
								submitHandler: function(form) {
									$.ajax({
									   type: "POST",
									   url: '../registo/ajax/forgotPassword.php',
									   data: $("#form_forgot").serialize(),
									   cache: false,
                                       dataType: 'json',
									   success: function(msg){
										   
										   if(msg == 'false' || !msg || msg == false){
											_this.login('error',{
												form: 	defaults.form,
												boundary: defaults.boundary 
											});
                                            alert($("#message_error").val());
                                            
										   }else{
                                           	 alert($("#message_success").val());
											 window.location = defaults.goTo;
										   }
									   }
									 });
								}
								
							});
							
							//BINDS
							$(".forgot-title").append('<span class="div_img_home close" title="Close">&nbsp;</span>');
							$('.forgot-title span.close ').unbind('click');
							$('.forgot-title span.close ').bind('click',function(e){
								e.preventDefault();
						
								$(this).closest('.forgot-boundary').fadeTo('fast', 0).slideUp('fast',function(){ $(".forgot-boundary").remove(); $('.forgot-overlay').remove(); });
							});
			
						}
					});
				});
			},
			error: function(options){
				var defaults = {	
					form: '#form_login',
					boundary: ''
				};
				if ( options ) { 
					$.extend( defaults, options );
				}
				return this.each(function(){
					$(defaults.form + " input:text").val('');
					$(defaults.form + " input:password").val('');
                    $("div.message").remove();
                    if(defaults.boundary != ''){
						$(defaults.boundary).show().prepend('<div class="message error">Utilizador nao encontrado.</div>');
						$(defaults.boundary + " .title").hide();
                    }else{
                   		$('body').append('<div class="message error">Utilizador nao encontrado.</div>');
                        smallMensage();
                   }
                    
				});
				
			},
            logout: function(options){
				var defaults = {	
					form: '#form_login',
					loginButton: '#doLogout',
					urlSubmit: '../registo/ajax/doLogout.php',
					goTo: '/'
				};
				var _this = $(this);
				if ( options ) {  $.extend( defaults, options ); }
                
				return this.each(function(){
                	$(defaults.loginButton).bind('click', function(){
						$.ajax({
		                   type: "POST",
		                   url: defaults.urlSubmit,
		                   cache: false,
		                   dataType: 'json',
		                   success: function(msg){
		                   	window.location = defaults.goTo;
		                   }
		                 });
                     });
	                    
				});
				
			}
		};
		
        function smallMensage(){$('.message span.close').remove();$('.message').each(function(){if (!$(this).hasClass('no-close')) {$(this).append('<span class="div_img_home close" title="Close">&nbsp;</span>');}});$('.message span.close ').unbind('click');$('.message span.close ').bind('click',function(e){e.preventDefault();$(this).closest('.message').fadeTo('fast', 0).slideUp('fast');});}
		
		$.fn.login = function( method ) {
		
			if ( methods[method] ) {
				return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
			} else if ( typeof method === 'object' || ! method ) {
				return methods.create.apply( this, arguments );
			} else {
				$.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
			}    
			
		};	
	})(jQuery);
    
(function( $ ){

  var methods = {
    init : function( options ) {  
		var defaults={
			loading: 		'templates/kk_loading.gif',
			next: 			'next',
			previsous: 		'back',
			duration: 		200,
			elements: 		[],
			elementActive: 	0,
            iframeScroll:   'no'
		};
		
		//PREENCHE O ARRAY DE VARIAVEIS
		if ( options ) { $.extend( defaults, options ); }
			
		//Vai buscar todos os elementos e preenche o array
		methods.getObjects(this, defaults );
		
		
		return this.each(function(){
			//PREENCHE O ARRAY DE VARIAVEIS
			if ( options ) { $.extend( defaults, options ); }
			
			var _this = $(this);
		
        	
        
			//Cria o bind do click
			_this.bind('click', function(){
				try{
					methods.create(defaults);
					methods.show(_this, defaults,_this);
				}catch(e){ methods.destroy(); }
				return false;
				
			});
	
		});
		
	},
    
	getObjects: function(_this, defaults){
	
		$('.' +_this.attr('class')).each(function(){
			defaults.elements.push({
				'href': $(this).attr('href'),
				'title': $(this).attr('title'),
                'rel': $(this).attr('rel')
			});
            if($(this).attr('rel') && $(this).attr('rel')!='image') $(this).attr('title', '');
		});
	},
    standalone: function( options ){
    
    	var defaults={
			loading: 		'templates/kk_loading.gif',
			next: 			'next',
			previsous: 		'back',
			duration: 		200,
			elements: 		[],
			elementActive: 	0,
            title: 			'',
            url: 			'',
            rel: 			'iframe'
		};
		
		//PREENCHE O ARRAY DE VARIAVEIS
		if ( options ) { $.extend( defaults, options ); }
        
        defaults.elements.push({
            'href': defaults.url,
            'title': defaults.title,
            'rel': defaults.rel
        });
        
        try{
            methods.create(defaults);
            methods.show($(this), defaults,$(this));
        }catch(e){ methods.destroy(); }
    },
	create: function( defaults){
		
		$('.kk-overlay, #kk-lightbox').remove();
		$('body').append('<div class="kk-overlay"><!-- --></div>');
		$('body').append('<div id="kk-lightbox"></div>');
		
		//OVERLAY
		$('.kk-overlay').animate({opacity: 0.8}, 0);
		$('#kk-lightbox').append('<div class=" kk-topbutton"><div class="kk-sprite kk-topcloseButtonImage"></div></div>','<div class="kk-container"></div>');
		$('#kk-lightbox,.kk-overlay').css('position','fixed')
		$('.kk-container').append('<div class="kk-center"></div>');
        
        
		$('.kk-center').append( $('<img />',{ style:'display:none'} ),'<div class="kk-Loading"></div>','<div class="kk-bottombutton"></div>');

		$('.kk-center img').wrap("<div class='arrond-img'></div>");

		$('.kk-bottombutton').append(
			$('<div class="kk-title-boundary" />'),
			$('<div class="kk-buttons-boundary" />'),
			$('<div style="clear:both"></div>')
		);
		
		$('.kk-buttons-boundary').append("<div class='kk-sprite kk-prev kk-button'></div>","<div class='kk-current'></div>","<div class='kk-sprite kk-button kk-next'></div>",'<div style="clear:both"></div>');
		$('.kk-title-boundary').append("<div class='kk-title'></div>","<div class='kk-caption'></div>");

		if(defaults.elements.length<=1){
			//Bind button next e prev	
			$(".kk-buttons-boundary").hide();
		}
		
		$(window).bind('resize', methods.repostion);
        
        $('.kk-overlay').bind('click',methods.destroy );

	},
	show: function(_this, defaults, elementSelect){
		
		
		if(elementSelect!=''){	
			$.each(defaults.elements,function(i,e){
				if(e.href==elementSelect.attr('href'))
					defaults.elementActive = i;
			});
		}
		//Create Button Close	
		$('.kk-topcloseButtonImage').bind('click',methods.destroy );
		
        switch(defaults.elements[defaults.elementActive].rel){
       		
            case 'iframe': methods.iframe( _this, defaults, elementSelect ); break;
           // case 'html': break;
            case 'login':methods.lg_login(_this, defaults, elementSelect); break;
            default: methods.lg_image(_this, defaults, elementSelect); break;
       	}
		
        
		$is = defaults.elementActive;
		//Bind button next e prev	
		
        $(".kk-prev").unbind('click').bind('click', function(event){event.stopPropagation();methods.prev(_this, defaults)});
        $(".kk-next").unbind('click').bind('click', function(event){event.stopPropagation();methods.next(_this, defaults)});
		
	},
    iframe: function(_this, defaults, elementSelect){
    
      if(defaults.elements[defaults.elementActive].title){	
			$titleSlipt = defaults.elements[defaults.elementActive].title.split('::');
			if($titleSlipt[0]!='') $('.kk-title').html($titleSlipt[0]).show(); else $('.kk-title').hide();
			if($titleSlipt.length>1 && $titleSlipt[1]!='') $('.kk-caption').html($titleSlipt[1]).show(); else $('.kk-caption').hide();
            if($titleSlipt.length>2 && $titleSlipt[2]!='') $.extend( defaults, $titleSlipt[2] );
		}
        
        $is = defaults.elementActive;
		$('.kk-current').html((parseInt($is)+1)+' / '+defaults.elements.length);
        
        $('.kk-bottombutton,.kk-topbutton').hide();
		$('.kk-Loading').show();
        
       	$('.arrond-img').html('<iframe allowtransparency="yes" scrolling="'+ defaults.iframeScroll +'" frameborder="0" height="'+ defaults.height +'" width="'+ defaults.width +'" src="'+ defaults.url +'"></iframe>');       
      	
        var t = $('.arrond-img');
        t.hide();
        
        $('#kk-lightbox').css({
            width: t.outerWidth(true) + 10,
            height: t.outerHeight(true) + 40
        });
        
        var bbt = 0;
        if( defaults.elements[defaults.elementActive].title.lenght > 0) bbt = parseFloat($('.kk-bottombutton').outerHeight(true))
        
        $('.kk-container')
        .stop()
        .css('padding','10px')
        .animate({
            width: t.width(),
            height: (t.height() + bbt)-3
          }, {
            duration: defaults.duration,
            specialEasing: {
              width: 'linear',
              height: 'easeOutBounce'
            },
            complete: function() {
              $('.kk-Loading').hide(); 
              t.show();
              $('.kk-bottombutton,.kk-topbutton').show();
              $('.kk-title-boundary').css('width', t.width() - ($('.kk-buttons-boundary').outerWidth(true) + 20))
            }
          });
          
        methods.repostion(); 
      
        
    },
    lg_login: function(_this, defaults, elementSelect){
    	if(defaults.elements[defaults.elementActive].title){	
       
			$titleSlipt = defaults.elements[defaults.elementActive].title.split('::');
             
			if($titleSlipt[0]!='') $('.kk-title').html($titleSlipt[0]).show(); else $('.kk-title').hide();
			if($titleSlipt.length>1 && $titleSlipt[1]!='') $('.kk-caption').html($titleSlipt[1]).show(); else $('.kk-caption').hide();
            if($titleSlipt.length>2 && $titleSlipt[2]!='') $.extend( defaults, $titleSlipt[2] );
            
		}
        
        
        
        $is = defaults.elementActive;
		$('.kk-current').html((parseInt($is)+1)+' / '+defaults.elements.length);
        
        $('.kk-bottombutton,.kk-topbutton').hide();
		$('.kk-Loading').show();
        
       	$('.arrond-img').html('<iframe allowtransparency="yes" scrolling="no" frameborder="0" height="351" width="334" src="'+site_path+'/registo/log_iframe.php"></iframe>');       
       
       var t = $('.arrond-img');
        t.hide();
        
        $('#kk-lightbox').css({
            width: t.outerWidth(true) + 10,
            height: t.outerHeight(true) + 40
        });
        
        $('.kk-container')
        .stop()
        .css('padding','10px')
        .animate({
            width: t.width(),
            height: t.height() + parseFloat($('.kk-bottombutton').outerHeight(true))
          }, {
            duration: defaults.duration,
            specialEasing: {
              width: 'linear',
              height: 'easeOutBounce'
            },
            complete: function() {
              $('.kk-Loading').hide(); 
              t.show();
              $('.kk-bottombutton,.kk-topbutton').show();
              $('.kk-title-boundary').css('width', t.width() - ($('.kk-buttons-boundary').outerWidth(true) + 20))
            }
          });
          
        methods.repostion();  
    },
    lg_image: function(_this, defaults, elementSelect){
    
   		if(defaults.elements[defaults.elementActive].title){	
       
			$titleSlipt = defaults.elements[defaults.elementActive].title.split('::');
             
			if($titleSlipt[0]!='') $('.kk-title').html($titleSlipt[0]).show(); else $('.kk-title').hide();
			if($titleSlipt.length>1 && $titleSlipt[1]!='') $('.kk-caption').html($titleSlipt[1]).show(); else $('.kk-caption').hide();
		}
		
		
		$is = defaults.elementActive;
		$('.kk-current').html((parseInt($is)+1)+' / '+defaults.elements.length);
		
		$('.kk-bottombutton,.kk-topbutton').hide();
		$('.kk-Loading').show();
		
		$('.kk-center img')
		.hide()
		.attr('src', defaults.elements[defaults.elementActive].href)
		.load(function(){
			var t = $(this);
			
			$('#kk-lightbox').css({
				width: t.outerWidth(true) + 10,
				height: t.outerHeight(true) + 40
			});

			$('.kk-container')
			.stop()
			.css('padding','10px')
			.animate({
				width: t.width(),
				height: t.height() + 30
			  }, {
			    duration: defaults.duration,
			    specialEasing: {
			      width: 'linear',
			      height: 'easeOutBounce'
			    },
			    complete: function() {
			      $('.kk-Loading').hide(); 
				  t.show();
				  $('.kk-bottombutton,.kk-topbutton').show();
				  $('.kk-title-boundary').css('width', t.width() - ($('.kk-buttons-boundary').outerWidth(true) + 20))
			    }
			  });
			
			methods.repostion();
		});
    },
    
	next: function(_this, defaults){
		defaults.elementActive+=1;
		if(defaults.elementActive<=(defaults.elements.length-1)){		
			methods.show(_this, defaults,'');
		}
		if( defaults.elementActive> defaults.elements.length-1 )
			defaults.elementActive = defaults.elements.length-1;
	},
	prev: function(_this, defaults){
		defaults.elementActive-=1;
		if(defaults.elementActive>=0){
			methods.show(_this, defaults,'');
		}
		if(defaults.elementActive<0){
			defaults.elementActive = 0;
			
		}
	},
	repostion: function(){
		
		var h = parseFloat($(window).height()),
			w = parseFloat($(window).width()),
			lgh = parseFloat($('#kk-lightbox').outerHeight(true)),
			lgw = parseFloat($('#kk-lightbox').outerWidth(true)),
			bt = parseFloat($('.kk-topbutton').outerHeight(true));
		
		
		
		$('#kk-lightbox').css({
			top: ((h/2-lgh/2)+(75/2)),
			left: (w/2-lgw/2)+(75/2)
		});
        
        var hc = parseFloat($('.kk-container').outerHeight(true)),
        	wc = parseFloat($('.kk-container').outerWidth(true));
		
		$('.kk-Loading').css({
        	'top': (hc/2)-50,
            'left': (wc/2)-50
        })
	},
	destroy: function( event ){
    	event.stopPropagation();
		$('.kk-overlay, #kk-lightbox').remove();
	}
  };

  $.fn.kklightbox = function( method ) {
    
    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    
  
  };

})( jQuery );
    
    //Validation
	(function(c){c.extend(c.fn,{validate:function(a){if(this.length){var b=c.data(this[0],"validator");if(b)return b;b=new c.validator(a,this[0]);c.data(this[0],"validator",b);if(b.settings.onsubmit){this.find("input, button").filter(".cancel").click(function(){b.cancelSubmit=true});b.settings.submitHandler&&this.find("input, button").filter(":submit").click(function(){b.submitButton=this});this.submit(function(d){function e(){if(b.settings.submitHandler){if(b.submitButton)var f=c("<input type='hidden'/>").attr("name",
	b.submitButton.name).val(b.submitButton.value).appendTo(b.currentForm);b.settings.submitHandler.call(b,b.currentForm);b.submitButton&&f.remove();return false}return true}b.settings.debug&&d.preventDefault();if(b.cancelSubmit){b.cancelSubmit=false;return e()}if(b.form()){if(b.pendingRequest){b.formSubmitted=true;return false}return e()}else{b.focusInvalid();return false}})}return b}else a&&a.debug&&window.console&&console.warn("nothing selected, can't validate, returning nothing")},valid:function(){if(c(this[0]).is("form"))return this.validate().form();
	else{var a=true,b=c(this[0].form).validate();this.each(function(){a&=b.element(this)});return a}},removeAttrs:function(a){var b={},d=this;c.each(a.split(/\s/),function(e,f){b[f]=d.attr(f);d.removeAttr(f)});return b},rules:function(a,b){var d=this[0];if(a){var e=c.data(d.form,"validator").settings,f=e.rules,g=c.validator.staticRules(d);switch(a){case "add":c.extend(g,c.validator.normalizeRule(b));f[d.name]=g;if(b.messages)e.messages[d.name]=c.extend(e.messages[d.name],b.messages);break;case "remove":if(!b){delete f[d.name];
	return g}var h={};c.each(b.split(/\s/),function(j,i){h[i]=g[i];delete g[i]});return h}}d=c.validator.normalizeRules(c.extend({},c.validator.metadataRules(d),c.validator.classRules(d),c.validator.attributeRules(d),c.validator.staticRules(d)),d);if(d.required){e=d.required;delete d.required;d=c.extend({required:e},d)}return d}});c.extend(c.expr[":"],{blank:function(a){return!c.trim(""+a.value)},filled:function(a){return!!c.trim(""+a.value)},unchecked:function(a){return!a.checked}});c.validator=function(a,
	b){this.settings=c.extend(true,{},c.validator.defaults,a);this.currentForm=b;this.init()};c.validator.format=function(a,b){if(arguments.length==1)return function(){var d=c.makeArray(arguments);d.unshift(a);return c.validator.format.apply(this,d)};if(arguments.length>2&&b.constructor!=Array)b=c.makeArray(arguments).slice(1);if(b.constructor!=Array)b=[b];c.each(b,function(d,e){a=a.replace(RegExp("\\{"+d+"\\}","g"),e)});return a};c.extend(c.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",
	validClass:"valid",errorElement:"label",focusInvalid:true,errorContainer:c([]),errorLabelContainer:c([]),onsubmit:true,ignore:[],ignoreTitle:false,onfocusin:function(a){this.lastActive=a;if(this.settings.focusCleanup&&!this.blockFocusCleanup){this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass);this.addWrapper(this.errorsFor(a)).hide()}},onfocusout:function(a){if(!this.checkable(a)&&(a.name in this.submitted||!this.optional(a)))this.element(a)},
	onkeyup:function(a){if(a.name in this.submitted||a==this.lastElement)this.element(a)},onclick:function(a){if(a.name in this.submitted)this.element(a);else a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(a,b,d){a.type==="radio"?this.findByName(a.name).addClass(b).removeClass(d):c(a).addClass(b).removeClass(d)},unhighlight:function(a,b,d){a.type==="radio"?this.findByName(a.name).removeClass(b).addClass(d):c(a).removeClass(b).addClass(d)}},setDefaults:function(a){c.extend(c.validator.defaults,
	a)},messages:{required:"Campo Obrigatorio.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Valor errado.",accept:"Please enter a value with a valid extension.",maxlength:c.validator.format("Please enter no more than {0} characters."),
	minlength:c.validator.format("Please enter at least {0} characters."),rangelength:c.validator.format("Please enter a value between {0} and {1} characters long."),range:c.validator.format("Please enter a value between {0} and {1}."),max:c.validator.format("Please enter a value less than or equal to {0}."),min:c.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:false,prototype:{init:function(){function a(e){var f=c.data(this[0].form,"validator");e="on"+e.type.replace(/^validate/,
	"");f.settings[e]&&f.settings[e].call(f,this[0])}this.labelContainer=c(this.settings.errorLabelContainer);this.errorContext=this.labelContainer.length&&this.labelContainer||c(this.currentForm);this.containers=c(this.settings.errorContainer).add(this.settings.errorLabelContainer);this.submitted={};this.valueCache={};this.pendingRequest=0;this.pending={};this.invalid={};this.reset();var b=this.groups={};c.each(this.settings.groups,function(e,f){c.each(f.split(/\s/),function(g,h){b[h]=e})});var d=this.settings.rules;
	c.each(d,function(e,f){d[e]=c.validator.normalizeRule(f)});c(this.currentForm).validateDelegate(":text, :password, :file, select, textarea","focusin focusout keyup",a).validateDelegate(":radio, :checkbox, select, option","click",a);this.settings.invalidHandler&&c(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler)},form:function(){this.checkForm();c.extend(this.submitted,this.errorMap);this.invalid=c.extend({},this.errorMap);this.valid()||c(this.currentForm).triggerHandler("invalid-form",
	[this]);this.showErrors();return this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(a){this.lastElement=a=this.clean(a);this.prepareElement(a);this.currentElements=c(a);var b=this.check(a);if(b)delete this.invalid[a.name];else this.invalid[a.name]=true;if(!this.numberOfInvalids())this.toHide=this.toHide.add(this.containers);this.showErrors();return b},showErrors:function(a){if(a){c.extend(this.errorMap,
	a);this.errorList=[];for(var b in a)this.errorList.push({message:a[b],element:this.findByName(b)[0]});this.successList=c.grep(this.successList,function(d){return!(d.name in a)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){c.fn.resetForm&&c(this.currentForm).resetForm();this.submitted={};this.prepareForm();this.hideErrors();this.elements().removeClass(this.settings.errorClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},
	objectLength:function(a){var b=0,d;for(d in a)b++;return b},hideErrors:function(){this.addWrapper(this.toHide).hide()},valid:function(){return this.size()==0},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{c(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(a){}},findLastActive:function(){var a=this.lastActive;return a&&c.grep(this.errorList,function(b){return b.element.name==
	a.name}).length==1&&a},elements:function(){var a=this,b={};return c(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled]").not(this.settings.ignore).filter(function(){!this.name&&a.settings.debug&&window.console&&console.error("%o has no name assigned",this);if(this.name in b||!a.objectLength(c(this).rules()))return false;return b[this.name]=true})},clean:function(a){return c(a)[0]},errors:function(){return c(this.settings.errorElement+"."+this.settings.errorClass,
	this.errorContext)},reset:function(){this.successList=[];this.errorList=[];this.errorMap={};this.toShow=c([]);this.toHide=c([]);this.currentElements=c([])},prepareForm:function(){this.reset();this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset();this.toHide=this.errorsFor(a)},check:function(a){a=this.clean(a);if(this.checkable(a))a=this.findByName(a.name).not(this.settings.ignore)[0];var b=c(a).rules(),d=false,e;for(e in b){var f={method:e,parameters:b[e]};try{var g=
	c.validator.methods[e].call(this,a.value.replace(/\r/g,""),a,f.parameters);if(g=="dependency-mismatch")d=true;else{d=false;if(g=="pending"){this.toHide=this.toHide.not(this.errorsFor(a));return}if(!g){this.formatAndAdd(a,f);return false}}}catch(h){this.settings.debug&&window.console&&console.log("exception occured when checking element "+a.id+", check the '"+f.method+"' method",h);throw h;}}if(!d){this.objectLength(b)&&this.successList.push(a);return true}},customMetaMessage:function(a,b){if(c.metadata){var d=
	this.settings.meta?c(a).metadata()[this.settings.meta]:c(a).metadata();return d&&d.messages&&d.messages[b]}},customMessage:function(a,b){var d=this.settings.messages[a];return d&&(d.constructor==String?d:d[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(arguments[a]!==undefined)return arguments[a]},defaultMessage:function(a,b){return this.findDefined(this.customMessage(a.name,b),this.customMetaMessage(a,b),!this.settings.ignoreTitle&&a.title||undefined,c.validator.messages[b],"<strong>Warning: No message defined for "+
	a.name+"</strong>")},formatAndAdd:function(a,b){var d=this.defaultMessage(a,b.method),e=/\$?\{(\d+)\}/g;if(typeof d=="function")d=d.call(this,b.parameters,a);else if(e.test(d))d=jQuery.format(d.replace(e,"{$1}"),b.parameters);this.errorList.push({message:d,element:a});this.errorMap[a.name]=d;this.submitted[a.name]=d},addWrapper:function(a){if(this.settings.wrapper)a=a.add(a.parent(this.settings.wrapper));return a},defaultShowErrors:function(){for(var a=0;this.errorList[a];a++){var b=this.errorList[a];
	this.settings.highlight&&this.settings.highlight.call(this,b.element,this.settings.errorClass,this.settings.validClass);this.showLabel(b.element,b.message)}if(this.errorList.length)this.toShow=this.toShow.add(this.containers);if(this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight){a=0;for(b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass)}this.toHide=this.toHide.not(this.toShow);
	this.hideErrors();this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return c(this.errorList).map(function(){return this.element})},showLabel:function(a,b){var d=this.errorsFor(a);if(d.length){d.removeClass().addClass(this.settings.errorClass);d.attr("generated")&&d.html(b)}else{d=c("<"+this.settings.errorElement+"/>").attr({"for":this.idOrName(a),generated:true}).addClass(this.settings.errorClass).html(b||
	"");if(this.settings.wrapper)d=d.hide().show().wrap("<"+this.settings.wrapper+"/>").parent();this.labelContainer.append(d).length||(this.settings.errorPlacement?this.settings.errorPlacement(d,c(a)):d.insertAfter(a))}if(!b&&this.settings.success){d.text("");typeof this.settings.success=="string"?d.addClass(this.settings.success):this.settings.success(d)}this.toShow=this.toShow.add(d)},errorsFor:function(a){var b=this.idOrName(a);return this.errors().filter(function(){return c(this).attr("for")==b})},
	idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(a){var b=this.currentForm;return c(document.getElementsByName(a)).map(function(d,e){return e.form==b&&e.name==a&&e||null})},getLength:function(a,b){switch(b.nodeName.toLowerCase()){case "select":return c("option:selected",b).length;case "input":if(this.checkable(b))return this.findByName(b.name).filter(":checked").length}return a.length},
	depend:function(a,b){return this.dependTypes[typeof a]?this.dependTypes[typeof a](a,b):true},dependTypes:{"boolean":function(a){return a},string:function(a,b){return!!c(a,b.form).length},"function":function(a,b){return a(b)}},optional:function(a){return!c.validator.methods.required.call(this,c.trim(a.value),a)&&"dependency-mismatch"},startRequest:function(a){if(!this.pending[a.name]){this.pendingRequest++;this.pending[a.name]=true}},stopRequest:function(a,b){this.pendingRequest--;if(this.pendingRequest<
	0)this.pendingRequest=0;delete this.pending[a.name];if(b&&this.pendingRequest==0&&this.formSubmitted&&this.form()){c(this.currentForm).submit();this.formSubmitted=false}else if(!b&&this.pendingRequest==0&&this.formSubmitted){c(this.currentForm).triggerHandler("invalid-form",[this]);this.formSubmitted=false}},previousValue:function(a){return c.data(a,"previousValue")||c.data(a,"previousValue",{old:null,valid:true,message:this.defaultMessage(a,"remote")})}},classRuleSettings:{required:{required:true},
	email:{email:true},url:{url:true},date:{date:true},dateISO:{dateISO:true},dateDE:{dateDE:true},number:{number:true},numberDE:{numberDE:true},digits:{digits:true},creditcard:{creditcard:true}},addClassRules:function(a,b){a.constructor==String?this.classRuleSettings[a]=b:c.extend(this.classRuleSettings,a)},classRules:function(a){var b={};(a=c(a).attr("class"))&&c.each(a.split(" "),function(){this in c.validator.classRuleSettings&&c.extend(b,c.validator.classRuleSettings[this])});return b},attributeRules:function(a){var b=
	{};a=c(a);for(var d in c.validator.methods){var e=a.attr(d);if(e)b[d]=e}b.maxlength&&/-1|2147483647|524288/.test(b.maxlength)&&delete b.maxlength;return b},metadataRules:function(a){if(!c.metadata)return{};var b=c.data(a.form,"validator").settings.meta;return b?c(a).metadata()[b]:c(a).metadata()},staticRules:function(a){var b={},d=c.data(a.form,"validator");if(d.settings.rules)b=c.validator.normalizeRule(d.settings.rules[a.name])||{};return b},normalizeRules:function(a,b){c.each(a,function(d,e){if(e===
	false)delete a[d];else if(e.param||e.depends){var f=true;switch(typeof e.depends){case "string":f=!!c(e.depends,b.form).length;break;case "function":f=e.depends.call(b,b)}if(f)a[d]=e.param!==undefined?e.param:true;else delete a[d]}});c.each(a,function(d,e){a[d]=c.isFunction(e)?e(b):e});c.each(["minlength","maxlength","min","max"],function(){if(a[this])a[this]=Number(a[this])});c.each(["rangelength","range"],function(){if(a[this])a[this]=[Number(a[this][0]),Number(a[this][1])]});if(c.validator.autoCreateRanges){if(a.min&&
	a.max){a.range=[a.min,a.max];delete a.min;delete a.max}if(a.minlength&&a.maxlength){a.rangelength=[a.minlength,a.maxlength];delete a.minlength;delete a.maxlength}}a.messages&&delete a.messages;return a},normalizeRule:function(a){if(typeof a=="string"){var b={};c.each(a.split(/\s/),function(){b[this]=true});a=b}return a},addMethod:function(a,b,d){c.validator.methods[a]=b;c.validator.messages[a]=d!=undefined?d:c.validator.messages[a];b.length<3&&c.validator.addClassRules(a,c.validator.normalizeRule(a))},
	methods:{required:function(a,b,d){if(!this.depend(d,b))return"dependency-mismatch";switch(b.nodeName.toLowerCase()){case "select":return(a=c(b).val())&&a.length>0;case "input":if(this.checkable(b))return this.getLength(a,b)>0;default:return c.trim(a).length>0}},remote:function(a,b,d){if(this.optional(b))return"dependency-mismatch";var e=this.previousValue(b);this.settings.messages[b.name]||(this.settings.messages[b.name]={});e.originalMessage=this.settings.messages[b.name].remote;this.settings.messages[b.name].remote=
	e.message;d=typeof d=="string"&&{url:d}||d;if(this.pending[b.name])return"pending";if(e.old===a)return e.valid;e.old=a;var f=this;this.startRequest(b);var g={};g[b.name]=a;c.ajax(c.extend(true,{url:d,mode:"abort",port:"validate"+b.name,dataType:"json",data:g,success:function(h){f.settings.messages[b.name].remote=e.originalMessage;var j=h===true;if(j){var i=f.formSubmitted;f.prepareElement(b);f.formSubmitted=i;f.successList.push(b);f.showErrors()}else{i={};h=h||f.defaultMessage(b,"remote");i[b.name]=
	e.message=c.isFunction(h)?h(a):h;f.showErrors(i)}e.valid=j;f.stopRequest(b,j)}},d));return"pending"},minlength:function(a,b,d){return this.optional(b)||this.getLength(c.trim(a),b)>=d},maxlength:function(a,b,d){return this.optional(b)||this.getLength(c.trim(a),b)<=d},rangelength:function(a,b,d){a=this.getLength(c.trim(a),b);return this.optional(b)||a>=d[0]&&a<=d[1]},min:function(a,b,d){return this.optional(b)||a>=d},max:function(a,b,d){return this.optional(b)||a<=d},range:function(a,b,d){return this.optional(b)||
	a>=d[0]&&a<=d[1]},email:function(a,b){return this.optional(b)||/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(a)},
	url:function(a,b){return this.optional(b)||/((https|http|ftp):\/\/)?(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(a)},
	date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a))},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/-]\d{1,2}[\/-]\d{1,2}$/.test(a)},number:function(a,b){return this.optional(b)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},creditcard:function(a,b){if(this.optional(b))return"dependency-mismatch";if(/[^0-9-]+/.test(a))return false;var d=0,e=0,f=false;a=a.replace(/\D/g,"");for(var g=a.length-1;g>=
	0;g--){e=a.charAt(g);e=parseInt(e,10);if(f)if((e*=2)>9)e-=9;d+=e;f=!f}return d%10==0},accept:function(a,b,d){d=typeof d=="string"?d.replace(/,/g,"|"):"png|jpe?g|gif";return this.optional(b)||a.match(RegExp(".("+d+")$","i"))},equalTo:function(a,b,d){d=c(d).unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){c(b).valid()});return a==d.val()}}});c.format=c.validator.format})(jQuery);
	(function(c){var a={};if(c.ajaxPrefilter)c.ajaxPrefilter(function(d,e,f){e=d.port;if(d.mode=="abort"){a[e]&&a[e].abort();a[e]=f}});else{var b=c.ajax;c.ajax=function(d){var e=("port"in d?d:c.ajaxSettings).port;if(("mode"in d?d:c.ajaxSettings).mode=="abort"){a[e]&&a[e].abort();return a[e]=b.apply(this,arguments)}return b.apply(this,arguments)}}})(jQuery);
	(function(c){!jQuery.event.special.focusin&&!jQuery.event.special.focusout&&document.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.handle.call(this,e)}c.event.special[b]={setup:function(){this.addEventListener(a,d,true)},teardown:function(){this.removeEventListener(a,d,true)},handler:function(e){arguments[0]=c.event.fix(e);arguments[0].type=b;return c.event.handle.apply(this,arguments)}}});c.extend(c.fn,{validateDelegate:function(a,
	b,d){return this.bind(b,function(e){var f=c(e.target);if(f.is(a))return d.apply(f,arguments)})}})})(jQuery);
	(function() {
		
		function stripHtml(value) {
			// remove html tags and space chars
			return value.replace(/<.[^<>]*?>/g, ' ').replace(/&nbsp;|&#160;/gi, ' ')
			// remove numbers and punctuation
			.replace(/[0-9.(),;:!?%#$'"_+=\/-]*/g,'');
		}
		jQuery.validator.addMethod("maxWords", function(value, element, params) { 
		    return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length < params; 
		}, jQuery.validator.format("Please enter {0} words or less.")); 
		 
		jQuery.validator.addMethod("minWords", function(value, element, params) { 
		    return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params; 
		}, jQuery.validator.format("Please enter at least {0} words.")); 
		 
		jQuery.validator.addMethod("rangeWords", function(value, element, params) { 
		    return this.optional(element) || stripHtml(value).match(/\b\w+\b/g).length >= params[0] && value.match(/bw+b/g).length < params[1]; 
		}, jQuery.validator.format("Please enter between {0} and {1} words."));
	})();
	
	
	}
    
//v1.1
//Copyright 2006 Adobe Systems,Inc. All rights reserved.
function AC_AX_RunContent()
{
	var ret=AC_AX_GetArgs(arguments);
	AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs);
}

function AC_AX_GetArgs(args)
{
	var ret=new Object();
	ret.embedAttrs=new Object();
	ret.params=new Object();
	ret.objAttrs=new Object();
	for (var i=0; i < args.length; i=i+2)
	{
		var currArg=args[i].toLowerCase();    
	
		switch (currArg)
		{	
			case "pluginspage":
			case "type":
			case "src":
			ret.embedAttrs[args[i]]=args[i+1];
			break;
			case "data":
			case "codebase":
			case "classid":
			case "id":
			case "onafterupdate":
			case "onbeforeupdate":
			case "onblur":
			case "oncellchange":
			case "onclick":
			case "ondblClick":
			case "ondrag":
			case "ondragend":
			case "ondragenter":
			case "ondragleave":
			case "ondragover":
			case "ondrop":
			case "onfinish":
			case "onfocus":
			case "onhelp":
			case "onmousedown":
			case "onmouseup":
			case "onmouseover":
			case "onmousemove":
			case "onmouseout":
			case "onkeypress":
			case "onkeydown":
			case "onkeyup":
			case "onload":
			case "onlosecapture":
			case "onpropertychange":
			case "onreadystatechange":
			case "onrowsdelete":
			case "onrowenter":
			case "onrowexit":
			case "onrowsinserted":
			case "onstart":
			case "onscroll":
			case "onbeforeeditfocus":
			case "onactivate":
			case "onbeforedeactivate":
			case "ondeactivate":
			ret.objAttrs[args[i]]=args[i+1];
			break;
			case "width":
			case "height":
			case "align":
			case "vspace": 
			case "hspace":
			case "class":
			case "title":
			case "accesskey":
			case "name":
			case "tabindex":
			ret.embedAttrs[args[i]]=ret.objAttrs[args[i]]=args[i+1];
			break;
			default:
			ret.embedAttrs[args[i]]=ret.params[args[i]]=args[i+1];
		}
	}
	return ret;
}

//v1.0
//Copyright 2006 Adobe Systems,Inc. All rights reserved.
function AC_AddExtension(src,ext)
{
	if (src.indexOf('?') !=-1)return src.replace(/\?/,ext+'?'); 
	else return src + ext;
}

function AC_Generateobj(objAttrs,params,embedAttrs) 
{ 
	var str='<object ';
	for (var i in objAttrs)
	str +=i + '="' + objAttrs[i] + '" ';
	str +='>';
	for (var i in params)
	str +='<param name="' + i + '" value="' + params[i] + '" /> ';
	str +='<embed ';
	for (var i in embedAttrs)
	str +=i + '="' + embedAttrs[i] + '" ';
	str +=' ></embed></object>';
	document.write(str);
}

function AC_FL_RunContent()
{
	var ret=AC_GetArgs(arguments,".swf","movie","clsid:d27cdb6e-ae6d-11cf-96b8-444553540000","application/x-shockwave-flash");
	AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs);
}

function AC_SW_RunContent()
{
	var ret=AC_GetArgs(arguments,".dcr","src","clsid:166B1BCA-3F9C-11CF-8075-444553540000",null);
	AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs);
}

function AC_GetArgs(args,ext,srcParamName,classid,mimeType)
{
	var ret=new Object();
	ret.embedAttrs=new Object();
	ret.params=new Object();
	ret.objAttrs=new Object();
	for (var i=0; i < args.length; i=i+2)
	{
		var currArg=args[i].toLowerCase();    

		switch (currArg)
		{	
			case "classid":
			break;
			case "pluginspage":
			ret.embedAttrs[args[i]]=args[i+1];
			break;
			case "src":
			case "movie":	
			args[i+1]=AC_AddExtension(args[i+1],ext);
			ret.embedAttrs["src"]=args[i+1];
			ret.params[srcParamName]=args[i+1];
			break;
			case "onafterupdate":
			case "onbeforeupdate":
			case "onblur":
			case "oncellchange":
			case "onclick":
			case "ondblClick":
			case "ondrag":
			case "ondragend":
			case "ondragenter":
			case "ondragleave":
			case "ondragover":
			case "ondrop":
			case "onfinish":
			case "onfocus":
			case "onhelp":
			case "onmousedown":
			case "onmouseup":
			case "onmouseover":
			case "onmousemove":
			case "onmouseout":
			case "onkeypress":
			case "onkeydown":
			case "onkeyup":
			case "onload":
			case "onlosecapture":
			case "onpropertychange":
			case "onreadystatechange":
			case "onrowsdelete":
			case "onrowenter":
			case "onrowexit":
			case "onrowsinserted":
			case "onstart":
			case "onscroll":
			case "onbeforeeditfocus":
			case "onactivate":
			case "onbeforedeactivate":
			case "ondeactivate":
			case "type":
			case "codebase":
			ret.objAttrs[args[i]]=args[i+1];
			break;
			case "width":
			case "height":
			case "align":
			case "vspace": 
			case "hspace":
			case "class":
			case "title":
			case "accesskey":
			case "name":
			case "id":
			case "tabindex":
			ret.embedAttrs[args[i]]=ret.objAttrs[args[i]]=args[i+1];
			break;
			default:
			ret.embedAttrs[args[i]]=ret.params[args[i]]=args[i+1];
		}
	}
	ret.objAttrs["classid"]=classid;
	if (mimeType) ret.embedAttrs["type"]=mimeType;
	return ret;
}

/*
FlashObject v1.2.3: Flash detection and embed - http://blog.deconcept.com/flashobject/

FlashObject is (c) 2005 Geoff Stearns and is released under the MIT License:
http://www.opensource.org/licenses/mit-license.php*/

if(typeof com == "undefined") var com = new Object();
if(typeof com.deconcept == "undefined") com.deconcept = new Object();
if(typeof com.deconcept.util == "undefined") com.deconcept.util = new Object();
if(typeof com.deconcept.FlashObjectUtil == "undefined") com.deconcept.FlashObjectUtil = new Object();
com.deconcept.FlashObject = function(swf, id, w, h, ver, c, useExpressInstall, quality, redirectUrl, detectKey)
{
	this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
	this.skipDetect = com.deconcept.util.getRequestParameter(this.DETECT_KEY);
	this.params = new Object();
	this.variables = new Object();
	this.attributes = new Array();

	if(swf) this.setAttribute('swf', swf);
	if(id) this.setAttribute('id', id);
	if(w) this.setAttribute('width', w);
	if(h) this.setAttribute('height', h);
	if(ver) this.setAttribute('version', new com.deconcept.PlayerVersion(ver.toString().split(".")));
	if(c) this.addParam('bgcolor', c);
	var q = quality ? quality : 'high';
	this.addParam('quality', q);
	this.setAttribute('redirectUrl', '');
	if(redirectUrl) this.setAttribute('redirectUrl', redirectUrl);
	if(useExpressInstall)
	{
		/*check to see if we need to do an express install*/
		var expressInstallReqVer = new com.deconcept.PlayerVersion([6,0,65]);
		var installedVer = com.deconcept.FlashObjectUtil.getPlayerVersion();
		if (installedVer.versionIsValid(expressInstallReqVer) && !installedVer.versionIsValid(this.getAttribute('version'))) {this.setAttribute('doExpressInstall', true);}
	} else {this.setAttribute('doExpressInstall', false);}
}
com.deconcept.FlashObject.prototype.setAttribute = function(name, value){this.attributes[name] = value;}
com.deconcept.FlashObject.prototype.getAttribute = function(name){return this.attributes[name];}
com.deconcept.FlashObject.prototype.getAttributes = function(){return this.attributes;}
com.deconcept.FlashObject.prototype.addParam = function(name, value){this.params[name] = value;}
com.deconcept.FlashObject.prototype.getParams = function(){return this.params;}
com.deconcept.FlashObject.prototype.getParam = function(name){return this.params[name];}
com.deconcept.FlashObject.prototype.addVariable = function(name, value){this.variables[name] = value;}
com.deconcept.FlashObject.prototype.getVariable = function(name){return this.variables[name];}
com.deconcept.FlashObject.prototype.getVariables = function(){return this.variables;}
com.deconcept.FlashObject.prototype.getParamTags = function()
{
	var paramTags = ""; var key; var params = this.getParams();
   	for(key in params)
	{
    	paramTags += '<param name="' + key + '" value="' + params[key] + '" />';
	}
   	return paramTags;
}
com.deconcept.FlashObject.prototype.getVariablePairs = function()
{
	var variablePairs = new Array();
	var key;
	var variables = this.getVariables();
	for(key in variables)
	{
		variablePairs.push(key +"="+ variables[key]);
	}
	return variablePairs;
}
com.deconcept.FlashObject.prototype.getHTML = function()
{
	var flashHTML = "";
	if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length)
	{
		/*netscape plugin architecture*/
		if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "PlugIn"); }
		flashHTML += '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" id="'+ this.getAttribute('id') + '" name="'+ this.getAttribute('id') +'"';
		var params = this.getParams();
		for(var key in params){ flashHTML += ' '+ key +'="'+ params[key] +'"'; }
		pairs = this.getVariablePairs().join("&");
		if (pairs.length > 0){ flashHTML += ' flashvars="'+ pairs +'"'; }
		flashHTML += '></embed>';
	}
	else
	{
		/*PC IE*/
		if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "ActiveX"); }
		flashHTML += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'" id="'+ this.getAttribute('id') +'">';
		flashHTML += '<param name="movie" value="' + this.getAttribute('swf') + '" />';
		var tags = this.getParamTags();
		if(tags.length > 0){ flashHTML += tags; }
		var pairs = this.getVariablePairs().join("&");
		if(pairs.length > 0){ flashHTML += '<param name="flashvars" value="'+ pairs +'" />'; }
		flashHTML += '</object>';
	}
	return flashHTML;
}
com.deconcept.FlashObject.prototype.write = function(element)
{
	element = $(element);
	if(this.skipDetect || this.getAttribute('doExpressInstall') || com.deconcept.FlashObjectUtil.getPlayerVersion().versionIsValid(this.getAttribute('version'))){
	if(element)
	{
		if (this.getAttribute('doExpressInstall'))
		{
			this.addVariable("MMredirectURL", escape(window.location));
			document.title = document.title.slice(0, 47) + " - Flash Player Installation";
			this.addVariable("MMdoctitle", document.title);
		}
		element.innerHTML = this.getHTML();
	}
	}
	else
	{
		if(this.getAttribute('redirectUrl') != "") {document.location.replace(this.getAttribute('redirectUrl'));}
	}
}
/* ---- detection functions ---- */
com.deconcept.FlashObjectUtil.getPlayerVersion = function()
{
	var PlayerVersion = new com.deconcept.PlayerVersion(0,0,0);
	if(navigator.plugins && navigator.mimeTypes.length)
	{
		var x = navigator.plugins["Shockwave Flash"];
		if(x && x.description)
		{
			PlayerVersion = new com.deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
		}
	}
	else if (window.ActiveXObject)
	{
		try
		{
			var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			PlayerVersion = new com.deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
		}
		catch (e) {}
	}
	return PlayerVersion;
}
com.deconcept.PlayerVersion = function(arrVersion)
{
	this.major = parseInt(arrVersion[0]) || 0;
    this.minor = parseInt(arrVersion[1]) || 0;
	this.rev = parseInt(arrVersion[2]) || 0;
}
com.deconcept.PlayerVersion.prototype.versionIsValid = function(fv)
{
	if(this.major < fv.major) return false;
	if(this.major > fv.major) return true;
	if(this.minor < fv.minor) return false;
	if(this.minor > fv.minor) return true;
	if(this.rev < fv.rev) return false;
	return true;
}
/* ---- get value of query string param ---- */
com.deconcept.util.getRequestParameter = function(param)
{
	var q = document.location.search || document.location.href.hash;
	if(q)
	{
		var startIndex = q.indexOf(param +"=");
		var endIndex = (q.indexOf("&", startIndex) > -1) ? q.indexOf("&", startIndex) : q.length;
		if (q.length > 1 && startIndex > -1) {return q.substring(q.indexOf("=", startIndex)+1, endIndex);}
	}
	return "";
}

/* add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }}

/* add some aliases for ease of use / backwards compatibility */
var getQueryParamValue = com.deconcept.util.getRequestParameter;
var FlashObject = com.deconcept.FlashObject;

/*POPUP SITE*/
function openProduct(url,w,h)
{
	/*Inicializa box*/
    $('.lightbox-overlay').remove();
    $('.lightbox').remove();
        
	$("body").append("<div class='lightbox-overlay' style='display:none;'></div>").append("<div class='lightbox' style='display:none;'></div>");
	createOverLay(url,w,h)
}

function createOverLay(url,w,h)
{
	try
	{
		$(".lightbox-overlay").css({
			background: '#000000',
			position:'fixed',
			top:0,
			left:0,
			'z-index':10000,
			height:$(document).height(),
			width: $(document).width()
		})
		.show(100, function(){
			$(this).animate({opacity: .5}, 0,function(){
					createBox(w,h, url)
				}
			);
		})
		.click(function(){
			$(".lightbox-overlay, .lightbox").fadeOut("fast");	
			$("#AuxiliarFrame").remove();
			$("body").css("overflow",'auto');
		})
		
		return true;
	}
	catch(e)
	{
		$(".lightbox-overlay, .lightbox").fadeOut("fast");	
		$('.lightbox-overlay').remove();
        $('.lightbox').remove();
		return false;
	}
	
}
/*Cria a box para o conteudo.*/
function createBox(w,h,url)
{
	try
	{
		var width = w==0 ? parseInt($(window).width()) -80: w;
		var height = h==0 ? parseInt($(window).height())- 80 : h;
		
		$(".lightbox").css(
		{
			background: '#FFFFFF',
            backgroundImage: ' url("../templates/kk_loading.gif")',
            backgroundRepeat:'no-repeat',
            backgroundPosition:'center',
			padding: '0',
			'overflow':'hidden',
			position: "fixed",
			width: width,
			height: height,
			'z-index':20000
		});
		
        
        var htmlST = parseInt($("html").scrollTop()),
        	bodyST = parseInt($("body").scrollTop()),
            aux=0;
        
        if( htmlST>=bodyST)
        	aux=htmlST;
        
        if( htmlST< bodyST)
        	aux = bodyST;
        
		$(".lightbox").css({
			top: (parseInt($(window).height()/2) - parseInt($(".lightbox").height()/2)),
			left: parseInt($(window).width()/2) - parseInt($(".lightbox").width()/2)
		}).show()
		.append('<iframe allowtransparency="1" src="'+url+'" frameborder="0" scrolling="yes" id="AuxiliarFrame" width="100%" height="'+height+'" style="position:relative;"></iframe>');
        
        
        
		//$("body").css("overflow",'hidden');
	}
	catch(e)
	{
		$(".lightbox-overlay, .lightbox").fadeOut("fast");	
		$("#AuxiliarFrame").remove();
		return false;
	}
}

function confirmDelete( url ){
	if(window.confirm("Tem a certza que deseja apagar o produto seleccionado?"))	
		window.open(url,'','location=0,status=0,scrollbars=1,width=500,height=500');	
}
