initCufon();

$(document).ready(function() {
  makeGalleryBoxesEqual('body.home .box .row');
  initFilterSidebar();
  styleFilterSidebarForm();
  initFilterMap();
  initTabs();
  initSearchEngineTabs();
  initAddToClipboard();
  initImagePreview();
  makeItemClickable();
});

function initCufon() {
  Cufon.replace('.cufon1');
  Cufon.replace('.cufon2',{fontWeight: 600 });
}

function styleFilterSidebarForm() {
  sidebar = $('#filter-sidebar');
  sidebar.find('.cbx:has(:checked)').addClass('checked');
  sidebar.find('.cbx input').change(function() {
    $(this).parent().toggleClass('checked');
  });
  sidebar.addClass('styled');
}

function initAddToClipboard() {
  $('.std-list a.clipboard, div.company-summary .clipboard').click(function(e) {
    e.preventDefault();

    $(this).toggleClass('in-clipboard');
    $(this).text($(this).hasClass('in-clipboard') ? 'Usuń ze schowka' : 'Dodaj do schowka');

    $('#clipboard-container').load(this.href);
  });
}

function initSearchEngineTabs() {
  $('#search-engine .tabs a').click(function() {
	var reload = false;
	if ($(this).parent().attr('class') == 'reload')
	{
		reload = true;
	}
    var tabname = $(this).attr('class');
    $(this).parents('ul').find('li').removeClass('active');
    $(this).parent().addClass('active');
    $('#search-engine').find('input[name=type]').val(tabname);
    $.cookie('csearch', tabname, { path: '/' });
    if (reload)
    {
    	$('#quick-search-form [name=new-search]').val('new-search');
    	$('#quick-search-form').submit();
    }
    return false;
  });
  $('#place').autocomplete(ac_places, {width: 300});

  setIntroInputText($('#query'), 'Np. usługi budowlane');
  setIntroInputText($('#place'), 'Np. miasto, województwo');
}

function setIntroInputText(input, text) {
  if (input.val() == '')
    input.addClass('empty').val(text);

  input.focus(function() {
    $(this).removeClass('empty');
    if ($(this).val() == text)
      $(this).val('');
  });
  input.blur(function() {
    if ($(this).val() == '') {
      $(this).addClass('empty');
      $(this).val(text);
    }
  });
}

var onTabShow = null;
function initTabs() {
  function activateTab(link) {
    $('#main .tabs li, .tabpane').removeClass('active');
    tabname = link.attr('href').substring(1);
    fulltabname = '#tab-' + tabname; 
    link.parent().addClass('active');

    $(fulltabname).addClass('active');
    if (onTabShow)
      onTabShow(tabname);
  };
  $('#main .tabs a').click(function() {
    activateTab($(this));
  });
  if (location.hash.length > 0) {
    activateTab($('a[href='+location.hash+']'));
  }
}

function makeGalleryBoxesEqual(rows) {
  var rows = $(rows);
  rows.each(function(index) {
    var maxHeight = 0;
    var headers = $(this).find('.item .sub h4');
    headers.each(function() {
      var h = $(this).height();
      if (h > maxHeight)
        maxHeight = h;
    });
    headers.height(maxHeight);

    maxHeight = 0;
    var items = $(this).find('.item .sub');
    items.each(function() {
      var h = $(this).height();
      if (h > maxHeight)
        maxHeight = h;
    });
    items.height(maxHeight);
  });
}

function initFilterSidebar() {
  $('#filter-sidebar .more a').toggle(
    function() {
      $(this).parents('.set').find('.hide').show();
      $(this).addClass('toggled').text('Zwiń');
      return false;
    },
    function() {
      $(this).parents('.set').find('.hide').hide();
      $(this).text('Pokaż więcej').removeClass('toggled');
      return false;
    }
  );
  $('#filter-sidebar .append a').click(function() {
    var item = $(this).closest('.set').find('.new-item');
    item.css({'display': 'block'});
    item.find('input').focus();
    return false;
  });
}

// ----

var filters = {
  map: null,
  geocoder: null,
  marker: null
}

function removeMarker(marker) {
  if (marker != null) {
    marker.setMap(null);
    marker = null;
  }
}

function initFilterMap() {
  var selectMapPosTrigger = $('#select-map-pos-trigger');

  selectMapPosTrigger.overlay({
    close: '.cancel',
    onLoad: function() {
      zoom = 6;
      if (filters.marker == null) {
        geo_x = $('#geo-x').val();
        geo_y = $('#geo-y').val();

        removeMarker(filters.marker);

        if (geo_x != '' && geo_y != '') {
          filters.marker = new google.maps.Marker({position: new google.maps.LatLng(geo_y, geo_x), draggable: true});
          zoom = 13;
        }
        else {
          filters.marker = new google.maps.Marker({position: new google.maps.LatLng(52.07950600379697, 19.09423828125), draggable: true});
        }
      }
      if (filters.map === null) {
        filters.map = new google.maps.Map(document.getElementById('filter-map'), {zoom: zoom, center: filters.marker.position, mapTypeId: google.maps.MapTypeId.ROADMAP});
      }
      filters.marker.setMap(filters.map);
    }
  });

  $('#dist-filter').change(function() {
    if ($(this).is(':checked')) {
      selectMapPosTrigger.click();
    }
  });

  selectMapPos = $('#select-map-pos');
  selectMapPos.find('form').submit(function(e) {
    var address = $(this).find('input[name=address]').val();
    if (address.length > 2) {
      if (filters.geocoder === null)
        filters.geocoder = new google.maps.Geocoder();
      filters.geocoder.geocode({'address': address}, function(results, status) {
        if (status != google.maps.GeocoderStatus.OK) {
          alert('Nie znaleziono podanego adresu.');
        }
        else {
          removeMarker(filters.marker);
          filters.map.setCenter(results[0].geometry.location);
          filters.map.setZoom(15);

          filters.marker = new google.maps.Marker({position: results[0].geometry.location, map: filters.map, draggable: true});
        }
      });
    }
    return e.preventDefault();
  });

  selectMapPos.find('.save').click(function() {
    if (filters.marker === null) {
      alert('Podaj lokalizację.');
      return false;
    }
    selectMapPosTrigger.overlay().close();

    point = filters.marker.position;
    $('#geo-x').val(point.c);
    $('#geo-y').val(point.b);
    $('#dist-filter').attr('checked', 'checked');
    $('#dist-filter').parent().addClass('checked');

    mapUrl = 'http://maps.google.com/maps/api/staticmap?center='+point.toUrlValue()+'&zoom=13&size=148x148&markers=size:mid|color:green|'+point.toUrlValue()+'&sensor=false';
    $('#filter-map-preview').empty().append($('<img/>', {'src': mapUrl}));

    return false;
  });
}

function showCompanyLocationMap(elementId, latitude, longitude, accuracy, company) {
  var point  = new google.maps.LatLng(latitude, longitude);
  var mapOptions = { 
    zoom: accuracy,
    center: point,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById(elementId), mapOptions);

  var marker = new google.maps.Marker({position: point});
  marker.setMap(map);

  if (company.name != '') {
    var puff = '<p style="min-height: 60px"><strong>'+company.name+'</strong><br />'+company.address+'<br />'+company.zip+' '+company.city+'</p>';
    var infowindow = new google.maps.InfoWindow({content: puff});
    infowindow.open(map, marker);
  }
}

function showCompaniesOnMap(elementId, coordinates, accuracy) {
  var point  = new google.maps.LatLng(52.4, 19.29);
  var mapOptions = { 
    zoom: accuracy,
    center: point,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById(elementId), mapOptions);
  var bounds = new google.maps.LatLngBounds();
  var infowindow = new google.maps.InfoWindow();
  
  function markerAdd(lat, lng, txt, id){
  	var point  = new google.maps.LatLng(lat, lng);
  	var marker = new google.maps.Marker({position: point});
  	marker.txt = txt;
  	marker.setMap(map);
  	google.maps.event.addListener(marker,"click",function()
	{
		infowindow.setContent(marker.txt);
		infowindow.open(map,marker);
	});
	google.maps.event.addDomListener(document.getElementById(id), 'mouseover', function()
	{
		infowindow.setContent(marker.txt);
		infowindow.open(map,marker);
	});
	bounds.extend(point)
	return marker;
  }
  
  for (coordinate in coordinates)
  {
  	marker = markerAdd(coordinates[coordinate]['latitude'], 
  					coordinates[coordinate]['longitude'], 
  					'<p style="min-height: 60px"><strong>'+coordinates[coordinate]['name']+'</strong><br />'+coordinates[coordinate]['address']+'<br />'+coordinates[coordinate]['zip']+' '+coordinates[coordinate]['city']+'<br />'+'<a href='+coordinates[coordinate]['url']+'>'+'Wizytówka'+'</a>'+'</p>',
  					coordinates[coordinate]['company_id'])
  }
  if (coordinates.length > 0)
  {
  	map.fitBounds(bounds);
  }
}

var directionsService;
var directionsDisplay;
function loadRoadMap() {
  var mapOptions = {
    zoom: 6,
    center: new google.maps.LatLng(52.40241887397331, 17.9736328125),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById('road-map'), mapOptions);

  directionsService = new google.maps.DirectionsService();
  directionsDisplay = new google.maps.DirectionsRenderer({map: map, panel: document.getElementById('road-tips')});
}

function findRoad()
{
  var start = document.getElementById('adres1').value;
  var end = document.getElementById('adres2').value;
  var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    } else {
      alert('Nie można znaleźć trasy.');
    }
  });
}

function initImagePreview() {
  $('a.preview').fancybox();
  $('a.preview_reference').fancybox({titleShow:true, titlePosition:'inside'});
  $('a.video-preview').fancybox({type: 'iframe', width: 640, height: 510});
}

function makeItemClickable() {
  $('.std-list .item').click(function(e) {
    if (!$(e.target).is('a') && e.button == 0) {
      location.href = $(this).find('h3 a').get(0).href;
    };
  });

  $('body.home .item, #tab-produkty .item').click(function(e) {
    if (!$(e.target).is('a') && e.button == 0) {
      location.href = $(this).find('h4 a').get(0).href;
    };
  });
}

