$(document).ready(function(){
  feature.init();
  detailMap.init(0);

  // SEARCH FORM
  $('#search-word').blur(function () {
    if ($(this).val() == '') {
      $(this).val('Search keywords');
    }
  })
  
  $('#search-word').focus(function () {
    if ($(this).val() == 'Search keywords') {
      $(this).val('');
    }
  })

  var research = 0;
      research += $('.dg-post-type-research').length > 0 ? 1 : 0;
      research += $('.post-type-archive-research').length > 0 ? 1 : 0;

  if (research && document.cookie.indexOf('registered=true') === -1) {
    $.colorbox({
      href: BASE + "/register/",
      width: 450,
      height: 400,
      close: '',
      //overlayClose: false, Lisa 20120201
     // escKey: false
    }, function () {
      $('form').ajaxForm({
        beforeSubmit: function(formData, jqForm, options) {
          jqForm.wpcf7ClearResponseOutput();
          jqForm.find('img.ajax-loader').css({ visibility: 'visible' });
          return true;
        },
        beforeSerialize: function(jqForm, options) {
          jqForm.find('.wpcf7-use-title-as-watermark.watermark').each(function(i, n) {
            $(n).val('');
          });
          return true;
        },
        data: { '_wpcf7_is_ajax_call': 1 },
        dataType: 'json',
        success: function(data) {
          var ro = $(data.into).find('div.wpcf7-response-output');
          $(data.into).wpcf7ClearResponseOutput();

          if (data.invalids) {
            $.each(data.invalids, function(i, n) {
              $(data.into).find(n.into).wpcf7NotValidTip(n.message);
            });
            ro.addClass('wpcf7-validation-errors');
          }

          if (data.captcha)
            $(data.into).wpcf7RefillCaptcha(data.captcha);

          if (data.quiz)
            $(data.into).wpcf7RefillQuiz(data.quiz);

          if (1 == data.spam)
            ro.addClass('wpcf7-spam-blocked');

          if (1 == data.mailSent) {
            $(data.into).find('form').resetForm().clearForm();
            ro.addClass('wpcf7-mail-sent-ok');

            // CoreData custom
            var closeTimeout = window.setTimeout($.colorbox.close, 1500);
            //- Cookie
            var expires = new Date();
            expires.setDate(expires.getDate()+30);
            document.cookie = "registered=true; path=/; expires="+expires.toUTCString()+"\";";

            if (data.onSentOk)
              $.each(data.onSentOk, function(i, n) { eval(n) });
          } else {
            ro.addClass('wpcf7-mail-sent-ng');
          }

          if (data.onSubmit)
            $.each(data.onSubmit, function(i, n) { eval(n) });

          $(data.into).find('.wpcf7-use-title-as-watermark.watermark').each(function(i, n) {
            $(n).val($(n).attr('title'));
          });

          ro.append(data.message).slideDown('fast');
        }
      }); 
    }); 
  }

  // OUR CLIENTS
	$('#filter-clients').change(function () {
		location.href=$(this).val();
	})
	
	// MAIN NAVIGATION: add class .last 
	$('#main-nav li:last').addClass('last');
  
  // OUR PEOPLE
  $('.person').each(function(i){
    $(this).find('.person-read-more').addClass('person-read-more-'+i).click(function(){openPerson(i)});
    $(this).find('.person-content-more').addClass('person-content-more-'+i);
    $(this).find('.close').addClass('close-'+i).click(function(){closePerson(i)});
  });	

  function openPerson(i) {
    $('.person-read-more-'+i).fadeOut('fast');
    $('.close-'+i).fadeIn('fast');
    $('.person-content-more-'+i).toggle('fast');
    return false;
  }

  function closePerson(i) {
    $('.person-read-more-'+i).fadeIn('fast');
    $('.close-'+i).fadeOut('fast');
    $('.person-content-more-'+i).toggle('fast');
    return false;
  }

  // FAQs
  $('.faq').each(function(i){
    $(this).find('.faq-read-more').addClass('faq-read-more-'+i).click(function(){openFAQ(i)});
    $(this).find('.faq-content-more').addClass('faq-content-more-'+i);
    $(this).find('.close').addClass('close-'+i).click(function(){closeFAQ(i)});
  }); 

  function openFAQ(i) {
    $('.faq-read-more-'+i).hide();
    $('.close-'+i).show();
    $('.faq-content-more-'+i).toggle('fast');
    return false;
  }

  function closeFAQ(i) {
    $('.faq-read-more-'+i).show();
    $('.close-'+i).hide();
    $('.faq-content-more-'+i).toggle('fast');
    return false;
  }
	
});



// Feature slides
var feature = {
  config: {
    container: '.features',
    buttons: 'li',
    home: true
  },

  init: function () {
    var self = this;

    // Quit if no container.
    if (!$(self.config.container).length) {
      return false;
    }

    // Cache the main elements
    self.elems = {
      $container: $(self.config.container),
      $buttons: $(self.config.container).find(self.config.buttons)
    };

    self.setup();
  },

  setup: function () {
    var self = this,
        animOpen = {
          'duration': 200,
          'easing': 'easeInOutQuad',
          'queue': false
        },
        animClose = {
          'duration': 400,
          'easing': 'easeInOutQuad',
          'queue': false
        };

    // Hoverboards
    self.elems.$container.delegate(self.config.buttons, 'mouseover mouseout', function (e) {
      var $cur = $(this),
          curId = $cur.attr('id');

      // Check if animated to prevent animation conflicts
      if (e.type === 'mouseover') {
        self.elems.$buttons.addClass('inactive');

        $cur.removeClass()
            .addClass('active');
            //.animateToClass('.feature2-active', animOpen);

        //self.elems.$buttons.not($cur).animateToClass('.feature2-inactive', animClose);
      } else {
        self.elems.$buttons.removeClass();
            //.animateToClass('.feature2-default', animClose);
      }

    });

  }
};

var detailMap = {
  config: {
    mapContainerID: 'map',
    mapContainerClass:  '.contact-map',
    mapWrapper: 'map-wrapper',
    marker: 'marker'
  },

  map: {
    map: null,
    wrapper: null,
    markers: []
  },
  
  generated: false,
  
  init: function () {
    var self = this,
        i,
        map,
        marker,
        mapsLen = $(self.config.mapContainerClass).length;
    
    if (!mapsLen) {
      return false;
    }

    // Cache the maps
    self.elems = {
      $maps: $(self.config.mapContainerClass)
    };         
  
    for (i = 0; i < mapsLen; i+=1) {
      map = self.config.mapContainerID + i,
      marker = self.config.marker + i;

      self.elems['$'+map] = $('#'+map);
      self.elems['$'+marker] = $('#'+marker);

      self.generateMap(i);
    };

  },
  
  generateMap: function(num) {
    var self = this,
        $currentmap = self.elems['$map'+num],
        markers = self.generateMarkers(num),
        options = {
          zoom: 8,
          center: new google.maps.LatLng(-34.397, 150.644),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        },
        bounds = new google.maps.LatLngBounds();

    self.map.container = $('<div class="'+self.config.mapWrapper+'"></div>');

    $currentmap.html(self.map.container);    

    self.map['map'+num] = new google.maps.Map($currentmap.get(0), options);
    
    $(markers).each( function () {
      var point = new google.maps.LatLng(this.latitude, this.longitude);
      bounds.extend(point);
    });
 
    self.map['map'+num].fitBounds(bounds);

    self.addMarkers(markers, num);
    
    self.generated = true;
  },
  
  generateMarkers: function (num) {
    var self = this,
        marker = null,
        markers = [],
        $marker = self.elems['$marker'+num],
        icon = TEMPLATE_DIRECTORY + '/images/map/marker.png',
        hoverIcon = icon.replace('.png', '-hover.png');

    marker = {
      icon: icon,
      hoverIcon: hoverIcon,
      latitude: parseFloat( $marker.find('.marker-lat').text() ),
      longitude: parseFloat( $marker.find('.marker-lon').text() )
    };

    if (marker.latitude && marker.longitude) {
      markers.push(marker);
    }

    return markers;
  },

  addMarkers: function(markers, num) {
    var self = this,
        i,
        point,
        marker,
        curmap = 'map'+num,
        toAdd = markers.slice(0, 4); //get top 4
        markers = markers.slice(4); //remove top 4
        markersLen = toAdd.length;
  
    for (i = 0; i < markersLen; i += 1) {
      point = new google.maps.LatLng(toAdd[i].latitude, toAdd[i].longitude);
      marker = self.createMarker(toAdd[i], point, self.map['map'+num]);
    }

    if (markersLen) {
      setTimeout( function () { self.addMarkers(markers, num); }, 100 );
    } else {
      //check zoom level
      setTimeout( function () {
        var zoom = self.map[curmap].getZoom();
        
        if (zoom > 16) {
          self.map[curmap].setZoom(16);
        }
      }, 500);
    }
  },
  
  createMarker: function(marker, point, theMap)
  {
    var self = this;

    var customIcon = new google.maps.MarkerImage(
      marker.icon,
      new google.maps.Size(42, 56)
    );

    var gMarker = new google.maps.Marker({
      map: theMap,
      draggable: false,
      position: point,
      visible: true,
      icon: customIcon
    });
    gMarker.setClickable(false);
    return gMarker;
  }
};
