var _srch_field_what 	= "";
var _srch_field_where = "";

actionDialogIncorrect = function(){
	$("#dialog").parent().animate({marginLeft: "-50px"},50 ).animate({marginLeft: "50px"},100 ).animate({marginLeft: "0px"},50).animate({marginLeft: "-20px"},50 ).animate({marginLeft: "0px"},50);
}


$.postJSON = function(url, data, callback) {
  $.post(url, data, callback, "json");
}

function escape_quote(string) {
  return string.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&quot;');
}

function submitLogin(_obj)
{
  var isDialog = ($('#dialog').length > 0) ? '#dialog ' : '';
  var params  = {user_phone   : $(isDialog+'input[name=user_phone]').val(),
                 user_password: $(isDialog+'input[name=user_password]').val()};

  $.postJSON(_obj.action, params,
	  function(json)
	  {
	    if(json.STATUS == 'OK')
	    {
	      //Ja nepieciešam redirekts, tad vispirms kā post parametru padod uz kurieni
	      if($('input[name=form-url]').length){
        	window.location = $('input[name=form-url]').val();
        	return;
				}
        // Padod funkciju kuru pēc autorizācijas izpildīt
        if($('input[name=function]').length){
          eval($('input[name=function]').val());
          return;
        }

	      var _send_date    = $(isDialog+'input#additional_params_date').val();
	      var _send_module  = $(isDialog+'input#additional_params_module').val();
	      var _send_msg     = $(isDialog+'input#additional_params_msg').val();

        OpenSendSmsForm(false, _send_msg, _send_date, _send_module);

	    }
      else
      {
	      if($(isDialog+'#login_error').length){
	        var error_msg = "";
	        jQuery.each(json.MSG, function() {
	            error_msg += this + "<br />";
	        });
	        $(isDialog+'#login_error').html(error_msg);
	      }
	    }
	  }
  );
}

function pageLoaderIn(content, text)
{
  var loaderHtml  = "";
      loaderHtml += "<div style=\"width:100%;text-align:center;margin-top:30px;\">";
      loaderHtml += "<img style=\"margin:auto auto\" src=\"/img/ajax-loader.gif\" />";
      if(text) loaderHtml += "<br />" + text;
      loaderHtml += "</div>";
  $(content).html(loaderHtml);
  $(content).css({display:"block"});
};


// menu

//------------------------------------------------

Array.prototype.getUniqueValues = function () {
var hash = new Object();
for (j = 0; j < this.length; j++) {hash[this[j]] = true}
var array = new Array();
for (value in hash){
if( value!=null && value!='null' && value!="undefined" ){
	if( value != ''){
		array.push(value);
	}
}
};
return array;
}

//------------------------------------------------


var openedMenu = new Array();

$(document).ready(function()
{

  if($("#uksearchform").length)
  {
    var ajxUrl = ($("#uksearchform #srchlib").length) ? 'librarys' : 'katalogs' ;

    $('#uksearchform :input#x1').attr("tabindex", "1");
    $('#uksearchform :input#x1').attr("autocomplete", "off");
    $('#uksearchform :input#x2').attr("tabindex", "2");
    $('#uksearchform :input#x2').attr("autocomplete", "off");
    
    //if($('#uksearchform :input#x1').val() == "") $('#uksearchform :input#x1').val(_LNG_srch_what);
    if($('#uksearchform :input#x2').val() == "") $('#uksearchform :input#x2').val(_LNG_srch_where);
    
    $("#uksearchform :input#x1").focus(function()
    {
      if($(this).val() == _LNG_srch_what) $(this).val('');
      _srch_field_where = ($("#uksearchform :input#x2").val() != _LNG_srch_where) ? $("#uksearchform :input#x2").val() : "";

			$("#uksearchform :input#x1").autocomplete({
			    source: "/"+ajxUrl+"/acpl/?where="+_srch_field_where,
			    dataType: "json",
			    minLength: 2,
				open: function(event, ui) {
					$('.ui-autocomplete li:nth-child(even)').addClass('even');
				}
			});
		});
    

    $("#uksearchform :input#x2").focus(function()
    {
      if($(this).val() == _LNG_srch_where) $(this).val('');
      _srch_field_what = ($("#uksearchform :input#x1").val() != _LNG_srch_what) ? $("#uksearchform :input#x1").val() : "";

			$("#uksearchform :input#x2").autocomplete({
			    source: "/"+ajxUrl+"/acpl/addr/?what="+_srch_field_what,
			    dataType: "json",
			    minLength: 2,
				open: function(event, ui) {
					$('.ui-autocomplete li:nth-child(even)').addClass('even');
				}
			});
		});
 
    $("#uksearchform").submit(function()
    {
      if($(':input#x1').val() == 'Nosaukums, pakalpojums...')   $(':input#x1').val('');
      if($(':input#x1').val() == 'Название, услуга...')         $(':input#x1').val('');
      if($(':input#x1').val() == 'Name, service ...')           $(':input#x1').val('');
      if($(':input#x2').val() == 'Rajons, pilsēta, iela...')    $(':input#x2').val('');
      if($(':input#x2').val() == 'Регион, город, улица ...')    $(':input#x2').val('');
      if($(':input#x2').val() == 'Район, город, улица ...')     $(':input#x2').val('');
      if($(':input#x2').val() == 'Region, city, street ...')    $(':input#x2').val('');
      return true;
    });
    
    $(':input#x1').focus();

  }

  if($("#marathon-user-form").length)
  {
	  if($('#marathon-user-form :input#xx1').val() == "") $('#marathon-user-form :input#xx1').val("Numurs...");
	  if($('#marathon-user-form :input#xx2').val() == "") $('#marathon-user-form :input#xx2').val("Vārds, uzvārds...");
	  if($('#marathon-user-form :input#xx3').val() == "") $('#marathon-user-form :input#xx3').val("Komanda...");

		$("#marathon-user-form :input#xx1").focus(function(){
			    if($(this).val() == "Numurs...") $(this).val(''); });
		$("#marathon-user-form :input#xx2").focus(function(){
			    if($(this).val() == "Vārds, uzvārds...") $(this).val(''); });
		$("#marathon-user-form :input#xx3").focus(function(){
			    if($(this).val() == "Komanda...") $(this).val(''); });

		$("#marathon-user-form").submit(function(){
	    if($('#marathon-user-form :input#xx1').val() == "Numurs...")
    		$('#marathon-user-form :input#xx1').val("");
	    if($('#marathon-user-form :input#xx2').val() == "Vārds, uzvārds...")
    		$('#marathon-user-form :input#xx2').val("");
	    if($('#marathon-user-form :input#xx3').val() == "Komanda...")
    		$('#marathon-user-form :input#xx3').val("");
		});
  }



  if($("#mapsearchform").length)
  {
    var ajxUrl = 'katalogs' ;

    $('#mapsearchform :input#whatSearch').attr("autocomplete", "off");
    $('#mapsearchform :input#whereSearch').attr("autocomplete", "off");

    if($('#mapsearchform :input#whatSearch').val() == "") $('#mapsearchform :input#whatSearch').val(_LNG_srch_what);
    if($('#mapsearchform :input#whereSearch').val() == "") $('#mapsearchform :input#whereSearch').val(_LNG_srch_where);

    $("#mapsearchform :input#whatSearch").focus(function()
    {
      if($(this).val() == _LNG_srch_what) $(this).val('');
      _srch_field_where = ($("#mapsearchform :input#whereSearch").val() != _LNG_srch_where) ? $("#mapsearchform :input#whereSearch").val() : "";

			$("#mapsearchform :input#whatSearch").autocomplete({
			    source: "/"+ajxUrl+"/acpl/?where="+_srch_field_where,
			    dataType: "json",
			    minLength: 2,
				open: function(event, ui) {
					$('.ui-autocomplete li:nth-child(even)').addClass('even');
				}
			});
		});

    $("#mapsearchform :input#whereSearch").focus(function()
    {
      if($(this).val() == _LNG_srch_where) $(this).val('');
      _srch_field_what = ($("#mapsearchform :input#whatSearch").val() != _LNG_srch_what) ? $("#mapsearchform :input#whatSearch").val() : "";

			$("#mapsearchform :input#whereSearch").autocomplete({
			    source: "/"+ajxUrl+"/acpl/addr/?what="+_srch_field_what,
			    dataType: "json",
			    minLength: 2,
				open: function(event, ui) {
					$('.ui-autocomplete li:nth-child(even)').addClass('even');
				}
			});
		});

    $("#mapsearchform").submit(function()
    {
      if($(':input#whatSearch').val() == 'Nosaukums, pakalpojums...')   $(':input#whatSearch').val('');
      if($(':input#whatSearch').val() == 'Название, услуга...')         $(':input#whatSearch').val('');
      if($(':input#whatSearch').val() == 'Name, service ...')           $(':input#whatSearch').val('');
      if($(':input#whereSearch').val() == 'Rajons, pilsēta, iela...')    $(':input#whereSearch').val('');
      if($(':input#whereSearch').val() == 'Регион, город, улица ...')    $(':input#whereSearch').val('');
      if($(':input#whereSearch').val() == 'Район, город, улица ...')     $(':input#whereSearch').val('');
      if($(':input#whereSearch').val() == 'Region, city, street ...')    $(':input#whereSearch').val('');
      return true;
    });

  }



  $.fn.typewriter = function() {
          this.each(function() {
              var $ele = $(this), str = $ele.text(), progress = 0;
              $ele.text('_');

              $ele.mouseover(
              	function(){
              		$ele.text(str);
              		clearInterval(timer);
              	}
              )
              var timer = setInterval(function() {
                  $ele.text(str.substring(0, progress++) + (progress & 1 ? '_' : ''));
                  if (progress > str.length){
                 	  clearInterval(timer);
                 	  setTimeout(function(){ $ele.typewriter() },500);
                   }
              }, 80);
          });
          return this;
  }

  if( $('#TextAdText') ){
	  $('#TextAdText').typewriter();
  }



  jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
  };


//----------------------------
	$(".MainMenu > b > a").removeAttr("href");
	$(".MainMenu > b > a").removeAttr("onclick");
	$(".MainMenu > b > a").click( function(){
		className =  $(this).parent().attr('class').split(' ').slice(-1);
		if( $(this).parent().next("div").hasClass("open") ){
			$(this).parent().next("div").slideUp("slow");
			$(this).parent().next("div").removeClass("open");
			max = openedMenu.length;
			for(i=0; i<=max; i++){
				if( openedMenu[i] == className ){
					openedMenu[i] = null;
				}
			}
		}else{
			$(this).parent().next("div").slideDown("slow");
			$(this).parent().next("div").addClass("open");
			openedMenu[openedMenu.length] = className;
			openedMenu = openedMenu.getUniqueValues();
		}
		$.cookie('openedMenu', openedMenu, { path: '/' });
		return false;
	}
	);


	menu = $.cookie('openedMenu');
	if( menu ){
		openedMenu = menu.split(',');
	}

	for (value in openedMenu){
		if( typeof(openedMenu[value])=='string' && openedMenu[value] != ""){
      $('.'+openedMenu[value]).next("div").addClass("open");
		}
	};

	if(openedMenu.length==0){
		 $('div.MenuLevel2').each(
		 	function(){
		 		if( $(this).hasClass("open") ){
		 			className =  $(this).prev().attr('class').split(' ').slice(-1);
		 			openedMenu.push(className);
		 		}
		 	}
		 );
		$.cookie('openedMenu', openedMenu, { path: '/' });
	}

	$('#AllServiceOpen').click(
		function(){
			if( !AllServicesIsOpened){
				showAllServices();
			}else{
				hideAllServices();
			}
			return false;
		}
	);


	/*$('#AllServiceOpen div').mouseleave(
		function(){
			setTimeout( 'hideAllServices()', 1000);
		}
	);*/

	$('#AllServiceOpen div ul.AllServices li a').click(
		function(){
			document.location = $(this).attr('href');
		}
	);

  /* Labā Bloka Izvēlnes */
  $('.ProfileMenu .ProfileMenuHead').click(function() {
    if($(this).hasClass("open")){
      $(this).removeClass("open");
      $(this).next().slideUp('normal');
    }else{
      $(this).addClass("open");
      $(this).next().slideDown('normal');
    }
  });

  /* Labā Bloka Izvēlnes */
  $('.ProfileSmall .showmenu').click(function() {
    if($('.Profile .ProfileMenu').hasClass('ProfileMenuOpened')){
      $('.Profile .ProfileMenu').removeClass('ProfileMenuOpened').slideUp();
    }else{
      $('.Profile .ProfileMenu').addClass('ProfileMenuOpened').slideDown();
    }
  });

 /* POOL */

  if( $('#poll').length ){
    var poll_load = 0;
    function get_answers(){
      if( $('#poll').text() == '' || poll_load == 1 ){
        $.ajax({
          type: 'GET',
          url: '/poll/?get',
          dataType: 'html',
          success: function(data){
            $('#poll').html(data);
            get_vote();
          }
        });
      }else{
        poll_load = 1;
         get_vote();
      }
    }

    function get_vote(){
      $('#poll_results').click(function(){ get_results(); });
      $('#poll .radio').click(function(){
        var aid = $(this).val();
        $('#poll .radio').css('visibility', 'hidden');
        $.ajax({
          type: 'GET',
          url: '/poll/?vote&id='+ aid,
          dataType: 'html',
          success: function(data){
            $('#poll').html(data);
            $('#poll_vote').click(function(){ get_answers(); });
          }
        });
      });
    }

    function get_results(){
      $.ajax({
        type: 'GET',
        url: '/poll/?res',
        dataType: 'html',
        success: function(data){
          $('#poll').html(data);
          $('#poll_vote').click(function(){ get_answers(); });
        }
      });
    }

    get_answers();
  }

 /* Open Forma - Pievienot Uzņēmumu */

 $('a#foot_add_company').click(function()
 {
  $.postJSON(this.href, {},
    function(json){
      if(json.STATUS == 'OK'){
        var branches = "";
        var CADD_HTMLForm = json.HTML;
        if($('#dialog')) $('#dialog').remove();
        $('#Wrap').append('<div id="dialog"">'+CADD_HTMLForm+'</div>');
        $("#dialog").dialog({
          beforeclose : function(){$('#dialog').remove();},
          title: _LNG_add_company,
          modal: true,
          width: 600,
          closeOnEscape: true,
          resizable: false
        });

        //$('#add_company_form :input#acf_sector').attr("autocomplete", "off");
        //$("#add_company_form :input#acf_sector").autocomplete('/company/add/search/sector/',{});

      }
    });
    return false;
 });

 /* END OF :: Open Forma - Pievienot Uzņēmumu */

});

function SubmitAddCompanyForm()
{
  var addCompanyForm = ":form#add_company_form";
  var autoSector = "";;
  var formElements = {};

  $("#add_company_form :input").each(function(){
    if(this.name && this.name != null && this.name != ""){
      var elmKey    = this.name;
      var elmVal    = this.value;
      formElements[elmKey] = elmVal;
    }
  });

  $(".BranchesList div").each(function(k, v){
      if(v.textContent && v.textContent != null){
        var seper = (autoSector.length > 0) ? ', ' : '';
        autoSector += seper + v.textContent;
      }
  });

  if(jQuery.trim($(":input#acf_name").val()) == ""){
      $('#dialog .Alert').html("<p>"+_LNG_add_company_no_name+"</p>").slideDown(); return; }

  seper = (formElements['acf_sector'] > 0) ? ', ' : '';
  formElements['acf_sector'] =  formElements['acf_sector'] +seper+ autoSector;

  $.postJSON('/company/add/send/', formElements,
    function(json){
      if(json.STATUS == 'OK'){
        if($('#dialog')) $('#dialog').remove();
        showNotification(_LNG_add_company_sent);
      }
    }
  );
}

var AllServicesIsOpened = false;

function showAllServices(){
	$('#AllServiceOpen').removeClass('services');
	$('#AllServiceOpen').addClass('services-selected');
	$('#AllServiceOpen p').show();
	$('#AllServiceOpen div').slideDown('slow');
	AllServicesIsOpened = true;
}

function hideAllServices(){
	setTimeout( function(){
		 $('#AllServiceOpen p').hide();
		 $('#AllServiceOpen').removeClass('services-selected');
		 $('#AllServiceOpen').addClass('services');
		 AllServicesIsOpened = false;
		 }, 500);
	$('#AllServiceOpen div').slideUp('300');
}

function showNotification(msg)
{
  if(msg){
    var AlertHTML  = "<div><a class=\"close\" href=\"#\" title=\"Aizvērt!\"></a><p>";
          AlertHTML += msg;
        AlertHTML += "</p></div>";
  }
  $('#Wrap .AlertBig').html(AlertHTML); $('#Wrap .AlertBigTop').slideDown();
  $('#Wrap .AlertBig a.close').click(function(){$('#Wrap .AlertBigTop').slideUp();});
  setTimeout( function(){$('#Wrap .AlertBigTop').slideUp();}, 20000);
}

function openLetterBox(letter)
{
  $('.letterBlock').hide();
  $('div.letterBlock.L-'+letter).fadeIn();
  $('ul.BranchesLetters li').removeClass('selected');
  $('ul.BranchesLetters li.LB-'+letter).addClass('selected');
}

/**
*  URL encode / decode
*
**/
var Url = {
  // public method for url encoding
  encode : function (string) {
    return escape(this._utf8_encode(string));
  },
  // public method for url decoding
  decode : function (string) {
    return this._utf8_decode(unescape(string));
  },
  // private method for UTF-8 encoding
  _utf8_encode : function (string) {
    string = string.replace(/\r\n/g,"\n");
    var utftext = "";
    for (var n = 0; n < string.length; n++) {
      var c = string.charCodeAt(n);
      if (c < 128) {
        utftext += String.fromCharCode(c);
      }
      else if((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192);
        utftext += String.fromCharCode((c & 63) | 128);
      }
      else {
        utftext += String.fromCharCode((c >> 12) | 224);
        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
        utftext += String.fromCharCode((c & 63) | 128);
      }
    }
    return utftext;
  },
  // private method for UTF-8 decoding
  _utf8_decode : function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;
    while ( i < utftext.length ) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      }
      else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      }
      else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
    }
    return string;
  }
}

