var CountryId = 0;
var BusinessId = 0;
var map;
var markers = new Array();


function ChangeOrganigrammeCountry(id) {
    $('.news-list-white h2').hide();
    $('#hc' + id).show();

    $('.nav-country > li a').removeClass('on')
    $('#c' + id).addClass('on');

    $('.diagram img').hide();
    $('#i' + id).show();
}

jQuery.validator.addMethod("initialMessage", function (initial_message, element) {
    return this.optional(element) || initial_message != element.defaultValue;
}, " ");  //adiciona metodo para mensagem inicial


jQuery.validator.addMethod("phone", function(value, element) {
    return this.optional(element) || /^((\+*)[0-9]*)$/.test(value);
  }, "Please enter a valid phone number"
);


function setCountry(id, name) {
    $('#countryId').val(id);
    $('#countryName').val(name);
    $('.drop-country > div > span').text(name);
    $('.drop-country ul').removeClass('on');
  $('.drop-country span').removeClass('error');
}

function newsletterForm() {
    var newsletterEmail = $('#newsletterEmail').val();
    var newsletterMessageText = $('#newsltterMessage').text();
    $('#newsletterEmail').focus(function () { if ($(this).val() == newsletterEmail) { $(this).val(''); } });
    $('#newsletterEmail').blur(function () { if ($(this).val() == '') { $(this).val(newsletterEmail); } });

    $('#newsletterSign').validate({
        errorPlacement: function (error, element) {
            error.hide();
            $('#newsltterMessage').text('O E-Mail indicado não é válido');
        },
        invalidHandler: function (form, validator) {
            var errors = validator.numberOfInvalids();

        },
        rules: {
           newsletterEmail: { initialMessage: true, email: true, required: true }
        },
        submitHandler: function () {

            $('#newsltterMessage').text("A enviar...");


            $.post('/base/Forms/SubmitNewsletterSubscriber.aspx',
                {

                    email: $('#newsletterEmail').val()
                },
                function (data) {
                    var jsonData = eval('(' + data + ')');
                    if (jsonData.Status) {
                      $('#newsletterEmail').val(newsletterEmail);
                      $('#newsltterMessage').text("Registo efectuado com sucesso");
                        setTimeout(changeNewslletterMessage, 5000);
                    }else{
                      $('#newsltterMessage').text(jsonData.Message);
                    }
                    
                }
            );



            return false;
        }
    });


}

function changeNewslletterMessage(){
  $('#newsltterMessage').text('* Campo Obrigatório');
}

function contactForm() {
    var subject= $('#subject').val();
    var firstName = $('#firstName').val();
    var lastName = $('#lastName').val();
    var countryId= $('#countryId').val();
    var countryName= $('#countryName').val();
    var phone = $('#phone').val();
    var email = $('#email').val();
    var message= $('#message').val();
    var company = $('#company').val();

    $('#subject').focus(function () {if ($(this).val() == subject) {$(this).val('');}});
    $('#subject').blur(function () { if ($(this).val() == '') { $(this).val(subject); } });

    $('#firstName').focus(function () { if ($(this).val() == firstName) { $(this).val(''); } });
    $('#firstName').blur(function () { if ($(this).val() == '') { $(this).val(firstName); } });

    $('#lastName').focus(function () { if ($(this).val() == lastName) { $(this).val(''); } });
    $('#lastName').blur(function () { if ($(this).val() == '') { $(this).val(lastName); } });

    $('#phone').focus(function () { if ($(this).val() == phone) { $(this).val(''); } });
    $('#phone').blur(function () { if ($(this).val() == '') { $(this).val(phone); } });

    $('#email').focus(function () { if ($(this).val() == email) { $(this).val(''); } });
    $('#email').blur(function () { if ($(this).val() == '') { $(this).val(email); } });

    $('#message').focus(function () { if ($(this).val() == message) { $(this).val(''); } });
    $('#message').blur(function () { if ($(this).val() == '') { $(this).val(message); } });

    $('#company').focus(function () { if ($(this).val() == company) { $(this).val(''); } });
    $('#company').blur(function () { if ($(this).val() == '') { $(this).val(company); } });


    $('#contactForm').validate({
        errorPlacement: function (error, element) {
            error.hide();
            
        },
        invalidHandler: function (form, validator) {
            var errors = validator.numberOfInvalids();
            
      if($('#countryId').val() == ''){
        $('.drop-country span').addClass('error');
      }
            /*if (errors == 2) {
            $('#newsMsg').text('Por favor insira o seu nome e email').css({ 'left': '8px', 'display': 'block' });
            } else if ($('body').validate().element("#newsNameInput")) {
            $('#newsMsg').text('Por favor insira um email v�lido').css({ 'left': '248px', 'display': 'block' });
            } else {
            $('#newsMsg').text('Por favor insira o seu nome').css({ 'left': '8px', 'display': 'block' });
            }*/
        },
        rules: {
            countryId: { required: true },
            subject: { initialMessage: true, required: true },
            firstName: { initialMessage: true, required: true },
            lastName: { initialMessage: true, required: true },
            company: { initialMessage: true, required: true },
            email: { initialMessage: true, required: true },
            phone: { initialMessage: true, required: true, phone:true },
            email: { initialMessage: true, email: true, required: true },
            message: { initialMessage: true, required: true }
        },
        submitHandler: function () {

            $('#formMessage').text("A enviar...");


            $.post('/base/Forms/SubmitContact.aspx',
                {
                    subject: $('#subject').val(),
                    firstName: $('#firstName').val(),
                    lastName: $('#lastName').val(),
                    countryId: $('#countryId').val(),
                    countryName: $('#countryName').val(),
                    phone: $('#phone').val(),
                    email: $('#email').val(),
                    message: $('#message').val(),
                    company: $('#company').val()
                },
                function (data) {
                    var jsonData = eval('(' + data + ')');
                    if (jsonData.Status) {
                        $('#subject').val(subject);
                        $('#firstName').val(firstName);
                        $('#lastName').val(lastName);
                        $('#countryId').val('');
                        $('#countryName').val(countryName);
                        $('#phone').val(phone);
                        $('#email').val(email);
                        $('#message').val(message);
                        $('#company').val(company);
                    }
                    $('#formMessage').text(jsonData.Message);
                }
            );



            return false;
        }
    });
}

function changePage(loadTo, callPage) {$(loadTo).load(callPage);}
function loadCompany(callPage, countryId, page, businessId, elem) {
    if (countryId != 0 && countryId != undefined && countryId != null) {
        CountryId = countryId;
        $('.nav-country > li a').removeClass('on')
        $('#c' + CountryId).addClass('on');
    }
    if (businessId != undefined && businessId != null) {BusinessId = businessId;}
    if (existe($('.drop-country span')) && elem != '') {$('.drop-country span').text(elem);}
    $.get(callPage + '?page=' + page + '&countryId=' + CountryId + '&businessId=' + BusinessId, function (data) {
        $('#companyList li:not(:first)').remove();

        $('#companyList').append(data);
    });
    $('#cPaging').load(callPage + 'Paginator?page=' + page + '&countryId=' + CountryId + '&businessId=' + BusinessId);
}

function changeCountry(cId) {
    if (cId != '') {
        $('.nav-country > li a').removeClass('on')
        $('#c' + cId).addClass('on');

        $('.contacts-list').hide();
        $('#ct' + cId).show();
    }
}

function createGMapMarker(latitude, longitude, cid) {
    var myLatlng = new google.maps.LatLng(latitude, longitude);
    var image = new google.maps.MarkerImage('/img/googleMapMarker.png', new google.maps.Size(52, 76), new google.maps.Point(0, 0), new google.maps.Point(15, 55));
    var marker = new google.maps.Marker({position: myLatlng, map: map, icon: image});
    google.maps.event.addListener(marker, 'click', function(){changeCountry(cid);});
    return marker;
}
function initialize() {
    var myLatlng = new google.maps.LatLng(countrysGMaps[0]['lat'], countrysGMaps[0]['lng']);
    var myOptions = { zoom: countrysGMaps[0]['zoom'], center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP, streetViewControl: true };
    map = new google.maps.Map(document.getElementById("gMap"), myOptions);
    for (var i = 0; i < countrysGMaps.length; i++) {countrysGMaps[i]['marker'] = createGMapMarker(countrysGMaps[i]['lat'], countrysGMaps[i]['lng'], countrysGMaps[i]['id']);}
}

function ChangeGMap(arrIndex) {
    var newCenter = new google.maps.LatLng(countrysGMaps[arrIndex]['lat'], countrysGMaps[arrIndex]['lng']);
    map.setCenter(newCenter);
    map.setZoom(countrysGMaps[arrIndex]['zoom']);
}

function showMarker(arrIds) {
    $('.map-wide img').hide();
    for (var i = 0; i < arrIds.length; i++) {
        $('#c' + arrIds[i]).show();
    }
    
}
// slider
function slider(slide, nav, larg) {
    
  //$(nav+' li:last-child').css('margin-right','0');
  var sliderActivo = 0;
  var sliderTimer = setTimeout(autoSlide,7200);
  var sliderCount = $(slide+' > ul li').size();
  var sliderWidth = larg * sliderCount;
  $('.controler .pos').html((sliderActivo + 1) + '/<strong>' + sliderCount + '</strong>');
  $('.controler h2:first').show();
  $('.controler h3:first').show();
  $('#ulSlider').css({ 'width': sliderWidth });
  $(nav + ' li').each(function () {
      $(this).bind('click', function () {
          intIndex = 0;
         
          switch ($(this).attr('class')) {
              case 'prev':
                  intIndex = sliderActivo - 1
                  break;
              case 'next':
                  intIndex = sliderActivo + 1
                  break;
          }
          if (intIndex < 0) {
              intIndex = 0;
          }
          if (intIndex > (sliderCount-1)) {
              intIndex = (sliderCount - 1);
          }
          reseTimer();
          sliderActivo = intIndex;
          $('#ulSlider').stop().animate({ left: '-' + (intIndex * larg) + 'px' }, 900, 'easeInOutExpo');
          $(nav + ' .pos').html((sliderActivo + 1) + '/<strong>' + sliderCount + '</strong>');
          $('.controler h2').hide();
          $('.controler h3').hide();
          $('.controler h2:eq(' + sliderActivo + ')').show();
          $('.controler h3:eq(' + sliderActivo + ')').show();
          return false;
      });
  });
  $(slide).fadeIn();
  function autoSlide(){
    sliderActivo == sliderCount-1 ? sliderActivo=0 : sliderActivo++;
    $('#ulSlider').stop().animate({ left: '-' + (sliderActivo * larg) + 'px' }, 900, 'easeInOutExpo');
    $('.controler .pos').html((sliderActivo + 1) + '/<strong>' + sliderCount + '</strong>');
    $('.controler h2').hide();
    $('.controler h3').hide();
    $('.controler h2:eq(' + sliderActivo + ')').show();
    $('.controler h3:eq(' + sliderActivo + ')').show();
    reseTimer();
  }
  function reseTimer(){
    clearTimeout(sliderTimer);
    sliderTimer = setTimeout(autoSlide,5500);
  }
}

function sliderGal() {
  var galIndex = 0;
  var nGalIndex = 0;  
  var sliderGalIndex = 0;
  var sliderGalCount = $('#galImg img').size();
  var sliderImgWidth = 600*sliderGalCount;
  var sliderThumbsWidth = 165*sliderGalCount;
  var sliderTimerGal = setTimeout(autoSlideGal,5200);
  
  $('#galImg div').css({'width':sliderImgWidth});
  $('#galSlider').css({'width':'5000px'});
  $('#galTxt div:first').show();
  $('#galSlider li:first div').show();
  
  $('#galLeft').bind("mouseenter",function(){
    if (sliderGalIndex>0) $(this).css({'backgroundPosition':'-79px -442px','cursor':'pointer'});
  });
  $('#galRight').bind("mouseenter",function(){
    if (sliderGalIndex<sliderGalCount-3) $(this).css({'backgroundPosition':'-610px -442px','cursor':'pointer'});
  });
  $('#galLeft').bind("mouseleave",function(){
    $(this).css({'backgroundPosition':'-79px -332px','cursor':'default'});
  });  
  $('#galRight').bind("mouseleave",function(){
    $(this).css({'backgroundPosition':'-610px -332px','cursor':'default'});
  });
  $('#galLeft').bind("click",function(){  
    if (sliderGalIndex>0) {
      sliderGalIndex -= 1;
      $('#galSlider').stop().animate({left: '-'+(sliderGalIndex*165)+'px'}, 300, "easeInOutExpo");
      if (sliderGalIndex==0) $(this).css({'backgroundPosition':'-79px -332px','cursor':'default'});
      reseTimerGal();
      return false;
    } else {return false}  
  });  
  $('#galRight').bind("click",function(){
    if (sliderGalIndex<sliderGalCount-3){
      sliderGalIndex += 1;
      $('#galSlider').stop().animate({left: '-'+(sliderGalIndex*165)+'px'}, 300, "easeInOutExpo");
      if (sliderGalIndex==sliderGalCount-3) $(this).css({'backgroundPosition':'-610px -332px','cursor':'default'});
      reseTimerGal();
      return false;
    } else {return false}  
  });  
  $('#galSlider li').each(function(intIndex){  
    $(this).bind("click",function(){
      nGalIndex = intIndex;
      $('#galTxt div:eq('+galIndex+')').fadeOut(function(){
        $('#galTxt div:eq('+intIndex+')').fadeIn();
        galIndex = nGalIndex;
      });
      $('#galImg div').stop().animate({left: '-'+(intIndex*600)+'px'}, 900, "easeInOutExpo");
      $('#galSlider li').removeClass();
      $('#galSlider li div').hide();
      $('div', this).show();
      reseTimerGal();
      return false;
    });
    $(this).bind("mouseenter",function(){
      $('div', this).show();
    });
    $(this).bind("mouseleave",function(){
      if (nGalIndex!=intIndex) $('div', this).hide();
    });
  });
  function autoSlideGal(){
    if (nGalIndex == sliderGalCount-1) {
      nGalIndex=sliderGalIndex=0;
      $('#galSlider').stop().animate({left: '0px'}, 900, "easeInOutExpo");    
    } else {
      nGalIndex++;
      if (nGalIndex > 2) {
        sliderGalIndex=nGalIndex-2;
        $('#galSlider').stop().animate({left: '-'+(sliderGalIndex*165)+'px'}, 900, "easeInOutExpo");
      } else {
        sliderGalIndex=0;
        $('#galSlider').stop().animate({left: '0px'}, 900, "easeInOutExpo");
      }  
    }    
    $('#galImg div').stop().animate({left: '-'+(nGalIndex*600)+'px'}, 900, "easeInOutExpo");
    $('#galTxt div:eq('+galIndex+')').fadeOut(function(){
      $('#galTxt div:eq('+nGalIndex+')').fadeIn();
      galIndex = nGalIndex;
    });    
    $('#galSlider li').removeClass();
    $('#galSlider li div').hide();
    $('#galSlider li div:eq('+nGalIndex+')').show();  
    reseTimerGal();
  }
  function reseTimerGal(){
    clearTimeout(sliderTimerGal);
    sliderTimerGal = setTimeout(autoSlideGal,5500);
  }  
}

function existe(x) {
    if ($(x).length > 0) return true;
}

function querySt(ji) {
    hu = window.location.search.substring(1);
    gy = hu.split("&");
    for (i = 0; i < gy.length; i++) {
        ft = gy[i].split("=");
        if (ft[0] == ji) {
            return ft[1];
        }
    }
}
function doSearch(pageNumber) {
    
    var html = '';
    var nav = '';
    $.post('/base/Search/GetResults/' + pageNumber + '.aspx', { query: querySt('query') },
    function (data) {
        var jsonData = eval('(' + data + ')');


        if (jsonData.TotalPages > 0) {
            for (var i = 0; i < jsonData.List.length; i++) {
                var liClass = '';
                if (i % 2 != 0) {
                    liClass = 'class="news-list-grey bg"';
                } else {
                    liClass = '';
                }
                html += '<li ' + liClass + ' onClick="location.href=\'' + jsonData.List[i].Link + '\'"><div>';

                html += '<h3>' + jsonData.List[i].Titulo + '</h3>';
                var txt = jsonData.List[i].Texto;
                if (txt.length == 0) {
                    txt = '&nbsp;';
                }
                html += '<p><strong>' + txt + '</strong></p></div>';
                if (jsonData.List[i].Link != '#') {
                    html += '<div class="ref"><a href="' + jsonData.List[i].Link + '" class="more">Saber mais</a></div>';
                }
                html += '</li>';
            }

            if (jsonData.TotalPages > 1) {
                nav = '<ul class="nav-dot alone">';
                var linkBefore = '';
                var linkAfter = '';
                if (jsonData.Page > 1) {
                    linkBefore = 'onclick="javascript:doSearch(' + (jsonData.Page - 1) + ')"';
                }
                if (jsonData.Page < jsonData.TotalPages) {
                    linkAfter = 'onclick="javascript:doSearch(' + (jsonData.Page + 1) + ')"';
                }

                nav += '<li class="prev" ' + linkBefore + '>Previous</li>';
                nav += '<li class="pos">' + jsonData.Page + '/<strong>' + jsonData.TotalPages + '</strong></li>';
                nav += '<li class="next" ' + linkAfter + '>Next</li>';
                nav += '</ul>';
            }

        }
        $('.work').html(html);
        //$('.nav-dot.alone').html(nav);
        $('#navS').html(nav);
        var saux = resources["Foram_encontrados"];
        saux = saux.replace("{0}", jsonData.TotalResults);
        $('.top-header.transparent-white h2 em').html(saux);
    });

}

$(document).ready(function () {

    //    $("#s1EstadoCivTxt").change(function () {
    //        alert("ssss");
    //    });


    if (existe('.breadcrumbs')) {
        $('.wrapper').prepend('<div class="bc"></div>');
        $('.top-bar').css('margin-bottom', '74px');
    }
    if (existe('#sliderHome')) slider('#sliderHome', '.controler', 1000); // sliderHome
    if (existe('#contactForm')) contactForm();
    if (existe('#galImg')) sliderGal();
    newsletterForm();
    setTimeout(mmFunction, 500);
    function mmFunction() {
        var mmList = $('#mm li').not('#mm ul li');
        mmList.each(function (intIndex) {

            $('.abs', this).css({ 'float': 'left', 'visibility': 'hidden', 'display': 'block' });
            var larg1 = $('.abs div:first', this).outerWidth();
            var larg2 = Number($('.abs div:first div', this).outerWidth() + 10);
            $('.abs', this).css({ 'float': 'none', 'visibility': 'visible', 'display': 'none' });
            if (larg1 > larg2) {
                $('.abs', this).css({ 'position': 'absolute', 'width': larg1 });
                $('ul li', this).css({ 'width': Number(larg1 - 24) });
                $('.bottom div', this).css({ 'width': Number(larg1 - 6) });
            } else {
                $('.abs', this).css({ 'position': 'absolute', 'width': larg2 });
                $('ul li', this).css({ 'width': Number(larg2 - 24) });
                $('.bottom div', this).css({ 'width': Number(larg2 - 6) });
            }
            $(this).mouseenter(function () {
                $('.abs', this).show();
            });
            $('.abs', this).mouseleave(function () {
                $(this).hide();
            });
        });
    }
    var searchInputVal = $('#searchInput').val();
    $('#searchInput').focus(function () {
        if (searchInputVal == $(this).val()) {
            $(this).val('');
        }
    });
    $('#searchInput').blur(function () {
        if ($(this).val() == '') {
            $(this).val('Pesquisar...');
        }
    });

    $('#searchForm').submit(function () {
        if ($('#searchInput').val() != 'Pesquisar...' && $('#searchInput').val() != '') {
            window.location = SEARCHURL+'?query=' + $('#searchInput').val();
        }
        return false;
    })
    $('.img-border:last > div').css('margin-bottom', '0px');

});


function GetOptDetail(url, contentor) {

    $.get(url, function (data) {
        if (data != '') {
            $(contentor).html(data);
        }
    });
}

function GetNewPageOpt(url, contentor) {

    $.get(url, function (data) {
        if (data != '') {
            $(contentor).html(data);
        }
    });
}


//#ulSlider

//


