var if_det = false;

function enable_all() {
  $('input.disch').attr('disabled','');
}

function open_map_window(url) {
  var nw = window.open(url, 'nw', 'height=500,width=500,status=yes');
  if (!nw.opener) nw.opener = self;
  if (window.focus) nw.focus();
  return false;
}

function load_basic() {
  var point  = new google.maps.LatLng(lat, long);
  var mapOptions = { 
    zoom: acc,
    center: point,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);

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

  if (name!="" && add!="" && zip!="" && city!="") {
    var puff = '<div style="position:relative; float:left;"><br /><strong>'+name+'</strong><br />'+add+'<br />'+zip+' '+city+'</div><div style="padding-left:5px;"><br /></div>'
    var infowindow = new google.maps.InfoWindow({content: puff});
    infowindow.open(map, marker);
  }
}

var directionsService;
var directionsDisplay;

function znajdzDojazd() // funkcja znajduje dojazd
{
  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 load_road()
{
  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('wskazowki')});
}

function tekstBledu(blad)
{
  switch(blad)
  {
    case G_GEO_MISSING_QUERY:
    case G_GEO_MISSING_ADDRESS: var tekst = 'Nie podano adresu!'; break;
    case G_GEO_UNAVAILABLE_ADDRESS:
    case G_GEO_BAD_REQUEST:
    case G_GEO_SERVER_ERROR:
    case G_GEO_UNKNOWN_ADDRESS: var tekst = 'Adres nie został odnaleziony. Usuń ulicę, jeżeli ją podałeś i sprawdź ponownie.'; break;
    case G_GEO_TOO_MANY_QUERIES: var tekst = 'Przekroczono limit zapytań do strony Google'; break;
    default: var tekst = 'Nie udało się znaleźć przejazdu pomiędzy podanymi punktami';
  }
  return tekst;
}

function add_cat_ct(v)
{
  ctall = parseInt($('span#ct_all').html());
  ctall++;
  $('span#ct_all').html(ctall);
  cat_ct = $('span#scat'+v).html();
  if (cat_ct == null || cat_ct == "")
    cat_ct = 0;
  cat_ct = parseInt(cat_ct);
  cat_ct++;
  $('span#scat'+v).html(cat_ct);
  $('span#lb'+v).show();
  $('span#rb'+v).show();
  if (ctall>10)
  {
    to_del = ctall - 10;
    txt1 = "Można wybrać maksymalnie 10 kategorii.<br />"
    txt2 = "<span style='font-weight:normal;color:#000000;'>Ilość kategorii do usunięcia: <strong>" + to_del + "</strong></span>";
    $('div#ct_all_txt').html(txt1+txt2);
  }
}

function clipboard_add(id)
{
      $.getJSON('/schowek/dodaj', { id: id, type:'company' }, function(data, textStatus){
          if (textStatus == 'success')
          {
             if (data.all>0)
              {
              $('div#clipboard').show();
              $('span#ccount').html(data.all);
            }
            $('div#s'+id).removeClass("fico_c");
            $('div#s'+id).addClass("fico_c_shift");
            $('a#cid'+id).html('usuń ze schowka');
            $('div#schowek').removeClass("fico_c");
            $('div#schowek').addClass("fico_c_shift");
            $('a#span_clip').html('usuń ze schowka');
          }
        }, type='xml');
}

function clipboard_sub(id)
{
  $.getJSON('/schowek/usun', { id: id, type:'company' }, function(data, textStatus) {
    if (textStatus == 'success')
    {
      if (data.all>0)
      {
        $('div#clipboard').show();
        $('span#ccount').html(data.all);
      }
      else
        $('div#clipboard').hide();

      $('div#s'+id).removeClass("fico_c_shift");
      $('div#s'+id).addClass("fico_c");
      $('div#schowek').removeClass("fico_c_shift");
      $('div#schowek').addClass("fico_c");
      $('a#cid'+id).html('dodaj do schowka');
      $('a#span_clip').html('dodaj do schowka');
    }
  }, type='xml');
}

function clipboard_p_add(id)
{
  $.getJSON('/schowek/dodaj', { id: id, type:'product' }, function(data, textStatus){
      if (textStatus == 'success')
      {
         if (data.all>0)
          {
          $('div#clipboard').show();
          $('span#ccount').html(data.all);
        }
        if (if_det == false)
        {
          $('div#s'+id).removeClass("fico_c");
          $('div#s'+id).addClass("fico_c_shift");
          $('div#pschowek').removeClass("fico_c");
          $('div#pschowek').addClass("fico_c_shift");
        }
        $('a#cid'+id).html('usuń ze schowka');
        $('a#pspan_clip').html('usuń ze schowka');
      }
    }, type='xml');
}

function clipboard_p_sub(id)
{
  $.getJSON('/schowek/usun', { id: id, type:'product' }, function(data, textStatus){
      if (textStatus == 'success')
      {
         if (data.all>0)
          {
          $('div#clipboard').show();
          $('span#ccount').html(data.all);
        }
        else
          $('div#clipboard').hide();
        if (if_det == false)
        {
          $('div#s'+id).removeClass("fico_c_shift");
          $('div#s'+id).addClass("fico_c");
          $('div#pschowek').removeClass("fico_c_shift");
          $('div#pschowek').addClass("fico_c");
        }
        $('a#cid'+id).html('dodaj do schowka');
        $('a#pspan_clip').html('dodaj do schowka');
      }
    }, type='xml');
}

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').click(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');

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

    return false;
  });
}

$(document).ready(function() {

  //************* podświetlanie buttonów

  $('td.b_on').mouseover(function()
  {
    var bg_id = $(this).attr('id');
    var part_nr = (bg_id[bg_id.length-2]+bg_id[bg_id.length-1]);
    $('td#b_top_'+part_nr).css('background','url(/img/fp_top_on.gif)');
    $('td#b_mid_'+part_nr).css('background','url(/img/fp_mid_on.gif)');
    $('td#b_bot_'+part_nr).css('background','url(/img/fp_bot_on.gif)');
  });

  $('td.b_on').mouseout(function()
  {
    var bg_id = $(this).attr('id');
    var part_nr = (bg_id[bg_id.length-2]+bg_id[bg_id.length-1]);
    $('td#b_top_'+part_nr).css('background','url(/img/fp_top.gif)');
    $('td#b_mid_'+part_nr).css('background','url(/img/fp_mid.gif)');
    $('td#b_bot_'+part_nr).css('background','url(/img/fp_bot.gif)');
  });

  $('td.b_gold').mouseover(function()
  {
    var bg_id = $(this).attr('id');
    var part_nr = (bg_id[bg_id.length-2]+bg_id[bg_id.length-1]);
    $('td#b_top_gold_'+part_nr).css('background','url(/img/fp_top_gold_on.gif)');
    $('td#b_mid_gold_'+part_nr).css('background','url(/img/fp_mid_gold_on.gif)');
    $('td#b_bot_gold_'+part_nr).css('background','url(/img/fp_bot_gold_on.gif)');
  });

  $('td.b_gold').mouseout(function()
  {
    var bg_id = $(this).attr('id');
    var part_nr = (bg_id[bg_id.length-2]+bg_id[bg_id.length-1]);
    $('td#b_top_gold_'+part_nr).css('background','url(/img/fp_top_gold.gif)');
    $('td#b_mid_gold_'+part_nr).css('background','url(/img/fp_mid_gold.gif)');
    $('td#b_bot_gold_'+part_nr).css('background','url(/img/fp_bot_gold.gif)');
  });

  //************************************

  $('input.chb').click(function()
  {
    v = $(this).attr('id');
    chck = $(this).attr('checked');

    // *** zliczanie wszystkich ***
    ctall = parseInt($('span#ct_all').html());
    if (chck) ctall++;
    else ctall--;
    $('span#ct_all').html(ctall);
    if (ctall>10)
    {
      to_del = ctall - 10;
      txt1 = "Można wybrać maksymalnie 10 kategorii.<br />"
      txt2 = "<span style='font-weight:normal;color:#000000;'>Ilość kategorii do usunięcia: <strong>" + to_del + "</strong></span>";
      $('div#ct_all_txt').html(txt1+txt2);
      $('input#sbut').attr('disabled','disabled');
      $('input#sbut').css({'background-color' : '#cccccc'});
    }
    else
    {
      $('div#ct_all_txt').html('');
      $('input#sbut').removeAttr('disabled');
      $('input#sbut').css({'background-color' : '#9c0834'});
    }
    // *** ***

    v = v.substring(5);
    cat_ct = $('span#scat'+v).html();
    if (cat_ct == null || cat_ct == "")
      cat_ct = 0;
    cat_ct = parseInt(cat_ct);
    if (chck) cat_ct++;
    else cat_ct--;
    $('span#scat'+v).html(cat_ct);
    if (cat_ct > 0)
    {
      $('span#lb'+v).show();
      $('span#rb'+v).show();
    }
    else
    {
      $('span#lb'+v).hide();
      $('span#rb'+v).hide();
    }
  });

  $('div.g_picture').mouseover(function()
  {
    $(this).css('background-color','#cccccc');
  });
  $('div.g_picture').mouseout(function()
  {
    $(this).css('background-color','');
  });

  $('a.a_clip').click(function()
  {
    if_det = true;
    k = $(this).parent().parent().parent().attr('id');
    $('div#'+k).hide();
    clipboard_sub(k.substring(4));
    p = parseInt($('span#clip_count').html());
    p = p - 1;
    $('span#clip_count').html(p);
    if (p == 0) $('div#no_comp').show();
  });

  $('a.ap_clip').click(function()
  {
    if_det = true;
    k = $(this).parent().parent().parent().attr('id');
    $('div#'+k).hide();
    clipboard_p_sub(k.substring(5));
    p = parseInt($('span#pclip_count').html());
    p = p - 1;
    $('span#pclip_count').html(p);
    if (p == 0) $('div#pno_comp').show();
  });

  $('a.span_clip').click(function()
  {
    var aux = $(this).parent().attr('id');
    aux = $('div#'+aux).attr('class');
    var cid_tmp = $(this).attr('id');
    cid = parseInt(cid_tmp.substring(3));
    if (aux == "fico_c_shift") {
      clipboard_sub(cid);
    }
    else {
      clipboard_add(cid);
    }
  });

  $('a.pspan_clip').click(function()
  {
    var aux = $(this).parent().attr('id');
    aux = $('div#'+aux).attr('class');
    var cid_tmp = $(this).attr('id');
    cid = parseInt(cid_tmp.substring(3));
    if (aux == "fico_c_shift") {
      clipboard_p_sub(cid);
    }
    else {
      clipboard_p_add(cid);
    }
  });

  $('a#span_clip').click(function()
  {
    var aux = $('div#schowek').attr('class');
    if (aux == "fico_c_shift") {
      clipboard_sub(cid);
    }
    else {
      clipboard_add(cid);
    }
  });

  $('a#pspan_clip').click(function()
  {
    var aux = $('div#pschowek').attr('class');
    if (aux == "fico_c_shift") {
      clipboard_p_sub(cid);
    }
    else {
      clipboard_p_add(cid);
    }
  });

  $('input#gallery_br').click(function()
  {
    $('div#gallery_ok').hide();
  });

  $('input.chb').click(function()
  {
    saux = "s" + $(this).parent().attr('id');
    number = $("span#"+saux).html();
    if (number == "") number=0;
    number = parseInt(number);
    number+=1;
    $("span#"+saux).html();
  });

  if ($('div#map').attr('id')) {
    load_basic();
  }
  if ($('div#road_map').attr('id')) {
    load_road();
  }

  $('body').focus(function()
  {
    var txt1 = $('input#log_log').attr('value');
    if (txt1=='') $('input#log_log').attr('value', 'Login');
    var txt2 = $('input#log_pas').attr('value');
    if (txt2=='') $('input#log_pas').attr('value', 'jakieshaslo');
  });

  $('input#log_log').click(function()
  {
    $(this).attr('value','');
  });

  $('input#log_pas').click(function()
  {
    $(this).attr('value','');
  });

  $('div.search_ch_produkt').hide();
  //$('div#firma_pass').hide();

  $('a#search_2').css('background','url("/img/search_links.gif") no-repeat 0px -27px');
  //$('a#firma_2').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');

  $('a#firma_2').click(function()
  {
    $('a#firma_1').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $('a#firma_3').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $('a#firma_4').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $(this).css('background','url("/img/pa/bg_links.gif") no-repeat 0px 0px');
    $('div#firma_info').hide();
    $('div#gallery_foto').hide();
    $('div#gallery_add').hide();
    $('div#firma_pass').show();
  });
  $('a#firma_1').click(function()
  {
    $('a#firma_2').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $('a#firma_3').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $('a#firma_4').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $(this).css('background','url("/img/pa/bg_links.gif") no-repeat 0px 0px');
    $('div#firma_pass').hide();
    $('div#gallery_foto').hide();
    $('div#gallery_add').hide();
    $('div#firma_info').show();
  });
  $('a#firma_3').click(function()
  {
    $('a#firma_1').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $('a#firma_2').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $('a#firma_4').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $(this).css('background','url("/img/pa/bg_links.gif") no-repeat 0px 0px');
    $('div#firma_pass').hide();
    $('div#firma_info').hide();
    $('div#gallery_add').hide();
    $('div#gallery_foto').show();
  });
  $('a#firma_4').click(function()
  {
    $('a#firma_1').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $('a#firma_2').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $('a#firma_3').css('background','url("/img/pa/bg_links.gif") no-repeat -123px 0px');
    $(this).css('background','url("/img/pa/bg_links.gif") no-repeat 0px 0px');
    $('div#firma_pass').hide();
    $('div#firma_info').hide();
    $('div#gallery_foto').hide();
    $('div#gallery_add').show();
  });

  var COOKIE_NAME_SEARCH = 'csearch';
  smenu_status = $.cookie(COOKIE_NAME_SEARCH);

  if (smenu_status == null || smenu_status == "") smenu_status = "search_2";

  if (smenu_status == "search_2")
  {
    $('a#search_1').css('background','url("/img/search_links.gif") no-repeat -177px 0px');
    $('a#search_2').css('background','url("/img/search_links.gif") no-repeat 0px -27px');
    $('div.search_ch_produkt').hide();
    $('div.search_ch_firma').show();
  }
  else
  {
    $('a#search_2').css('background','url("/img/search_links.gif") no-repeat 0px 0px');
    $('a#search_1').css('background','url("/img/search_links.gif") no-repeat -177px -27px');
    $('div.search_ch_firma').hide();
    $('div.search_ch_produkt').show();
  }

  $('a#search_2').click(function()
  {
    $('a#search_1').css('background','url("/img/search_links.gif") no-repeat -177px 0px');
    $(this).css('background','url("/img/search_links.gif") no-repeat 0px -27px');
    $('div.search_ch_produkt').hide();
    $('div.search_ch_firma').show();
    wli = 'search_2';
    $.cookie(COOKIE_NAME_SEARCH, wli, { path: '/' });
  });

  $('a#search_1').click(function()
  {
    $('a#search_2').css('background','url("/img/search_links.gif") no-repeat 0px 0px');
    $(this).css('background','url("/img/search_links.gif") no-repeat -177px -27px');
    $('div.search_ch_firma').hide();
    $('div.search_ch_produkt').show();
    wli = 'search_1';
    $.cookie(COOKIE_NAME_SEARCH, wli, { path: '/' });
  });

  if ($('#filter-sidebar').length) {
    initFilterMap();
  }
});

function addFormField_phone() {
  var id = document.getElementById("id").value;
  $("#divTxt").append("<p id='row" + id + "'><input style='margin-bottom:3px;' type='text' name='phone' id='txt" + id + "'><a href='#' onClick='removeFormField_phone(\"#row" + id + "\"); return false;'>&nbsp;<img src='/img/pa/input_sub.gif' style='display:inline' title='Usuń pole' alt='' /></a><p>");

  id = (id - 1) + 2;
  document.getElementById("id").value = id;
}

function removeFormField_phone(id) {
  $(id).remove();
}

function addFormField_fax() {
  var id = document.getElementById("id").value;
  $("#divTxtf").append("<p id='rowf" + id + "'><input style='margin-bottom:3px;' type='text' name='fax' id='txtf" + id + "'><a href='#' onClick='removeFormField_fax(\"#rowf" + id + "\"); return false;'>&nbsp;<img src='/img/pa/input_sub.gif' style='display:inline' title='Usuń pole' alt='' /></a><p>");

  id = (id - 1) + 2;
  document.getElementById("id").value = id;
}

function removeFormField_fax(id) {
  $(id).remove();
}

function addFormField_mail() {
  var id = document.getElementById("id").value;
  $("#divTxtm").append("<p id='rowm" + id + "'><input style='margin-bottom:3px;' type='text' name='email' id='txtm" + id + "'><a href='#' onClick='removeFormField_mail(\"#rowm" + id + "\"); return false;'>&nbsp;<img src='/img/pa/input_sub.gif' style='display:inline' title='Usuń pole' alt='' /></a><p>");

  id = (id - 1) + 2;
  document.getElementById("id").value = id;
}

function removeFormField_mail(id) {
  $(id).remove();
}

function addFormField_www() {
  var id = document.getElementById("id").value;
  $("#divTxtw").append("<p id='roww" + id + "'><input style='margin-bottom:3px;' type='text' name='www' id='txtw" + id + "'><a href='#' onClick='removeFormField_www(\"#roww" + id + "\"); return false;'>&nbsp;<img src='/img/pa/input_sub.gif' style='display:inline' title='Usuń pole' alt='' /></a><p>");

  id = (id - 1) + 2;
  document.getElementById("id").value = id;
}

function removeFormField_www(id) {
  $(id).remove();
}

function hs_cat(pole) {
  $("div#"+pole).toggle("fast");
  var aux;
  aux = $("img#i"+pole).attr('src');
  if (aux == '/img/pa/small_plus.gif')
  {
    $("img#i"+pole).attr('src','/img/pa/small_minus.gif');
  }
  else
  {
    $("img#i"+pole).attr('src','/img/pa/small_plus.gif');
  }
}

