var advancedSearch = false;
var anch = false

function validateEmail(email){
var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(email.match(emailRegEx)){
return true
}else{
return false;
}
}

var counter = 0;

var validForm = true;
$(document).ready(function () {
	
	$('.Search #submit').click(function()
	{
		if ($('#code').val() != '')
		{
			$('#place').val('');
			$('#street').val('');
			$('#house').val('');
		}
	});

	$('.delPhoto').click( function(e){
	if (confirm('Ar tikrai norite ištrinti šį nuotrauką?'))
	{
	        $('.delPhoto').attr('disabled', true);
	        $('.delPhoto').fadeTo(0,0.5);
		$.getJSON('/Skelbimai/trintiNuotrauka/'+$(this).attr('rel'), {}, function(json){
	        $('.delPhoto').attr('disabled', false);
	        $('.delPhoto').fadeTo(0,1);
	        
	        var numFields = 5 - $('.delPhoto').length;
	        var note = $('.fileSelect p').clone();
		$('.fileSelect input[type="file"]').remove();
		$('.fileSelect p').remove();
		for (i=0;i<numFields;i++) $('.fileSelect').append('<input type="file" name="photos[]"/>');
		$('.fileSelect').append(note);
		 });
		$(this).parent().remove();
		counter = 0;
		$('.delPhoto').each(function(){
		var temp = $(this).attr('rel').split('/');
		$(this).attr('rel', temp[0] + '/' + counter);
		counter++;
		});
	};
	e.preventDefault();
	});

	$('.miniPhoto').hover(
		function (e)
		{
		        $('#adverPhotoMain').attr('src', this.href);
		        $('#adverPhotoMain_a').attr('href', $(this).attr('rel'));
			var temp = this.href;
			$(this).attr('href', $(this).attr('rel'));
			$(this).attr('rel', temp);
		},
		function (e)
		{
			var temp = this.href;
			$(this).attr('href', $(this).attr('rel'));
			$(this).attr('rel', temp);
		}
	);
	
	if (typeof($('body').fancybox) == 'function')
    {
    	$('#adverPhotoMain_a').fancybox({ 'hideOnContentClick': true });
    	$('.miniPhoto').fancybox({ 'hideOnContentClick': true });
    	$('.thumb').fancybox({ 'hideOnContentClick': true });
    };
	$('.miniPhoto').click(function(e){e.preventDefault();});

	$('#email').each(
	function(){

			var hint = $('[rel="'+this.id+'"]');
			$(hint).css('cursor','pointer');
			$(hint).click(
				function(){
					$('#'+$(this).attr('rel')).focus();
				}
			 );

	        $(this).focus(function(){
			var hint = $('[rel="'+this.id+'"]');
			if ($(hint).css('display') == 'block') $(hint).fadeOut('fast');
		});
		$(this).blur(function(){
			var hint = $('[rel="'+this.id+'"]');
			if ($(hint).css('display') == 'none' && $(this).val() != '' && !validateEmail($(this).val())) {
			$(hint).html('<div class="arr"></div>Neteisingas el. paštas');
			$(hint).fadeIn('fast');
			};
		});
		
	}
	);

	$('.required').each(
	function () {
	        $(this).parent().find('div.clear').before('<strong>*</strong>');

			var hint = $('[rel="'+this.id+'"]');
			$(hint).css('cursor','pointer');
			$(hint).click(
				function(){
					$('#'+$(this).attr('rel')).focus();
				}
			 );

	        $(this).focus(function(){
			var hint = $('[rel="'+this.id+'"]');
			if ($(hint).css('display') == 'block') $(hint).fadeOut('fast');
		});
		$(this).blur(function(){
			var hint = $('[rel="'+this.id+'"]');
			if ($(hint).css('display') == 'none' && $(this).val() == '') {
			$(hint).html('<div class="arr"></div>Lauką privaloma užpildyti');
			$(hint).fadeIn('fast');
			};
		});

	}
	);
	
	$('#email').blur(function(){
		var hint = $('[rel="email"]');
		if ($(hint).css('display') == 'none' && $(this).val() == '') {
		$(hint).html('<div class="arr"></div>Užpildykite el. paštą arba telefoną');
		$(hint).fadeIn('fast');
		};
	});
	
	$('#phone').blur(function(){
		var hint = $('[rel="phone"]');
		if ($(hint).css('display') == 'none' && $(this).val() == '') {
		$(hint).html('<div class="arr"></div>Užpildykite telefoną arba el. paštą');
		$(hint).fadeIn('fast');
		};
	});
	
	$('#skelbimoForma').submit(function(e){
		validForm = true;
		$('.required').each(
		function () {
			if (this.name == 'specId' && $('#catId').val() != 8 && $('#catId').val() != 9  ) return true;
				var hint = $('[rel="'+this.id+'"]');
				if (this.type == 'checkbox')
				{
				        if (!this.checked) validForm = false;
					if ($(hint).css('display') == 'none' && !this.checked) {
						$(hint).fadeIn('fast');
	 				} else if (this.checked && $(hint).css('display') == 'block') {
						$(hint).fadeOut('fast');
					}
				} else {
				        if ($(this).val() == '') validForm = false;
					if ($(hint).css('display') == 'none' && $(this).val() == '') {
						$(hint).html('<div class="arr"></div>Lauką privaloma užpildyti');
						$(hint).fadeIn('fast');
	 				} else if ($(this).val() != '' && $(hint).css('display') == 'block') {
						$(hint).fadeOut('fast');
					}
				};
		}
		);
	
		var hint = $('[rel="email"]');
		if ( $('#email').val() != '' && !validateEmail( $('#email').val() ) )
		{
				validForm = false;
				$(hint).html('<div class="arr"></div>Neteisingas el. paštas');
				$(hint).fadeIn('fast');
		} 
		else if ($('#phone').val() == '' && $('#email').val() == '')
		{
			validForm = false;
			$(hint).html('<div class="arr"></div>Užpildykite el. paštą arba telefoną');
			$(hint).fadeIn('fast');
		}
		else if ( $(hint).css('display') == 'block' ) {
			$(hint).fadeOut('fast');
		}
		if ( $('#catId').val() != 8 && $('#catId').val() != 9 ) $('#spc').remove();
		
		if (validForm) this.submit();
		e.preventDefault();
	})

	$('.hint').each(
	function () {
		var offset = $(this).parent().width()+7;
		$(this).css('margin-left', offset + 'px');
 	}
	);

    $('#loginFormSwitch').click(
    function () {
      if ( $(this).hasClass('loginButtonOn') )
      {
      $(this).removeClass('loginButtonOn');
      $(this).addClass('loginButton');
      $('#loginForm').css('display','none');
      } else {
      $(this).addClass('loginButtonOn');
      $(this).removeClass('loginButton');
      $('#loginForm').css('display','block');
      }
    }
    )

    if (document.location.href.indexOf('#res') == -1);
    {
    if (anch===true)  document.location = document.location.href + '#res';
    }

    $('.result').hover(
    function () {
    $(this).attr('class','result_top');
    },
    
    function () {
    $(this).attr('class','result');
    }
    )

    $('[rel="external"]').attr('target','_blank');
    
    $('.plus').click(function () {
      if ($('[title="'+this.parentNode.parentNode.title+'"] > h1').attr('className') == '')
        {
          $(this).html('[ - ]');
          $(this.parentNode.parentNode).addClass('noSidePad');
          $('[title="'+this.parentNode.parentNode.title+'"] > h1').attr('className','hr');
          $('[title="'+this.parentNode.parentNode.title+'"] > .subContent').show('blind');
        } else {
          $(this).html('[ + ]');
          $('[title="'+this.parentNode.parentNode.title+'"] > .subContent').hide('blind',{},'normal',function()
          {
          $('[title="'+this.parentNode.title+'"]').removeClass('noSidePad');
          $('[title="'+this.parentNode.title+'"] > h1').attr('className','');
          }
          );
        };
    
    });
    
    $('#web').blur(
      function (){
          if (this.value != '' && $('#hasWeb').attr('checked')!='checked') $('#hasWeb').attr('checked','checked');
      }
    );

    $('#location').blur(
      function (){
          if (this.value == '') this.value = 'Visa Lietuva';
      }
    );
    $('#location').focus(
      function (){
          if (this.value == 'Visa Lietuva') this.value = '';
      }
    );

    $('#house_from').blur(
      function (){
          if (this.value == '') this.value = 'Nuo';
      }
    );
    $('#house_from').focus(
      function (){
          if (this.value == 'Nuo') this.value = '';
      }
    );

    $('#house_to').blur(
      function (){
          if (this.value == '') this.value = 'Iki';
      }
    );
    $('#house_to').focus(
      function (){
          if (this.value == 'Iki') this.value = '';
      }
    );
    
    
    $('.bottomLink > a').click(
      function (){
          if (this.className == 'dn')
            {
                $(this).removeClass();
                $(this).addClass('up');
                $(this).html('Greita paieška');
                $('#advancedSearch').show("blind", { direction: "vertical" }, 'slow');
            } else {
                $(this).removeClass();
                $(this).addClass('dn');
                $(this).html('Išplėstinė paieška');
                $('#advancedSearch').hide("blind", { direction: "vertical" }, 'slow');
            };
      }
    );
    
    $('#refresh').click(function(){
		$.ajax({
	  		url: '/Users/getAccount',
	  		success: function(data) {
	    		$('#account span').text(data);
	  		}
		});
	});
    
    $('.open-refills').click(function(){
    	$('.refills').show();
    });
});

var timeout = null;

function autocomplete(obj)
{
    if (timeout!=null) clearTimeout(timeout);
    timeout = setTimeout("getScopes('"+obj.value+"')",750);
    $('#autoComplete_scope').css('display','none');
    $('#autoComplete_scope').html('');
}

function autocomplete2(obj)
{
    if (timeout!=null) clearTimeout(timeout);
    timeout = setTimeout("getScopes2('"+obj.value+"')",750);
    $('#autoComplete_scope').css('display','none');
    $('#autoComplete_scope').html('');
}

function put(val)
{
  document.getElementById('scope').value = val;
    $('#autoComplete_scope').css('display','none');
    $('#autoComplete_scope').html('');
}

function updateScopeVal()
{
    var items = $('#scopeList').find('div');
    var arr = new Array();
    for (i=0;i<items.length;i++)
    {
      var item = items[i];
      arr.push(item.id.substr(6));
    }
    $('#scopeVal').val(arr.join(','));
}

function put2(obj)
{
  var id = obj.id.substr(3);
  var title = obj.innerHTML;
  var html = '<div id="scope_'+id+'"><a onclick="deleteScope('+id+')">[ - ]</a> '+title+'</div>';
  if ($('#scope_'+id).length == 0) $('#scopeList').append(html);
  updateScopeVal();
}

function deleteScope(id)
{
  $('#scope_'+id).remove();
  updateScopeVal();
}

function getScopes(q)
{
    timeout = null;
    $('#scope').addClass('ajaxLoad');
    $.post('/Catalog/scopeAutocomplete/',{query:  q},function (json){
    $('#scope').removeClass('ajaxLoad');
    if (json.length > 0)
    {
      for (i=0;i<json.length;i++)
      {
        var a = document.createElement('a');
        a.onclick = function () {
          put(this.innerHTML);
        };
        a.innerHTML = json[i].title;
        $('#autoComplete_scope').append(a);
      };
      $('#autoComplete_scope').css('display','block');
    };
    },'json');
}

function getScopes2(q)
{
    timeout = null;
    $('#scope').addClass('ajaxLoad');
    $.post('/Catalog/scopeAutocomplete/',{query: q},function (json){
    $('#scope').removeClass('ajaxLoad');
    if (json.length > 0)
    {
      for (i=0;i<json.length;i++)
      {
        var a = document.createElement('a');
        a.onclick = function () {
          put2(this);
        };
        a.innerHTML = json[i].title;
        a.id = 'sc_' + json[i].id;
        $('#autoComplete_scope').append(a);
      };
      $('#autoComplete_scope').css('display','block');
    };
    },'json');
}
