var markerIcon    = '/img/dott.png';
var ajaxloader    = '<span class="AjaxLoader"><p><img src="/img/ajax-loader.gif" alt=""><br />Lūdzu, uzgaidiet!</p></span>';
var openeda       = [];
var LayoutTab     = 'primary';

var multiple      = false;
var Filter;
var filterData    = {};
var filterCount   = 0;
var filterBlock   = "";
var filterBlockSize = [];

$(document).ready(function()
{
	setFilterFromUrlHash();
	initUkResults();
	initUkFilters();
});

/**
* Uk Loader Object
*/
ukLoader = function ()
{
	var target  = 'div.Content.UK-Content';
	this.start = function(){
		$(target).append(ajaxloader);
		$(target).addClass('AjaxLoader');
	};

	this.close = function(){
		$(target).removeClass('AjaxLoader');
		$(target+' span.AjaxLoader').remove();
	};
};

/**
* JS karte rezultātos
*
*/
function getJsSmallMmap(parent)
{
	var targetId  = parent.children('div.MoreInfo').children('.miniMap').children('div').attr('id');
	var getCoord  = $('#'+targetId).attr('class');
	if(getCoord != '' && getCoord != undefined){
		var coord     = getCoord.split(',');
		if($('#'+targetId).html() == '')
		{
			var jsmap;
			jsmap = new JanaSetaMap(targetId);
			jsmap.Load(coord[2], coord[0], coord[1]);
			jsmap.navigation_controls.HidePanningButton();
			jsmap.navigation_controls.HideZoomRegion();jsmap.zoom_tool.Hide();jsmap.ruler.Hide();
			jsmap.image_layer.Add(markerIcon, coord[0], coord[1], 10, 10);
			$('#'+targetId+' img[src="http://maps.kartes.lv/kijs/images/logo.jpg"]').hide();
			$('#'+targetId+' img[src="http://maps.kartes.lv/kijs//images/scale.gif"]').parent().hide();

		}
	}
}

function initUkResultRows()
{
	$('.ItemsList .FullInfo .Features a').tipsy({gravity: 'n'});

	$('div.ItemsList div.ResultItem div.MainInfo:not(.PP) a:not(.CloseItem)').click(function(event){
		event.stopPropagation();
		if( !$(this).parent().hasClass('mail') && !$(this).parent().hasClass('www')){
			var open = $(this).parentsUntil('div.ResultItem').parent();
			if( ! open.hasClass('OpenItem') ){
				$('div.clickable', open).trigger('click');
				return false;
			}
		}
	});

	$("div.ItemsList div.ResultItem div.clickable").click(function()
	{
		var openeda = $(this).parentsUntil('div.ResultItem').parent();
		if( !openeda.hasClass('OpenItem') ){
			openeda.addClass('OpenItem');
			openeda.children().children('div.Snippet').hide();
			openeda.children('div.ItemBottom').show();
			openeda.children('div.FullInfo').slideDown();
			openeda.children('div.RightInfo').show();

			$('a.InfoPageLink', openeda).show();
			$('a.MorePhones', openeda).show();
			//$('div.clickable', openeda).removeClass('clickable');

			getJsSmallMmap( openeda.children('div.RightInfo') );
			var getClickedId = $(this).parent('div');
				getClickedId = $(getClickedId[0]).attr('class').replace("itm-", "");
			$.post(linkAction+'se/', {'id':getClickedId, 'key':SearchKey});

		}else{
			$('div.ItemBottom', openeda ).trigger('click');
		}
	});

	$("div.ResultItem div.ItemBottom").click(function()
	{
		var openeda = $(this).parent();
		if( openeda.hasClass('OpenItem') ){
			openeda.removeClass('OpenItem');
			openeda.children('div.ItemBottom').hide();
			openeda.children().children('div.Snippet').show();
			openeda.children('div.RightInfo').hide();
			openeda.children('div.FullInfo').slideUp();

			//$('div.MainInfo', openeda).addClass('clickable');
			$('a.MorePhones', openeda).hide();
			$('a.InfoPageLink', openeda).hide();
		}
	});
}

/**
* Main Result Block TABS
*
*/
function infoSelectTab(name)
{
	$('.FullInfo .Header a').removeClass('Selected');
	$('.FullInfo ul.Contenth').hide();
	$('.FullInfo ul.'+$(name).attr('class')+'-Content').show();
	$(name).addClass('Selected');
}

/**
* Googles karte rezultātos
*
*/
function getGoogleImg(parent)
{
	var coord = parent.children('div.MoreInfo').children('.miniMap').children('img').attr('class');
	if(parent.children('div.MoreInfo').children('.miniMap').children('img').attr('src') === '#')
	{
		var imglink = "http://maps.google.com/maps/api/staticmap?center="+coord+
					"&zoom=14&size=198x198&maptype=roadmap&markers=icon:http://www.1188.lv/"+markerIcon+"|color:blue|"+coord+"&sensor=true";
		parent.children('div.MoreInfo').children('.miniMap').children('img').attr('src', imglink);
	}
}

/**
* *** FILTERS ***************************************************************************************
*/

/**
* Result Lefts side Filters
*/
UkFilter = function()
{
	// Add to Data array
	this.add = function(type, string, multiple)
	{
		// subfilter
		$('div.Inside[title="'+ string +'"]').show();
		
		if(type != SearchType)
		{
			if(filterData[type] == undefined){ filterData[type] = []; }
			// multiple search
			if(multiple == false){
				$('.FilterContent.'+type+' ul li input').attr('checked', false);
				filterData[type] = [];
			}
			if(jQuery.inArray(string, filterData[type])){
				filterData[type][filterData[type].length] = string;
				this.select(type, string);
				filterCount++;
			}
			filterBlock = type;
		}
	};

	// Remove from array
	this.remove = function(type, string, multiple)
	{
		if(multiple == false){
			this.add(type, string, multiple);
		}else{
			if(string == '' || string == undefined){
				if(filterData[type] != undefined){
					$('.FilterContent.'+type+' ul li input').attr('checked', false);
					delete filterData[type];
				}
			}else{
				if(filterData[type] != undefined){
					$.each(filterData[type], function(index, value) {
						if(string == value){
							filterData[type].splice(index, 1); filterCount--;
						}
					});
				}
			}
			this.deselect(type, string);
		}
	};

	// return Data array
	this.data = function(type)
	{
		if(type != undefined){
			if(filterData[type] != undefined){
				return filterData[type];
			}
		}else{
			return filterData;
		}
	};

	// Select elemtnt
	this.select = function(type, value)
	{
		$('.FilterContent.'+type+' ul li input[value=\''+value+'\']').attr('checked', true);
		$('.FilterContent.'+type+' ul li input[value=\''+value+'\']').addClass('Checked');
	};

	// Remove select elemtnt
	this.deselect = function(type, value)
	{
		$('.FilterContent.'+type+' ul li input[value=\''+value+'\']').attr('checked', false);
		$('.FilterContent.'+type+' ul li input[value=\''+value+'\']').removeClass('Checked');
	};

	// Iezīmējam tos kam ir atbilstoši rezultāti
	this.highlight = function(type, data)
	{
		if(data != null && data != undefined && SearchType != 'branche' && SearchType != 'name')
		{
			$('.FilterContent.'+type+' ul li a').addClass('disable');
			$.each(data, function(index, value)
			{
				$('.FilterContent.'+type+' ul li a[title=\''+value['title']+'\']').removeClass('disable');
				$('.FilterContent.'+type+' ul li a[title=\''+value['title']+'\']').html(value['title']+' ('+value['count']+')<span></span>');
			});
		}
	};
};

/**
* Inicializējam UK rezultātus
*
*/
function initUkResults()
{
	//$(function() {
	//  $('.RightSearchRes .InfoBar p a').tipsy({gravity: 'nw'});
	//});

	/**
	* Init Row
	*/
	initUkResultRows();

	/**
	*  Pageing
	*
	*/
	$("div.Pagination a").click(function()
	{
		if( $(this).hasClass('selected')) { return; }
		var	reloadData = new QueryResult();
			reloadData.SetUrl(this.href);
			reloadData.SetConfig({scroll: true, filter: LayoutTab=='primary' || LayoutTab == 'name'?false:true});
			reloadData.reload();
			return false;
	});

	/**
	*  Layout Tabs
	*
	*/
	$(".RightSearchRes ul.Tabs li a").click(function()
	{
		if(SearchCount > 0){
			if($(this).parent('li').hasClass('filter') && filterCount == 0) { return false; }
			if($(this).parent('li').hasClass('Selected')) { return false; }

			$('.RightSearchRes ul.Tabs li').removeClass('Selected');

			LayoutTab = $(this).parent('li').attr('class');

			$(this).parent('li').addClass('Selected');
			$(".RightSearchRes ul.Tabs ."+LayoutTab+" a").html($(this).html());
			var reloadData = new QueryResult();
			reloadData.SetUrl(this.href);
			if(LayoutTab == 'filter'){ // ja ejam atpakaļ uz filtra tabu
				reloadData.SetConfig({filter: true});
			}
			reloadData.reload();
		}
		return false;
	});

	// rādam filtrus izvēlētos
	if(LayoutTab == 'filter'){
		$('.InfoBar .Filters').show();
	}else{
		$('.InfoBar .Filters').hide();
	}

	if(SearchCount > 0){
		if(filterCount == 0){
			var _LayTabs = $('.RightSearchRes UL.Tabs LI');
			var _LayTabs_a = $('.RightSearchRes UL.Tabs LI').children('a');
			$(_LayTabs_a[_LayTabs_a.length-1]).addClass('Disabled').attr('href','javascript:void(0)');
		}
	}else{
		var _LayTabs = $('.RightSearchRes UL.Tabs LI');
		var _LayTabs_a = $('.RightSearchRes UL.Tabs LI').children('a').addClass('Disabled').attr('href','javascript:void(0)');
	}
}

/**
* Inicializējam Uk Meklēšanas filtrus
*
*/
function initUkFilters()
{
  var fType       = "";
  var fString     = "";
      Filter      = new UkFilter();

  if(SearchBranche != '') { Filter.add('branche', SearchBranche); }

  $('DIV.Filter .FilterContent ul li a.self, DIV.Filter .FilterContent ul li input, div.Filter div.FilterContent div.Inside a').click(function()
  {
    var getFilterElement;

	if( $(this).parent().parent().parent().hasClass('Inside') ){
		multiple = false;
		getFilterElement = this;
		fString = $(this).attr('title');
		
	}else if(this.value !== undefined){
      multiple = true;
      fString = this.value;
      getFilterElement = $(this).next('a');
	  
    }else{
      multiple = false;
      fString = $(this).attr('title');
      getFilterElement = this;
    }


    if($(getFilterElement).parent('li').parent('ul').parent('div').hasClass('address')) { fType = 'address'; }
    if($(getFilterElement).parent('li').parent('ul').parent('div').hasClass('addressRegion')) { fType = 'addressRegion'; }
    if($(getFilterElement).parent('li').parent('ul').parent('div').hasClass('addressNovads')) { fType = 'addressNovads'; }
    if($(getFilterElement).parent('li').parent('ul').parent('div').hasClass('branche')) { fType = 'branche'; }
    if(fType == "") { return true; } // Izpildam pieprasījumu bez AJAX

    if($(getFilterElement).prev('input').hasClass('Checked'))
    {
      Filter.remove(fType, fString, multiple);
    }
    else
    {
      Filter.add(fType, fString, multiple);;
    }

    var reloadData = new QueryResult();
        reloadData.SetUrl(SearchType == 'branche'?window.location.pathname+window.location.hash : linkAction+getQueryString($(getFilterElement).attr('href')));
        reloadData.SetPost(Filter.data());
        reloadData.SetConfig({filter: true});
        reloadData.reload();

    if(multiple == false) { return false; }
  });
}

/**
* Reload Uk Result Data
*/
function QueryResult()
{
  // Set default data
  var getUrl  = "";
  var getGet  = "";
  var getPost = {};
  var content = $('div#UkResultContent');
  var config  = {scroll: false, filter : false};
  var loader  = new ukLoader();

  // Set Params
  this.SetUrl   = function(url) { getUrl  = url; };
  this.SetGet   = function(get) { getGet  = get; };
  this.SetPost  = function(post){ getPost = post; };
  this.SetConfig= function(set) { config  = set; };

  this._POST    = function(){
    var _post_return = getPost;
        if(config.filter != undefined && config.filter){
          _post_return = filterData;
        }
    return _post_return;
  };

  this._GET    = function(){
    return getUrl + getGet;
  };

  // Reload DATA
  this.reload   = function(){
    loader.start();
    $.post(this._GET(), this._POST(),
        function(json){
          if(json.HTML){
             SearchKey = json.KEY;
             content.html(json.HTML);
            if(config.scroll != undefined && config.scroll){
              $('html, body').animate({scrollTop: $('HTML').offset().top}, 500);
            }
            loader.close();
            if(json.FILTER) { LayoutTab = 'filter'; }
            if(filterBlock != ''){
              if(filterBlock == 'branche') { Filter.highlight('address', json.GROUP.CITY); }
              if(filterBlock == 'addressRegion') { Filter.highlight('addressRegion', json.GROUP.REGION); }
              if(filterBlock == 'address') { Filter.highlight('branche', json.GROUP.BRANCH); }
            }else{
              Filter.highlight('address', json.GROUP.CITY);
              Filter.highlight('addressRegion', json.GROUP.REGION);
              Filter.highlight('branche', json.GROUP.BRANCH);
            }
            setUrlHash();
            initUkResults();
            return false;
          }
          return true;
        }, 'json');
  };
}

function removeAllFilters()
{
  filterData = {};
  $('.FilterContent ul li input ').removeClass('Checked');
  $('.FilterContent ul li input ').attr('checked', false);
  var reloadData = new QueryResult();
      reloadData.SetUrl(window.location.href);
      reloadData.SetConfig({filter: false, scroll: false});
      reloadData.reload();
}

/**
* Filtra bloka palielināšana
*/
function fOpenMore(_type)
{
  if(_type != undefined){
    if(filterBlockSize[_type] == undefined){
      filterBlockSize[_type] = 0;
    }
    filterBlockSize[_type]++;
    getFilterBlockRow = $('div.LeftSide .FilterContent.'+_type+' ul');
    if(filterBlockSize[_type] != undefined){
      $(getFilterBlockRow[filterBlockSize[_type]]).show();
    }
    $('div.LeftSide .FilterContent.'+_type+' a.Less:hidden').show();

    if(getFilterBlockRow.length == filterBlockSize[_type]+1){
      $('div.LeftSide .FilterContent.'+_type+' a.More:visible').hide();
    }
  }
}

/**
* Filtra bloka samazināšana
*/
function fOpenLess(_type)
{
  if(_type != undefined)
  {
    if(filterBlockSize[_type] > 0)
    {
      getFilterBlockRow = $('div.LeftSide .FilterContent.'+_type+' ul');
      if(filterBlockSize[_type] != undefined){
        $(getFilterBlockRow[filterBlockSize[_type]]).hide();
      }
      filterBlockSize[_type]--;
      if(filterBlockSize[_type] == 0){
        $('div.LeftSide .FilterContent.'+_type+' a.Less:visible').hide();
      }
      $('div.LeftSide .FilterContent.'+_type+' a.More:hidden').show();
    }
  }
}

/**
* Noņemam augšējos filtrus
*/
function removeTopBaloonFilters(_this_obj, title)
{
  $(_this_obj).parent('a').remove();
  Filter.remove('address', title, true);
  Filter.remove('addressRegion', title, true);
  Filter.remove('addressNovads', title, true);
  Filter.remove('branche', title, true);

  var reloadData = new QueryResult();
      reloadData.SetUrl(window.location.href);
      reloadData.SetPost(Filter.data());
      reloadData.SetConfig({filter: true});
      reloadData.reload();
}

/**
* Nomainam Url Hash uz atbilstošu atkarībā no filtriem
*
*/
function setUrlHash()
{
  var _hash = "";
  var _urlType = "";
  var fCount=0; for (var oi in filterData) fCount++;
  var ii=1; $.each(filterData, function(key, type)
  {
    if((SearchType != key))
    {
      _hash += (ii!=1?'&':'')+key+":";
      var i=1; $.each(type, function(v, value)
      {
        if(value != ''){
          _hash += value;
          if(type.length != i) { _hash += ";"; };
          i++;
        }

      });
      ii++;
    }
  });
  if(filterCount > 0 || window.location.hash != ''){ window.location.hash = _hash; }
}

/**
* Filter from Url hash
*    - Ja ir padots Url hash bet nav filtra, tad ielādējam filtru no
* Url hasha
*
*/
function setFilterFromUrlHash()
{
  var _GetTypes = [];
  var _hash     = window.location.hash;
  var  fCount   = 0; for (var oi in filterData) fCount++;

  // Ja ir padots Url hash bet nav filtra
  if(_hash != "" && fCount == 0)
  {
    Filter = new UkFilter();

    var _splitHash = _hash.replace("#", "").split("&");
    $.each(_splitHash, function(i1,_getSplitType)
    {
      var _splitParams = _getSplitType.split(':');
      _GetTypes[_splitParams[0]] = [];

      if(_splitParams[1] != undefined){
        var i=0; $.each(_splitParams[1].split(';'), function(i2, params)
        {
          if(params != ''){
            _GetTypes[_splitParams[0]][i] = params;
            Filter.add(_splitParams[0], _GetTypes[_splitParams[0]][i]);
          }
          i++;
        });
      }
    });

    var reloadData = new QueryResult();
        if(SearchType == 'branche'){
          reloadData.SetUrl(window.location);
        }else{
          reloadData.SetUrl(linkAction + getQueryString(parent.location));
        }
        reloadData.SetPost(Filter.data());
        reloadData.SetConfig({filter: true});
        reloadData.reload();
  }
}

/**
* Savācam _GET parametrus no dotā linka
*
*/
function getQueryString(params)
{
  var strReturn   = "";
  var strHref     = params.toString();

  if(strHref.indexOf("#") > -1){
    var _cutHash = strHref.split('#');
    strHref = _cutHash[0];
  }

  if (strHref.indexOf("?") > -1){
    return strHref.substr(strHref.indexOf("?")).toLowerCase();
  }else{ return ''; }
}

