var ret = true;


var mess = "All mandatory fields must be field in.";

if(typeof GClientGeocoder == 'function')
  var geocoder = new GClientGeocoder();

var submitFormEl = null;
var sForm = null

//Индикатор проверки геолокации
var geoCheker = false;
var adSearchRet = false;

$(document).ready(function() {
	$('p.label.num-1').click(function(){
		$(this).hide();
		$('#password').focus();
	})
	$('p.label.num-2').click(function(){
		$(this).hide();
		$('#password_confirm').focus();
	})
	$('#email').focusin(function(){$(this).attr('value','');});

  $(".menuLinkBlock").each(function() {
    var itemLen = $(this).children('.topMenuLink').width();
    $(this).children('div').children('.towel_center').attr('width', parseInt(itemLen) + 55);
  });

  if($('.aboutGallery a').length > 0) {
    $('.aboutGallery a').lightBox({
      imageBtnClose: '/images/lightbox-btn-close.gif',
      imageLoading:  '/images/lightbox-ico-loading.gif ',
      imageBtnPrev:  '/images/lightbox-btn-prev.gif',
      imageBtnNext:  '/images/lightbox-btn-next.gif'
    });
  }


  var shrinkFunc = function(dimension) {
    return dimension;
  }

  $(function() {
    if($('div.gallery').length > 0)
      $('div.gallery img').slidingGallery({Lheight:'308', Lwidth:'460', gutterWidth:-320, container:$('#slideShow')});
  });

  if($('.thumbnail').length > 0)
    $('.thumbnail').imgAreaSelect({onSelectChange: preview});

	$('#saveCrop').click(function() {
		var x1 = $('#x1').val();
		var y1 = $('#y1').val();
		var x2 = $('#x2').val();
		var y2 = $('#y2').val();
		var w = $('#w').val();
		var h = $('#h').val();
		if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
			alert("You must make a selection first");
			return false;
		}else{
			return true;
		}
	});

  if($("#profileTabs").length > 0)
    $("#profileTabs").tabs();

  $(".datapicer").datepick({
    changeMonth: false,
    multiSelect: 999,
    monthsToShow: 1,
    showTrigger: '#calImg'
  });


  $("#signUpForm > form > .input > label").click(function() {
    $(this).hide();
  });

  if($("#signUpForm > form > .input > #UserEmail").val() != '') {
    $("#signUpForm > form > .input > #UserEmail").parent().children('label').hide();
  }

  $("#signUpForm > form > .input > input").focus(function() {
    $(this).parent().children('label').hide();
  });

  $("#GoRegister").click(function() {
    $(this).parent().submit();
  });

  $("#signInBtn").click(function() {
    $("#popupContent").load('/users/login/', function() {
      $("#popupHeader").html($("#popupLabel").html());
      $("#shadow").css('height', $(document).height() + 'px').show();
      $("#popup").show();
    });

    return false;
  });

  $(".topMenuLink").hover(
    function() {
      if($(this).next().hasClass('topMenyHide'))
        $(this).css('background', 'url(/img/menu_hover.jpg) no-repeat center');
    },
    function() {
      $(this).css('background', 'none');
      //$(this).css('background', 'url(/img/menu.png) no-repeat');
    }
  );

  $("#postAnAd").click(function() {
    window.location.href = '/ads/create/';
    return false;
  });

  $(document).resize(function() {
    $("#shadow").css('height', $(document).height() + 'px');
  });

  $(document).keyup(function(e) {
    // esc
    if (e.keyCode == 27) {
      $("#shadow").css('display', 'none');
      $("#notRegister").show();
      $("#resizer").remove();
    }
  });

  $(".x").click(function() {
    $("#shadow").css('display', 'none');
    $("#notRegister").show();
    $("#resizer").remove();
  });

  $("#notRegister").click(function() {
    $("#popupContent").load('/users/register_complie/', function() {
      $("#popupHeader").html($("#popupLabel").html());
      $("#popup").show();
      $('body').append('<div id="resizer" style="height:200px;">&nbsp;</div>');
      $("#shadow").css('height', $(document).height() + 'px')

      $("#shadow").show();
      $("#notRegister").hide();
    });
  });

  $(".bebeficiaryPopup").click(function() {
    $("#popupContent").load($(this).attr('href'), function() {
      $("#popupHeader").html($("#popupLabel").html());
      $("#shadow").css('height', $(document).height() + 'px')
      $("#popup").show();
      $("#shadow").show();
    });
    return false;
  });

  $(".popUpLinkCancelSubscription").click(function() {
    $("#popupContent").load($(this).attr('href'), function() {
      $("#popupHeader").html($("#popupLabel").html());
      $("#shadow").css('height', $(document).height() + 'px')
      $("#popup").css({marginTop : '300px'}).show();
      $("#shadow").show();
    });
    return false;
  });

  $(".popUpLink").click(function() {
    $("#popupBig").hide();

    $("#popupContent").load($(this).attr('href'), function() {
      $("#popupHeader").html($("#popupContent > #popupLabel").html());

      $('.datepicer').datepicker({
        dateFormat: 'dd/mm/yy',
        gotoCurrent: true,
        showOn: "both",
        buttonImage: "/img/calendar.png",
        buttonImageOnly: true,
        changeYear: true,
        yearRange: '1980:c',
        maxDate : "+0",
        minDate : "01/01/1980"
      });


      $('.babyDatepicer').datepicker({
        dateFormat: 'dd/mm/yy',
        gotoCurrent: true,
        showOn: "both",
        buttonImage: "/img/calendar.png",
        buttonImageOnly: true,
        changeYear: true,
        yearRange: '1980:c',
        maxDate : "+0",
        minDate : "01/01/1980"
      });

      //$("#shadow").css('height', $(document).height() + 'px').show();

//      var lleft = 0;
//      $("#popup").show(5, function() {
//        $("#shadow").show(100);
//        lleft = ($("#popup").width() / 2) * -1;
//        alert($("#popup").width());
//      }).center();
//
//      $("#popup").css('marginLeft', lleft + 'px');
      $("#popup").show();
      $("#shadow").show(100);
    });
    return false;
  });

  //Попап для Facebook
  $(".fbPopUpLink").click(function() {
    FB.ui({method: 'apprequests', message: 'http://coogny.visual-craft.com/', data: 'tracking information for the user'});
    return false;
  });

  $(".popUpLinkBig").click(function() {
    $("#popup").hide();
    $("#popupContentBig").load($(this).attr('href') + '?about', function() {
      $("#popupHeaderBig").html($("#popupContentBig > #popupLabel").html());

      $('.datepicer').datepicker({
        dateFormat: 'dd/mm/yy',
        gotoCurrent: true,
        showOn: "both",
        buttonImage: "/img/calendar.png",
        buttonImageOnly: true,
        changeYear: true,
        yearRange: '1980:c',
        maxDate : "+0",
        minDate : "01/01/1980"
      });

      $('.babyDatepicer').datepicker({
        dateFormat: 'dd/mm/yy',
        gotoCurrent: true,
        showOn: "both",
        buttonImage: "/img/calendar.png",
        buttonImageOnly: true,
        changeYear: true,
        yearRange: '1980:c',
        maxDate : "+0",
        minDate : "01/01/1980"
      });



      $("#popupBig").show();
      $("#shadow").css('height', (parseInt($(document).height()) + parseInt(180)) + 'px').show();
    });
    return false;
  });

  $('.popUpAvailibility').click(function() {
    $("#popup").hide();
    $("#popupContentBig").load($(this).attr('href'), function() {
      $("#popupHeaderBig").html($("#popupContentBig > #popupLabel").html());

      $(".datapicer").datepick({
        dateFormat: 'dd/mm/yyyy',
        changeMonth: false,
        multiSelect: 999,
        monthsToShow: 1,
        showTrigger: '#calImg',
        onSelect: function(dates) {
          var value = '';
          for (var i = 0; i < dates.length; i++) {
              value += (i == 0 ? '' : ",") + $.datepick.formatDate('dd/mm/yyyy', dates[i]);
          }
          $('#UserFreeText').val(value || '');
        }

      });

      var dates = $('.datapicDates').html().split(',');
      $(".datapicerPopup").datepick('setDate', dates);

      $("#popupBig").show();
      $("#shadow").css('height', $(document).height() + 'px').show();
      $(".datepick-today").css({backgroundColor:'#FFF !important', color:'#858585'});
    });
    return false;

  });

  $(".closeStatusField").click(function() {
    $(this).parent().hide();
  });

  if($("#flashMessage").html() != '' && $("#flashMessage").html() != null) {
    $("#statusField").show();
  }

  if($('.datepicer').length > 0)
    $('.datepicer').datepicker({
      dateFormat: 'dd/mm/yy',
      gotoCurrent: true,
      showOn: "both",
      buttonImage: "/img/calendar.png",
      buttonImageOnly: true,
      changeYear: true,
      yearRange: '1980:c',
      maxDate : "+0",
      minDate : "01/01/1980"
    });

  if($('.babyDatepicer').length > 0)
    $('.babyDatepicer').datepicker({
      dateFormat: 'dd/mm/yy',
      gotoCurrent: true,
      showOn: "both",
      buttonImage: "/img/calendar.png",
      buttonImageOnly: true,
      changeYear: true,
      yearRange: '1980:c',
      maxDate : "+0",
      minDate : "01/01/1980"
    });

  if($('#AdStart').length > 0)
    var datess = $('#AdStart, #AdFinish').datepicker({

      dateFormat: 'dd/mm/yy',
      gotoCurrent: true,
      showOn: "both",
      buttonImage: "/img/calendar.png",
      buttonImageOnly: true,
      minDate: "+0",

      onSelect: function( selectedDate ) {
            var option = this.id == "AdStart" ? "minDate" : "maxDate",
              instance = $( this ).data( "datepicker" );

              date = $.datepicker.parseDate(
                instance.settings.dateFormat ||
                $.datepicker._defaults.dateFormat,
                selectedDate, instance.settings );
            datess.not( this ).datepicker( "option", option, date );
          }
    });

  //Проверка обязательных полей при регистрации
  $("form").submit(function() {
    var ret = true;
//    $('.mandatory').css('border-color','');
//
//    $('.mandatory').each(function() {
//      if($(this).val() == '') {
//        $(this).css('border-color','red');
//        ret = false;
//      }
//    });
//    if(!ret)
//      alert('All mandatory fields must be field in.');
//    return ret;
      chechMandatory($(this));

      if(ret == false) {
        alert(mess);
      }

      return ret;
  });


  $("#UserDateOfBirth").live('focus', function() {
    var fieldVal = $(this).val();

    if(fieldVal == 'jj/mm/aaaa')
      $(this).val('')
  });

  $("#UserDateOfBirth").live('blur', function() {
    var fieldVal = $(this).val();

    if(fieldVal == 'jj/mm/aaaa')
      $(this).val('jj/mm/aaaa')
    else if(fieldVal == '')
      $(this).val('jj/mm/aaaa')
  });

  //Галочки при регистрации
  $(".willDo").change(function() {
    var changeOn = 0;
    var selElement = $(this).attr('class').replace('willDo ', '');

    if($("." + selElement + ":checked").length > 0)
      changeOn = 1;

    $("#User" + selElement).attr('checked', changeOn);
  });

  $("#fb_conn").live('click', function() {
    myRef = window.open(
    $(this).attr('href'),
    'FacebookConnect',
    'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
    return false;
  });

  $("#fbconnectSmall").live('click', function() {
    myRef = window.open(
    $(this).attr('href'),
    'FacebookConnect',
    'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
    return false;
  });

  $("#setAvail").live('submit', function() {
    var dates = $('.datepicer').datepick('getDate');
    var value = '';
    for (var i = 0; i < dates.length; i++) {
        value += (i == 0 ? '' : ',') + $.datepick.formatDate(dates[i]);
    }
    $('#UserFreeText').val(value || 'none');

    return false;
  });

  $(".slide").hide();
  $(".slide:first").show().addClass('cur');
  //setTimeout("pageSlideshow()", 5000);

  var zIndex = 99;
  $(".slide").each(function() {
    $(this).children('img').attr({width:'230',height:'120'});
    $(this).css('z-index', zIndex--);
    $(this).css({left:'-100px', top:'10px'})
  });
  $('.slide:first').children('img').attr({width:'255',height:'135'});

  if($('div.gallery').length > 0)
    setTimeout("moveSlideRight()", 5000);


  //Проверка форм в попапах на обязательные поля
  $("form").live('submit', function() {

    if(geoCheker == true) {
      return true;
    }

    submitFormEl = $(this);

    if($(this).find("#UserAddress").length > 0) {

      ret = true;
      //Проверяем адресс и обязательные поля
      chechMandatory($(this));
      if(ret == true) {
        address = $("#UserCountry").val() + ',' +  $("#UserCity").val() + ',' + $("#UserAddress").val();
        addressRevers = $("#UserAddress").val() + ',' +  $("#UserCity").val() +  ',' + $("#UserCountry").val();
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {

              geocoder.getLatLng(
                addressRevers,
                function(point) {
                  if (!point) {
                    ret = false;
                    mess = address + " not found";

                    geoCheker = false;

                    if(ret == false) {
                      alert(mess);
                    }

                    return ret;
                  } else {
                    $("#UserPoint").val(point);
                    geoCheker = true;
                    submitFormEl.submit();

                  }
                }
              );


              //              ret = false;
              //              mess = address + " not found";
              //
              //              geoCheker = false;
              //
              //              if(ret == false) {
              //                alert(mess);
              //              }
              //
              //              return ret;
            } else {
              $("#UserPoint").val(point);
              geoCheker = true;
              submitFormEl.submit();

            }
          }
        );
          return false;
      } else {
        chechMandatory($(this));
        if(ret == false) {
          alert(mess);
        }

        return ret;
      }



    } else {
      ret = true;
      //Проверяем на не пустое значение
      chechMandatory($(this));

      if(ret == false) {
        alert(mess);
      }

      return ret;
    }


  });

  $("#UserImage").live('change', function() {
    var file = $(this).val();
    file = file.split('\\');
    $(".imageName").html(converFileName(file[file.length - 1]));
  });

  $("#AboutPhoto1").live('change', function() {
    var file = $(this).val();
    file = file.split('\\');
    $(".AboutPhoto1").html(converFileName(file[file.length - 1]));
  });

  $("#AboutPhoto2").live('change', function() {
    var file = $(this).val();
    file = file.split('\\');
    $(".AboutPhoto2").html(converFileName(file[file.length - 1]));
  });

  $("#AboutPhoto3").live('change', function() {
    var file = $(this).val();
    file = file.split('\\');
    $(".AboutPhoto3").html(converFileName(file[file.length - 1]));
  });

  $("#AboutPhoto4").live('change', function() {
    var file = $(this).val();
    file = file.split('\\');
    $(".AboutPhoto4").html(converFileName(file[file.length - 1]));
  });

  $("#BeneficiaryImage").live('change', function() {
    var file = $(this).val();
    file = file.split('\\');
    $(".BeneficiaryImage").html(converFileName(file[file.length - 1]));
  });


  $("#AdFrom").focus(function() {
    if($(this).val() == $("#AdDateValForFrom").val())
      $(this).val('');
  });

  $("#AdFrom").blur(function() {
    if($(this).val() == '')
      $(this).val($("#AdDateValForFrom").val());
  });


  $("#UserFrom").focus(function() {
    if($(this).val() == $("#UserDateValForFrom").val())
      $(this).val('');
  }).blur(function() {
    if($(this).val() == '')
      $(this).val($("#UserDateValForFrom").val());
  });

  if($('#UserFromDate, #UserToDate, #AdFromDate, #AdToDate').length > 0)
    $('#UserFromDate, #UserToDate, #AdFromDate, #AdToDate').datepicker({
      dateFormat: 'dd/mm/yy',
      gotoCurrent: true,
      showOn: "both",
      buttonImage: "/img/calendar.png",
      buttonImageOnly: true
    });

  $(".searchAdForm").submit(function() {
    sForm = $(this);
    if(adSearchRet == true)
      return true;

    if($("#AdFrom").val() != '' && $("#AdFrom").val() != $("#AdDateValForFrom").val() && $("#AdFrom").val() != $("#AdDefAddress").val()) {
      var adAdress = $("#AdUserCountry").val() + ',' + $("#AdFrom").val();
      showAddress(adAdress);
      return false;
    }

  });

  $(".searchUserForm").submit(function() {
    sForm = $(this);
    if(adSearchRet == true)
      return true;

    if($("#UserFrom").val() != '' && $("#UserFrom").val() != $("#UserDateValForFrom").val() && $("#UserFrom").val() != $("#UserDefAddress").val()) {
      var adAdress = $("#UserUserCountry").val() + ',' + $("#UserFrom").val();
      showAddressUser(adAdress);
      return false;
    }

  });

  $(".requestStars > div").live('click', function() {

    $(this).parent().children().each(function() {
      if($(this).attr('class') != 'end')
        $(this).attr('class', 'star');
    });

    $(this).attr('class', 'star_sel');
    $(this).prevAll().attr('class', 'star_sel');

    $(this).parent().parent().parent().children('#EvaluationStars').val($(this).parent().children('.star_sel').length);
  });

  $(".favUser").hover(
    function() {
      $(this).children('.deleteFromFav').show();
    },
    function() {
      $(this).children('.deleteFromFav').hide();
    }
  );

  $("#downFavList").click(function() {
    $("#profileFavList").slideDown('500');
    $(this).hide();
  });

  $(".submitLoginFormSideBar").click(function() {
    $('#sideBarLoginForm').submit();
    return false;
  });

});


function converFileName(fileName) {
  var newName = fileName;
  if(fileName.length > 6) {
    newName = fileName.substring(0, 5) + '...' + fileName.substring(fileName.length-4);
  }
  return newName;
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}


function moveSlideRight() {
  var elId = curSlideSrc.replace('/pub/slideshow/', '');
  elId = elId.replace('.jpg', '');

  $(".moveSlide").removeClass('curSlide');

  if($("#"+elId).next().length > 0)
    $("#"+elId).next().addClass('curSlide');
  else
    $(".moveSlide:first").addClass('curSlide');

  $.galleryUtility.slideLeft();
  setTimeout("moveSlideRight()", 5000);
}

var neadEl = "";

function showSlide() {
  if(curSlideSrc != neadEl) {
    $.galleryUtility.slideLeft();
    setTimeout("showSlide()", 500);
  }
}

function preview(img, selection) {
	$('#x1').val(selection.x1);
	$('#y1').val(selection.y1);
	$('#x2').val(selection.x2);
	$('#y2').val(selection.y2);
	$('#w').val(selection.width);
	$('#h').val(selection.height);
}

//var geocoder = new GClientGeocoder();
function showAddressAndCheck(el, address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        ret = false;
        mess = address + " not found";
        $("#UserPoint").val("");
      } else {
        $("#UserPoint").val(point);
        ret = true;
        chechMandatory(el);
      }
    }
  );
}

function showAddress(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        adSearchRet = false;
        $("#AdUserPoint").val("");
      } else {
        $("#AdUserPoint").val(point);
        adSearchRet = true;
        sForm.submit();
      }
    }
  );
}

function showAddress(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        adSearchRet = false;
        $("#AdUserPoint").val("");
      } else {
        $("#AdUserPoint").val(point);
        adSearchRet = true;
        sForm.submit();
      }
    }
  );
}

function showAddressUser(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        adSearchRet = false;
        $("#UserUserPoint").val("");
      } else {
        $("#UserUserPoint").val(point);
        adSearchRet = true;
        sForm.submit();
      }
    }
  );
}

//Проверяем на не пустое значение
function chechMandatory(el) {
   el.find('.mandatory').each(function() {

    if($(this).val() == '' || $(this).val() == 'jj/mm/aaaa') {
      $(this).css('border', '1px solid red');
      ret = false;
    } else {
      $(this).css('border', '1px solid #A8ACAD');
    }

    if(ret == true) {
     if($(this).hasClass('date')) {
        //Проверяем дату
          var enterDate = $(this).val().split('/');

          if(enterDate.length != 3)
            ret = false;

          if(enterDate[0] > 31) {
            ret = false;
          }

          if(enterDate[1] > 12) {
            ret = false;
          }

          if(enterDate[2] < 1900) {
            ret = false;
          }

          if(ret == false) {
            $(this).css('border', '1px solid red');
            mess = 'The date format should be dd/mm/yyyy';
          }
      }

      if($(this).hasClass('email')) {
        if(!(/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test($(this).val())) {
          ret = false;
          mess = 'Please enter a valid email address.';
        }
      }

    }
  });

  return ret;
}
window.onload = function(){
	//var h = $(window).height() - 297;
	//$('div#center').css('min-height', h);
	//$('#calendar2 tr:odd td a').css('background-color','#eaf1ff');
	$(".datepick-today").css({backgroundColor:'', color:'#858585'});
}
