// used only in search field (can be replaced with cleanField() later)
function valome(what){ if(!what._haschanged){ what.value='' }; what._haschanged=true; }

function changeParentWindowLocation(url) {
  if (window.opener) {
    window.opener.location.href = url;
    window.close();
  } else window.location.href = url;
}

function textCounter(inputFieldID, msgFieldID, limit) {
  var length = document.getElementById(inputFieldID).value.length;
  var value = document.getElementById(inputFieldID).value;
  if (length > limit) {
    document.getElementById(inputFieldID).value = value.substr(0, limit);
    document.getElementById(msgFieldID).innerHTML = limit;
  } else document.getElementById(msgFieldID).innerHTML = length;
}

// search by categories
function updateSubcategoryDD(srcID, dstID) {
  var srcOptions = document.getElementById(srcID).options;
  var oldDstOptions = document.getElementById(dstID).options;
  
  var ids = '';
  for(i = 0; i < srcOptions.length; i++) {
    if (srcOptions[i].selected) ids += srcOptions[i].value + '|';
  }
  
  /*var oldIds = '';
  for(i = 0; i < oldDstOptions.length; i++) {
    if (oldDstOptions[i].selected) oldIds += oldDstOptions[i].value + '|';
  }*/
  
  document.getElementById(dstID).innerHTML = '<option>&nbsp;</option>';
  document.getElementById(dstID).style.display = 'none';
  
  if (ids) {
    ids = ids.substr(0, ids.length - 1);
    //if (oldIds) oldIds = oldIds.substr(0, oldIds.length - 1);
    $.ajax({
      url: 'ajax/get_subcategories.php?categories=' + ids /*+ '&selected=' + oldIds*/,
      success: function(data) {
        if (!data) return;
        document.getElementById(dstID).innerHTML = data;
        document.getElementById(dstID).style.display = '';
      }
    });
  }
         
  //updateSearchCategoriesDD();
}

function updateSearchCategoriesDD() {
  var ddIDs = new Array('category_dd', 'subcategory_dd', 'subsubcategory_dd', 'subsubsubcategory_dd');
  var ids = '';
  for(i = 0; i < ddIDs.length; i++) {
    var options = document.getElementById(ddIDs[i]).options;
    for(j = 0; j < options.length; j++) {
      if (options[j].selected) ids += options[j].value + '|';
    }
  }
  ids += $('input[name="categories"]').val();
  
  $.ajax({
      url: 'ajax/get_filtered_subcategories.php?categories=' + ids,
      success: function(data) {
        if (!data) return;
        $('input[name="categories"]').val(data);
        $.ajax({
          url: 'ajax/get_search_tree.php?categories=' + data,
          success: function(data2) {
            if (!data2) return;
            $('#search_categories').html(data2);
          }
        });
      }
    });
}

function removeSearchCategory(categoryID) {
  document.getElementById('span_' + categoryID).style.display='none';
  var data = $('input[name="categories"]').val();
  var ids = data.split('|');
  
  var newData = '';
  for(i = 0; i < ids.length; i++) {
    if (ids[i] == categoryID) continue;
    newData += ids[i] + '|';
  }
  
  if (newData) newData = newData.substr(0, newData.length - 1);
  $('input[name="categories"]').val(newData);
}
// search by categories [end]

// AJAX calls

// content loading
function loadContent(category) {
  if (category != undefined) {
    //cleanFilters('');
    $.ajax({
      url: '/ajax/get_content.php?category_id=' + category,
      success: function(data) {
        $('#content_div').html(data);
      }
    });
  }
}

// nt paieska
function getNTtipas(action) {
  $.ajax({
    url: 'ajax/get_nt_tipas.php?action=' + action,
    success: function(data) {
      $('#nt_tipas_div').html(data);
    }
  });
}

function generateCode() {
  $.ajax({
    url: '../ajax/get_captcha_code.php',
    success: function(data) {
      $('#code').val(data);
    }
  });
}

function sendAdlink(catID, adID) {
  if (!$('#code').val()) {
    alert('Sugeneruokite patvirtinimo kodą.');
    return;
  }
  
  if ($('#code').val() != $('#code2').val()) {
    alert('Įvestas neteisingas patvirtinimo kodas.');
    return;
  }
  
  var from = $('#from').val();
  var to = $('#to').val();
  var name = $('#name').val();
  var comment = $('#comment').val();
  
  $.ajax({
    url: '../ajax/send_adlink.php?from=' + from + '&to=' + to + '&name=' + name + '&comment=' + comment + '&category_id=' + catID + '&id=' + adID,
    success: function(data) {
      if (data == 'ok') window.close();
      else alert(data);
    }
  });
}

function sendBadAdlink(catID, adID) {
  if (!$('#code').val()) {
    alert('Sugeneruokite patvirtinimo kodą.');
    return;
  }
  
  if ($('#code').val() != $('#code2').val()) {
    alert('Įvestas neteisingas patvirtinimo kodas.');
    return;
  }
  
  var reason = $('input:radio[name=reason]:checked').val();
  var comment = $('#comment').val();
  
  $.ajax({
    url: '../ajax/send_bad_adlink.php?reason=' + reason + '&comment=' + comment + '&category_id=' + catID + '&id=' + adID,
    success: function(data) {
      if (data == 'ok') window.close();
      else alert(data);
    }
  });
}

function sendErrorReport() {
  if (!$('#code').val()) {
    alert('Sugeneruokite patvirtinimo kodą.');
    return;
  }
  
  if ($('#code').val() != $('#code2').val()) {
    alert('Įvestas neteisingas patvirtinimo kodas.');
    return;
  }
  
  var comment = $('#comment').val();
  
  $.ajax({
    url: '../ajax/send_error_report.php?comment=' + comment,
    success: function(data) {
      if (data == 'ok') window.close();
      else alert(data);
    }
  });
}

function sendPassword() {
  var email = $('#email').val();
  if (!email || email == 'Įveskite savo el. pašto adresą') {
    alert('Įveskite el. pašto adresą.');
    return;
  }
  
  $.ajax({
    url: '../ajax/send_password.php?email=' + email,
    success: function(data) {
      if (data == 'ok') window.close();
      else alert(data);
    }
  });
}

function setCity(cityCode) {
  $.ajax({
    url: '../ajax/set_city.php?city=' + cityCode,
    success: function(data) {
      if (data == 'ok') window.location.reload();
    }
  });
}

function setPageItems(count) {
  $.ajax({
    url: '../ajax/set_page_items.php?count=' + count,
    success: function(data) {
      if (data == 'ok') window.location.reload();
    }
  });
}

function setState(state) {
  $.ajax({
    url: '../ajax/set_state.php?state=' + state,
    success: function(data) {
      if (data == 'ok') window.location.reload();
    }
  });
}

function setOrder(order) {
  $.ajax({
    url: '../ajax/set_order.php?order=' + order,
    success: function(data) {
      if (data == 'ok') window.location.reload();
    }
  });
}

function cleanFilters(redirectURL) {
  document.getElementById('city_filter').options[0].selected = true;
  document.getElementById('order_filter').options[0].selected = true;
  document.getElementById('state_filter').options[0].selected = true;
  
  $.ajax({
    url: '../ajax/clean_filters.php',
    success: function(data) {
      if (data == 'ok' && redirectURL) window.location.href = redirectURL;
    }
  });
}

// popUps
function popUp(url, popupWidth, popupHeight) {
  window.open(url, '', 'left=' + ((screen.width - popupWidth) / 2) + ',top=' + ((screen.height - popupHeight) / 2) + ',width=' + popupWidth + ',height=' + popupHeight + ',scrollbars=1,resizable=0,location=0,toolbar=0,menubar=0,status=0');
}

function popUpForFriend(catID, adID) {
  var popupWidth = 582;
  var popupHeight = 431;
  window.open('../popups/draugui.php?category_id=' + catID + '&id=' + adID , '', 'left=' + ((screen.width - popupWidth) / 2) + ',top=' + ((screen.height - popupHeight) / 2) + ',width=' + popupWidth + ',height=' + popupHeight + ',scrollbars=0,resizable=0,location=0,toolbar=0,menubar=0,status=0');
}

function popUpForBadAd(catID, adID) {
  var popupWidth = 582;
  var popupHeight = 431;
  window.open('../popups/netinkamas_skelbimas.php?category_id=' + catID + '&id=' + adID , '', 'left=' + ((screen.width - popupWidth) / 2) + ',top=' + ((screen.height - popupHeight) / 2) + ',width=' + popupWidth + ',height=' + popupHeight + ',scrollbars=0,resizable=0,location=0,toolbar=0,menubar=0,status=0');
}

function popUpForErrorReporting() {
  var popupWidth = 582;
  var popupHeight = 431;
  window.open('../popups/klaida.php', '', 'left=' + ((screen.width - popupWidth) / 2) + ',top=' + ((screen.height - popupHeight) / 2) + ',width=' + popupWidth + ',height=' + popupHeight + ',scrollbars=0,resizable=0,location=0,toolbar=0,menubar=0,status=0');
}

function popUpForPassword() {
  var popupWidth = 582;
  var popupHeight = 281;
  window.open('../popups/slaptazodis.php', '', 'left=' + ((screen.width - popupWidth) / 2) + ',top=' + ((screen.height - popupHeight) / 2) + ',width=' + popupWidth + ',height=' + popupHeight + ',scrollbars=0,resizable=0,location=0,toolbar=0,menubar=0,status=0');
}

function saveAd(adID, catID, status) {
  $.ajax({
      url: '../ajax/save_ad.php?ad_id=' + adID + '&category_id=' + catID + '&status=' + (status ? 1 :0),
      success: function(data) {
        dataArr = data.split('#');
        var id = catID + '-' + adID;
        
        if (dataArr.length == 1) {
          alert(dataArr[0]);
          $('#chbx_' + catID + '-' + adID).attr('checked', false);
          return;
        }
        
        if (window.opener) {
          window.opener.document.getElementById('saved_ads_count').innerHTML = '(' + data[0] + ')';
          window.opener.document.getElementById('span_' + id).innerHTML = dataArr[1];
          var spanWidth = window.opener.document.getElementById('span1_' + id).style.width;
          window.opener.document.getElementById('span1_' + id).style.width = (spanWidth == '367px' ? '377px' : '367px');
          window.opener.document.getElementById('chbx_' + id).checked = !window.opener.document.getElementById('chbx_' + id).checked;
          window.close();
        } else {
          $('#saved_ads_count').html('(' + data[0] + ')');
          $('#span_' + id).html(dataArr[1]);
          var spanWidth = $('#span1_' + id).css('width');
          $('#span1_' + id).css('width', spanWidth == '365px' ? '377px' : '365px');
        }
      }
    });
}

// image functions
function changeImage(objID, src, href) {
  if (document.getElementById(objID)) document.getElementById(objID).src = src;
  //if (document.getElementById(objID + '_href')) document.getElementById(objID + '_href').href = href; 
}

function rotateImages(objID, imageDirPath, imageArr) {
  var nextImgIndex = 0;
  var currentImgSrc = decodeURIComponent(document.getElementById(objID).src);
  
  for (i = 0; i < imageArr.length; i++) {
    if (imageDirPath + imageArr[i] == currentImgSrc) {
      nextImgIndex = i + 1;
      if (nextImgIndex == imageArr.length) nextImgIndex = 0;
      break;
    }
  }
  
  if (document.getElementById(objID)) document.getElementById(objID).src = imageDirPath + imageArr[nextImgIndex];
}

function rotateSmallImages(imageDirPath, bigImageDirPath, imageArr, marginArr, direction) {
  var nextImgIndex = 0;
  var firstImgSrc = decodeURIComponent(document.getElementById('img_0').src);
  var arrSize = imageArr.length;
  
  for (i = 0; i < imageArr.length; i++) {
    if (imageDirPath + imageArr[i] == firstImgSrc) {
      nextImgIndex = (direction < 0) ? (i - 1) : (i + 1);
      if (nextImgIndex == arrSize && direction > 0) nextImgIndex = 0;
      if (nextImgIndex == -1 && direction < 0) nextImgIndex = arrSize - 1;
      break;
    }
  }
  
  for (i = 0; i < 4; i++) {
    if (nextImgIndex == arrSize) nextImgIndex = 0;
    if (document.getElementById('img_' + i)) {
      document.getElementById('img_' + i).src = imageDirPath + imageArr[nextImgIndex];
      document.getElementById('img_' + i).style.marginTop = marginArr[nextImgIndex] + 'px';
      document.getElementById('img_' + i).setAttribute("onclick", "changeImage('big_img', '" +  bigImageDirPath + imageArr[nextImgIndex] + "');");
    }
    nextImgIndex++;
  }
}

function rotateSmallImagesStep4(arrowType) {
  if ($('#images').is(':visible') && arrowType == 'r') {
    $('#images').hide();
    $('#extra_images').show();
  } else if (arrowType == 'l') {
    $('#extra_images').hide();
    $('#images').show();
  }
}

// category tree (accordion menu)
function initMenu() {
  $('#menu ul').hide();
  $('#menu li a').click(
    function() {
      var checkElement = $(this).next();
      if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
        checkElement.slideDown('normal');
        checkElement.parent().siblings().children('a').removeClass('active');
        checkElement.parent().siblings().children('ul').hide();
        $(this).addClass('active');
        return;
      } else {
        checkElement.hide();
        $(this).removeClass('active');
      }
    }
  );
}

function cleanField(obj) { 
 if (obj.value.substr(0, 5) == 'Pvz.:' || obj.value.substr(0, 5) == '-----') obj.value = '';
}


// ----- initialization ----- //
$(document).ready(function () {
  $(document).pngFix();
  
  initMenu();
  
  // code generation button action
  $('#generate').click(function() {
    $.ajax({
      url: 'ajax/get_captcha_code.php',
      success: function(data) {
        $('#code').val(data);
      }
    });
  });
   
  $('#ad_form').submit(function() {
    if (window.location.href.indexOf('a=edit') == -1 && !$('#code').val()) {
      alert('Sugeneruokite patvirtinimo kodą.');
      return false;
    }
    
    if (!$("#agree_chbx:checked").length) {
      alert('Privalote sutikti su taisyklėmis.');
      return false;
    }
  });
  
  $('#code').select(function() {
    var tempText = $('#code').val();
    $('#code').val('');
    $('#code').val(tempText);
    return false;
  });
   
  // google map
  $('#get_map').click(function() {
    var city = $('#adr_miestas').val();
    if (!city) alert ('Pasirinkite miestą.');
    else if ((!$('#adr_gatve').val() || $('#adr_gatve').val().substr(0, 5) == 'Pvz.:') && city != 104) alert('Įveskite gatvės pavadinimą.');
    else {
    $.ajax({
      url: 'ajax/get_gmap.php?params_only=true&params=' + $('#adr_salis').val() + '|' + $('#adr_miestas').val() + '|' + $('#adr_gatve').val() + ($('#adr_namas').val() ? '|' + $('#adr_namas').val() : ''),
      success: function(data) {
        var dataArr = data.split('##');
        initializeMap(city == 104 ? 5 : 15);
        codeAddress(dataArr[0], dataArr[1]);
      }
    });
    }
   });
   
   // city dropdown
   $('#adr_miestas').change(function() {
      if ($('#adr_miestas').val() == 104) {
        $('#street_span').hide();
        $('#bnum_span').hide();
      } else {
        $('#street_span').show();
        $('#bnum_span').show();
      }
   });
   
   // auto models
   $('#marke').change(function() {
    $.ajax({
      url: 'ajax/get_auto_models.php?make=' + $('#marke').val(),
      success: function(data) {
        $('#modelis_div').html(data);
      }
    });
   });
   
   // content loading
   /*SWFAddress.onChange = function() {//SWFAddress.getValue()
     var category = SWFAddress.getParameter('category_id')
	   if (category != undefined) {
	      $.ajax({
          url: 'ajax/get_content.php?category_id=' + category,
          success: function(data) {
            $('#content_div').html(data);
          }
        });
     }
	 }*/
   
});
