var initialization = true;
//var defaultSearchValues = settings.defaultSearchValues;

$(function() {
    $($("input#location_name")).autocomplete(settings.baseUrl + '/ajax/locations-autocomplete', {
        formatItem: function(item) {
            return item.text;
        },
        formatResult: function(item) {
            return item.place + ', ' + item.country_name;
        },
        parse: function(data) {
           var tmp = null;
           eval('tmp=' + data);
           var result = [];
           for (var i in tmp) {
               result[result.length] = {
                        "data" : tmp[i],
                        "value": tmp[i].id,
                        "result": this.formatResult(tmp[i])
                    }
               ;
           }
           return result;
        },
        max: 230,
        width: '400px'
    }).result(function (event, item) {
        $('#selected_geoz_id').val(item.id);
        currentLocation = item;
        this.location_selected = item.place + ', ' + item.country_name;
    });
    /**
     * Add action to [Change City] button on search form
     */
    $('#button_change_city').click(function(){

        location_value = $("input#location_name").val();
        location_selected = $("input#location_name")[0].location_selected;

        $('#location_name').addClass('disabled');
        $('#location_name').attr("disabled", true);
        $('#button_change_city').addClass('active');
				$('#button_change_city').blur();
        $.ajax({
					type: "GET",
					data: 'id=' + $('#selected_geoz_id').val() + '&lv=' + escape(location_value) + '&ls=' + escape(location_selected),
					url: settings.baseUrl + '/ajax/location-change',
					dataType : "script",
					success: function (data, textStatus) {
						$('#button_change_city').removeClass('active');
						$('#location_name').removeAttr('disabled');
						$('#location_name').removeClass('disabled');
					}
        });
    })
  /*Login form*/
  $('#header_login').hide();
  $('#header_login_lnk').click(function(){
    $(this).hide();
    $('#header_login').slideDown();
  });

  $('.search-select a').click(function(){
    var clicked = this;
    $('.search-select a').each(function(){
      if (this != clicked) {
        $(this).removeClass('active');
      }
    });
    $(this).addClass('active');
    $(this).blur();
    //get type
    var type = 1;
    var current_query = $('#search_key').val();
    //in_default_values
    if ($(this).parent('li').hasClass('first')) {
      type = 1;
      if (!initialization && in_default_values(current_query)) {
        $('#search_key').val(settings.defaultSearchValues.location);
      }
    } else if ($(this).parent('li').hasClass('second')) {
      type = 2;
      if (!initialization && in_default_values(current_query)) {
        $('#search_key').val(settings.defaultSearchValues.name);
      }
    }else if ($(this).parent('li').hasClass('third')) {
      type = 3;
      if (!initialization && in_default_values(current_query)) {
        $('#search_key').val(settings.defaultSearchValues.tag);
      }
    }
    $('#search_type').val(type);
    defaultValues('#search_key');
  });

  var stype = parseInt($('#search_type').val());
  switch(stype) {
    case 2:
      $('.search-select li.second a').click();
      break;
    case 3:
      $('.search-select li.third a').click();
      break
    default:
      $('.search-select li.first a').click();
  }


  //ref 1063 - fix font size
  $('.featured-bars-inner .name a').each(function(){
    fixLink(this);
  });
  var query_value = $('#search_key').val();
  if (!in_default_values(query_value)) {
    settings.defaultSearchValues.tag = query_value;
    settings.defaultSearchValues.name = query_value;
    settings.defaultSearchValues.location = query_value;
  }
  initialization = false;

  //top login form
  $('.top-login-form-item > a').click(function(){
    if ($(this).hasClass('clicked')) {
      var that = this;
      $('.top-login-form', $(this).parent()).slideUp('fast',function(){
        $(that).removeClass('clicked');
      });
    } else {
      $(this).addClass('clicked');
      $('.top-login-form', $(this).parent()).slideDown('fast');
    }
    $(this).blur();
    return false;
  });
});

function fixLink(link) {
  var linkWidth = parseInt($(link)[0].offsetWidth);
  var linkFont = parseInt($(link).css('fontSize'));
  var blockWidth = $(link).parent(0)[0].offsetWidth;
  if ((linkFont > 10) && linkWidth > blockWidth) {
    $(link).css('fontSize', (--linkFont) + 'px')
    fixLink(link);
  }
}

function defaultValues(selector) {
  selector = (typeof(selector) != 'undefined') ? selector : 'form input.form-default-value';
  var fields = $(selector);
  //var forms = fields.parents('form:first');
  fields.each(function() {
    this.defaultValue = this.value;
    $(this).focus(function() {
      if (this.value == this.defaultValue) {
        this.value = '';
        $(this).removeClass('form-default-value');
      }
    });
    $(this).blur(function() {
      if (this.value == '') {
        $(this).addClass('form-default-value');
        this.value = this.defaultValue;
      }
    });
  });

  // Clear all the form elements before submission.
}

function initPager(target, pageClass, count, onpage)
{
  var page = location.hash.match(/page\:(\d+)/);
  page = page == null ? 1 : page[1];
  var numPages = Math.ceil(count/onpage);
  //generate pager html
  var html = '';
  pagerSelectPage(pageClass, page);
  if (numPages <= 1){
    return;
  }
  for(i = 1; i < numPages+1; i++) {
    html += ' <a id="pager-link-' + i + '" href="#page:' + i + '" ' + (i == page ? 'class="active"' : '') +'>[' + i + ']</a> '
  }
  $(target).html(html);
  $(target + ' a').each(function(){
    $(this).click(function(){
      $(target + ' a').each(function(){
        $(this).removeClass('active');
      });
      $('#' + $(this).attr('id')).addClass('active');
      cpage = $(this).attr('id').substr(11);
      pagerSelectPage(pageClass, cpage);
      $(this).blur();
      window.scrollTo(0,245);
    });
  });
}

var pm_curshow = 0;
var pm_pages = 0;

function initPagerMore(pageClass, count, onpage) {
  var page = location.hash.match(/page\:(\d+)/);
  page = page == null ? 1 : page[1];
  pm_pages = Math.ceil(count/onpage);
  //generate pager html
  var html = '';
  pagerSelectPage(pageClass, page);
  if (pm_pages <= 1){
    $('.morego').hide();
    return;
  }
  $('.morego').click(function(){
    pm_curshow++;
    $($('.barItemBlock').get(pm_curshow)).slideDown('slow');
    if (pm_pages == pm_curshow + 1) {
      $(this).hide();
      return;
    }
  });
}

function pagerSelectPage(pageClass, page)
{
  current = 0;
  $('.' + pageClass).each(function(){
    if($(this).css('display') == 'block' && $('.' + pageClass).index(this) +1 != page) {
      $(this).slideUp('slow');
    }
  });
  $($('.' + pageClass).get(page - 1)).slideDown('slow');
}

$(document).ready(function(){
  defaultValues();
});

function initMap()
{
  return new GMap2(
    document.getElementById("googlemap"),
    {
      mapTypes : [G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP]
    }
  );
}

function setMarker(map, latlng, title, message)
{
  marker = new GMarker(latlng, {title: title});
  GEvent.addListener(marker,"click", function() {
    var myHtml = message;
    map.openInfoWindowHtml(latlng, myHtml, {maxWidth: 350});
  });
  return marker;
}

function saveUserTags(button, $barId)
{
  var tags=$("#tags").val();
  if (!tags){
    alert('Tags field are empty!');
    return;
  }
  var firstButtonValue = $(button).val();
  var button = button;
	$(button).hide();
  $.ajax( {
        data: {
          'barid' : $barId,
          'tags': tags
        },
        url: settings.baseUrl + "/ajax/save-tags/",
        type: 'POST',
        success: function(data, textStatus) {
					$(button).show();
					$(button).removeClass("active");
          data = $.trim(data);
          if (data == 'this') {
            //parent.Shadowbox.close();
            parent.location.reload();
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("Error while submiting tags");
					$(button).show();
        }
  });
}

function abuseComment(commentId, link) {
  var linkHTML = $(link).html();
  $(link).html('Sending');
  $.ajax( {
        data: {
          'comment' : commentId
        },
        url: settings.baseUrl + "/ajax/abuse-comment/",
        type: 'POST',
        success: function(data, textStatus) {
          $(link).html(linkHTML);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("Error");
        }
  });
}

/*remove margin right for each 6-th item in just added list (home page)*/
$(document).ready(function(){
	$('.block-just ul.items li:nth-child(4)').each(function (){
		$(this).addClass('nl');
	});
	$('.barview-images li:nth-child(4)').each(function (){
		$(this).addClass('nl');
	});
});

//window.tb_close = tb_close;

$(function() {
  //profile - update password
  $('#update-password').click(function(){
    $(this).blur();
    $('#profile-messages').slideUp('slow');
    var ipass = $('#profile-password').val();
    var ipassv = $('#profile-password-v').val();
    $(this).addClass('loading');
    $.ajax({
      type: "POST",
      dataType : "json",
      timeout: 2000,
      url: settings.baseUrl + '/user/change-password-ajax',
      data: {
        pass  : ipass,
        passv : ipassv
      },
      success: function(response){
        $('#profile-messages').html(jparse_message(response)).slideDown('slow');
        $('#update-password.loading').removeClass('loading');
      },
      error  : function(XMLHttpRequest, textStatus, errorThrown) {
        var error = {
          errors : ['Error: ' + textStatus]
        };
        $('#profile-messages').html(jparse_message(error)).slideDown('slow');
        $('#update-password.loading').removeClass('loading');
      }
    });
  });
});

function jparse_message(data) {
  var lis = '';
  if (data.messages) {
    for(i in data.messages) {
      lis += '<li class="jmessage">' + data.messages[i] + '</li>';
    }
  }
  if (data.errors) {
    for(i in data.errors) {
      lis += '<li class="jerror">' + data.errors[i] + '</li>';
    }
  }

  return lis ? '<ul>' + lis + '</ul>' : false;
}
function in_default_values(str) {
  var vals = settings.defaultSearchValues;
  if (str == vals.location || str == vals.name || str == vals.tag) {
    return true;
  }
  else {
    return false;
  }
}
