String.prototype.trim = function()
{
  return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

function EventsLogin(){
	$('a.makelogin').click(function(ev){
		ev.preventDefault();
		
		$('.loginform').show(500);
	});
	
	$('.closelogin').click(function(){
		$('.loginform').hide(500);
	});
}

function EventSubMenuTop(){
	$('ul.menuheader > li').hover(function(){
		$('ul.menuheader > li ul').hide();
		$('ul:not(:animated)', this).show(200, function(){
			SetSubmenuWidthIE7($(this));
		});
	}, function(){
		$('ul:not(:animated)', this).hide(200);
	});
} 

function EventsMenuMain(){
	$('ul.menumain > li a.sel').css('background-color', $('span.name', $('ul.menumain > li a.sel')).css('border-top-color'));
	
	$('ul.menumain > li a').hover(function(){
	   if($(this).is(':not(.sel)'))
		  $(this).css('background-color', $('span.name', $(this)).css('border-top-color'));
	}, function(){
	   if($(this).is(':not(.sel)'))
		  $(this).css('background-color', '#242325');
	});
}

function EventsSearchMain(){
/*
	$('.searchmain input[type="text"]').focusin(function(){
		$(this).val('');
	});
	*/
	
	$('.searchmain input[type="image"]').hover(function(){
		$(this).attr('src', 'sysimages/bgpesq_hover.jpg');
	}, function(){
		$(this).attr('src', 'sysimages/bgpesq.jpg');
	});
}

function SetSubmenuWidthIE7(that){
	if($.browser.msie && $.browser.version == '7.0' && that.data('calcWidth') == false){
		that.data('calcWidth', true);
		var childs = $('li', that);
		var maxW = 0;
	
		childs.each(function(){
			var thatW = $(this).outerWidth();
			if(thatW > maxW){
				maxW = thatW;
			}
		});
	
		that.width(maxW);
	}
}

function VerifySideMenu(){
	$('ul.sidemenu > li > a > span').each(function(){	
		var spanPadTop = (($('ul.sidemenu > li > a').height() / 2) - ($(this).height() / 2)),
		leftBg = '6px', topBg = (($(this).height() / 2) + spanPadTop - 6);
	
		if($(this).parent('a').is('.sel'))
		{
			leftBg = '11px';
		}
		
		$(this).css({
			'padding-top' : spanPadTop + 'px',
			'background-position' : leftBg + ' ' + topBg + 'px'
		});
		/*
		if ($.browser.mozilla) {
			var thatText = $(this).text();

			if (thatText.length > 30) {
				thatText.replace(/-/g, "- ");
			}
	
			$(this).text(thatText);
		}
		*/
	});
	
	$('ul.subsidemenu > li > a span').each(function(){
		var thatHeight = $(this).height(), padd;
		
		padd = ((39 - thatHeight) / 2);
		
		$(this).css('padding-top', padd + 'px')
	});
	
	$('ul.sidemenu > li > a').bind({
		mouseenter : function(){
			if($(this).is('.unsel'))
			{
				var spanPadTop = (($('ul.sidemenu > li > a').height() / 2) - ($('span', $(this)).height() / 2)),
				topBg = (($('span', $(this)).height() / 2) + spanPadTop - 6);
			
				$('span', $(this)).css('background-position', '11px ' + topBg + 'px');
			}
		},
		
		mouseleave : function(){
			if($(this).is('.unsel'))
			{
				var spanPadTop = (($('ul.sidemenu > li > a').height() / 2) - ($('span', $(this)).height() / 2)),
				topBg = (($('span', $(this)).height() / 2) + spanPadTop - 6);
			
				$('span', $(this)).css('background-position', '6px ' + topBg + 'px');
			}
		}
	});
}

$(document).ready(function(){
	EventsLogin();
	EventsMenuMain();
	EventsSearchMain();
	EventSubMenuTop();
	VerifySideMenu();
	$('ul.menuheader > li > ul').data('calcWidth', false);
	
	if ($.browser.msie && $.browser.version == '7.0') {
		$('ul.sidemenu > li:first').css('border-top', '0px');
		$('ul.submenuheader > li').css('margin-left', '-16px');
		
	}
	
	if ($(window).width() < 990) {
		$('html').css('overflow-x', 'auto');
	} else {
		$('html').css('overflow-x', 'hidden');
	}
		
	$(window).resize(function () {
		//if ($.browser.msie && $.browser.version == '7.0') {
			if ($(window).width() < 990) {
				$('html').css('overflow-x', 'auto');
				$('#container').css('overflow', 'hidden');
			} else {
				$('html').css('overflow-x', 'hidden');
				$('#container').removeAttr('style');
			}
		//}
	});
	
	$('.factentrega input[type="radio"]:checked').parents('.itemdadosfact').css('border-color', '#B7B7B7');
});

function EventsProds(){
	$('.prod').hover(function(){
		$('.innerprod', this).css('border-color', $('ul.menumain > li a.sel').css('background-color'));
	}, function(){
		$('.innerprod', this).css('border-color', 'transparent');
	});
}

function OpenPopup(){
	$('.containerpopup').height($(document).height()).show(500);
	$(window).scrollTop(0);
}

function ShowFormInfo(){
  $('.trpedinfo').hide();
  $('.pedinfo').show(500);
}

function HideFormInfo(){
	$('.pedinfo').hide(500, function(){
		$('.trpedinfo').show();
	});
	
  if($(".sucesssubmit").css("display") == "block") {
  	$('.containerform').css("display", "block");
    $('.sucesssubmit').css("display", "none");
  }
}

function EventsFaqs(){
	$('ul.ulfaqs > li > a').click(function(ev){
		ev.preventDefault();
		
		var that = $(this);
		
		if(that.parent().is('.sel')){
			$('span.txtfaq', that.parent()).animate({
				height : '0px'
			}, 500, function(){
				that.parent().attr('class', 'unsel');
			});
		}
		else{
			$('span.txtfaq', $('ul.ulfaqs > li.sel')).animate({
				height : '0px'
			}, 500, function(){
				$(this).parent().attr('class', 'unsel');
			});
			
			var hToanim = $('span.txtfaq span.overflow', that.parent()).outerHeight(true);
			
			$('span.txtfaq', that.parent()).animate({
				height : hToanim + 'px'
			}, 500, function(){
				that.parent().attr('class', 'sel');
			});
		}
	});
}

function ResetForm(){
	$('a.cleanform').click(function(ev){
		ev.preventDefault();
		
		$('#frmreg')[0].reset();
	});
}

function SelectMoradaFact(){
	$('.radiofact').each(function(){
		if($('input:radio', $(this)).is(':not(:checked)')){
			$('label', $(this)).css('color', '#666666');
		}
		else{
			$('label', $(this)).css('color', '#333333');
		}
	});
	
	$('.dadosfact .morregisto').click(function(){
		$('.newmor').animate({
			height : '0px'
		}, 500, function(){
			$('label', $(this).parent()).css('color', '#666666');
			$('label', $('.morregisto').parent()).css('color', '#333333');
		});
	});
	
	$('.dadosfact .newmorada').click(function(){
		var hToAnim = $('div', $('.newmor')).outerHeight(true);
		
		$('.newmor').animate({
			height : hToAnim + 'px'
		}, 500, function(){
			$('label', $('.morregisto').parent()).css('color', '#666666');
			$('label', $(this).parent()).css('color', '#333333');
		});
	});
	
	$('.dadosentr .morregisto, .dadosentr .newmorada').click(function(){
		if($(this).is('.morregisto')){
			$('label', $(this).parents('.moradaentr')).css('color', '#666666');
			$('label', $(this).parent()).css('color', '#333333');
		}
		else{
			$('label', $(this).parents('.moradaentr')).css('color', '#666666');
			$('label', $(this).parent()).css('color', '#333333');
		}
	});
}

var childsNews;
var curNew = 1;
function NewsSlider(){
	$('ul.ulnewshome > li.current > span:first').text(1);
	$('ul.ulnewshome > li.current > span + span').text($('.wrappernews').children().length);

	childsNews = $('.wrappernews').children();
	$(childsNews[0]).show(500);
	
	$('ul.ulnewshome > li > a.prev').click(function(ev){
		ev.preventDefault();
		
		$(childsNews[curNew - 1]).hide(500, function(){
			if(curNew == 1){
				$(childsNews[childsNews.length - 1]).show(500);
				curNew = childsNews.length;
				$('ul.ulnewshome > li.current > span:first').text(curNew);
			}
			else{
				$(childsNews[curNew - 2]).show(500);
				curNew--;
				$('ul.ulnewshome > li.current > span:first').text(curNew);
			}
		}).delay(1000);
	});
	
	$('ul.ulnewshome > li > a.next').click(function(ev){
		ev.preventDefault();
		
		$(childsNews[curNew - 1]).hide(500, function(){
			if(curNew == childsNews.length){
				$(childsNews[0]).show(500);
				curNew = 1;
				$('ul.ulnewshome > li.current > span:first').text(curNew);
			}
			else{
				$(childsNews[curNew]).show(500);
				curNew++;
				$('ul.ulnewshome > li.current > span:first').text(curNew);
			}
		}).delay(1000);
	});
}

function seeFormEntr(that){
	that = that || null;
	
	if(that.id == 'endentr'){
		$('.formnewaddr').show(500, function(){
			$('input.addr').parents('.itemdadosfact').css('border-color', '#F4F4F4');
			$(this).parents('.itemdadosfact').css('border-color', '#B7B7B7');
		});
	}
	else{
		$('.formnewaddr').hide(400, function(){
			$('input.addr').parents('.itemdadosfact').css('border-color', '#F4F4F4');
			$(that).parents('.itemdadosfact').css('border-color', '#B7B7B7');
		});
	}
}

function filtro_mtec(opc) {
  var mrc  = $('#filt_mrc').val();
  var fam  = $('#filt_fam').val();
  var sfam = $('#filt_sfam').val();
  
  //alert(mrc+' + '+fam+' - '+sfam)
  
  var params = {o:opc,m:mrc,f:fam,sf:sfam};
  var str = jQuery.param(params);
  var aux = 0;
  
  jQuery.ajax({
    url: 'addOpcsSelects.php',
    data:str,
    success: function(data) {
      //alert(data);
      var res = data.split('||')
      //alert(res[1])
      if(res[1]=='OK'){
        $('#sel_fam').html(res[2]);
        $('#sel_sfam').html(res[3]);
      }
    }
  })
  
  return aux;
}

function verify_form_filter(){
  var mrc  = $('#filt_mrc').val();
  var fam  = $('#filt_fam').val();
  var sfam = $('#filt_sfam').val();
  
  if(mrc.length<=0) {
    //return false;
  }
  
  return true;
}

function muda_tutorial() {
  var tut  = $('#tutoriais').val();
  var idp  = $('#idp').val();
  
  location = "index.php?id="+idp+"&tut="+tut;
  
}

function muda_passo_tut() {
  var tut   = $('#tutoriais').val();
  var idp   = $('#idp').val();
  var ptut  = $('#tutoriais_passos').val();
  if(ptut>0){
    location = "index.php?id="+idp+"&tut="+tut+"&tdet="+ptut;
  } else {
    location = "index.php?id="+idp+"&tut="+tut;
  }
}


var OBJ;
var total;
var elem = new Array();
function formErros(obj) {
  OBJ=obj;
  total=obj.length;
    
  var frmObj=OBJ.form;
  objID=obj.id;
   
         
  elem = frmObj.elements;
  var erros = 0;
  for(i = 0; i < elem.length; i++) {
    if(elem[i].id==objID) {
      document.getElementById(objID).style.borderColor = "#FF0000";
      erros++;
    } else {
      if(elem[i].type != "submit") {
        elem[i].style.borderColor = "#999999";
      }
    }
  }
}

var contador=0;
function valida_pesq(pfield,txt,lg) {
  if(contador==1){
    if((document.getElementById(pfield).value!='') && (document.getElementById(pfield).value.trim()!='') && (document.getElementById(pfield).value.length>=3)) {
      return true;
    } else {
      if(lg=='pt'){
        alert('Tem de introduzir uma expressão com 3 ou mais caracteres.');
      }
      if(lg=='gb'){
        alert('You must enter an expression with three or more characters.');
      }
      if(lg=='sp'){
        alert('Debe introducir una expresión con tres o más caracteres.');
      }
      if(lg=='fr'){
        alert('Vous devez saisir une expression avec trois ou plusieurs caractères.');
      }
      
      return false;
    }
  }
  
  if((document.getElementById(pfield).value!='') && (document.getElementById(pfield).value.trim()!='') && (document.getElementById(pfield).value!=txt)) {
    if(document.getElementById(pfield).value.length>=3) {
      return true;
    } else {
      if(lg=='pt'){
        alert('Tem de introduzir uma expressão com 3 ou mais caracteres.');
      }
      if(lg=='gb'){
        alert('You must enter an expression with three or more characters.');
      }
      if(lg=='sp'){
        alert('Debe introducir una expresión con tres o más caracteres.');
      }
      if(lg=='fr'){
        alert('Vous devez saisir une expression avec trois ou plusieurs caractères.');
      }
      return false;
    }
  } else {
    if(lg=='pt'){
        alert('Tem de introduzir uma expressão a pesquisar.');
      }
      if(lg=='gb'){
        alert('You must enter an expression to search.');
      }
      if(lg=='sp'){
        alert('Debe introducir una expresión para la búsqueda.');
      }
      if(lg=='fr'){
        alert('Vous devez saisir une expression à rechercher.');
      }
    return false;
  }
}


function verify_number_carr(field,lg){
  var erro = 0;
  if (isNaN(field.value)) 
  {
    if(lg=='gb')
      alert("You can only enter numeric characters.");
    else if(lg=='sp')
      alert("Sólo se pueden introducir caracteres numéricos.");
    else if(lg=='fr')
      alert("Vous ne pouvez introduire des caractères numériques.");
    else
      alert("Só pode introduzir caracteres numéricos.");
      
    field.value=1;
    field.focus();
    if(erro==0) erro = 1;
  }
  
  if(field.value<=0){
    if(lg=='gb')
      alert("You must enter an amount greater than 0.");
    else if(lg=='sp')
      alert("Debe introducir una cantidad mayor que 0.");
    else if(lg=='fr')
      alert("Vous devez entrer un montant supérieur à 0.");
    else
      alert("Tem que introduzir uma quantidade superior a 0.");
      
    field.value=1;
    field.focus();
    
    if(erro==0) erro = 1;
  }
  
  return erro;
}

function remove_prod(pid) {
  jQuery("#product_id").val(pid);
  jQuery("#actualiza").val(4);
  jQuery("#basket_frm").submit();
}

function actualiza_prod(pid,id) {
  jQuery("#product_id").val(pid);
  jQuery("#lineprod").val(id);
  jQuery("#actualiza").val(5);
  jQuery("#basket_frm").submit();
}

function escolhe_mrc(id,lst_mrc,sel_mrc) {
  
  if(sel_mrc==0){
    location = "index.php?id="+id+"";
  } else {
    var params = {id:id,lstm:lst_mrc,smrc:sel_mrc};
    var str = jQuery.param(params);
    var aux = 0;
    
    jQuery.ajax({
      url: '_filtros.php',
      data:str,
      success: function(data) {
        //alert(data);
        var res = data.split('--OK--')
        location = res[1];
      }
    })
    
    return aux;
  }
}

function calcula_portes(met_sel) {
  var metodo = met_sel.value;
  var params = {met:metodo};
  var str = jQuery.param(params);
  var aux = 0;
  
  jQuery.ajax({
    url: '_calcula_portes.php',
    data:str,
    success: function(data) {
      //alert(data);
      var res = data.split('||OK||')
      if(res[1]=='CALCOK'){
        $('#val_portes').html('<span>'+res[2]+'&euro;</span>');
        $('#val_total').html('<span>'+res[3]+'&euro;</span>');
      }
    }
  })
}

function validapasso2(lg) {
  var tserv = document.getElementById('tserv');
  var end1 = document.getElementById('endfact');
  var end2 = document.getElementById('endentr');
  
  var hini = parseInt(document.getElementById('hora_de').value);
  var hfim = parseInt(document.getElementById('hora_at').value);
  var mini = parseInt(document.getElementById('min_de').value);
  var mfim = parseInt(document.getElementById('min_at').value);
  
  if(end1.checked == true) {
    // Dados de entrega iguais aos de faturação
    if(tserv.checked == true) {
      
      if(hini <= hfim) {
        
        if(hini < hfim) {
          
          return true;
        } else if(hini==hfim && mini<mfim) {
          
          return true;
        } else if(hini==hfim && mini==mfim) {
          
          if(lg=='pt') {
            alert('O horário de entrega inicial tem de ser diferente do horário de entrega final.');
          }
          if(lg=='gb') {
            alert('The initial delivery time must be different from the time of delivery.');
          }
          if(lg=='sp') {
            alert('El plazo de entrega inicial deberá ser diferente de la fecha de entrega.');
          }
          if(lg=='fr') {
            alert('Le délai de livraison initiale doit être différente de la date de livraison.');
          }
          return false;
        } else {
          
          if(lg=='pt') {
            alert('O horário de entrega está errado.');
          }
          if(lg=='gb') {
            alert('The delivery time is wrong.');
          }
          if(lg=='sp') {
            alert('El plazo de entrega está mal.');
          }
          if(lg=='fr') {
            alert('Le délai de livraison est erronée.');
          }
          return false;
        }
      } else {
        
        if(lg=='pt') {
          alert('O horário de entrega está errado.');
        }
        if(lg=='gb') {
          alert('The delivery time is wrong.');
        }
        if(lg=='sp') {
          alert('El plazo de entrega está mal.');
        }
        if(lg=='fr') {
          alert('Le délai de livraison est erronée.');
        }
        return false;
      }
      
    } else {
      if(lg=='pt'){
        alert('Tem de concordar com os termos do serviço.');
      }
      if(lg=='gb'){
        alert('You must agree to the terms of service.');
      }
      if(lg=='sp'){
        alert('Debe aceptar los términos del servicio.');
      }
      if(lg=='fr'){
        alert('Vous devez accepter les conditions de service.');
      }
      return false;
    }
  }
  
  if(end2.checked == true) {
    // Dados de entrega diferentes aos de faturação
    if(tserv.checked == true) {
      return verify_form_data(document.getElementById('basket_frm_p2'),'THISFORMDE',formErros);
    } else {
      if(lg=='pt'){
        alert('Tem de concordar com os termos do serviço.');
      }
      if(lg=='gb'){
        alert('You must agree to the terms of service.');
      }
      if(lg=='sp'){
        alert('Debe aceptar los términos del servicio.');
      }
      if(lg=='fr'){
        alert('Vous devez accepter les conditions de service.');
      }
      return false;
    }
  }
  
}


