var loaded = !((navigator.appName == "Microsoft Internet Explorer") && ($.browser.version <= 7.0));
$(document).ready(function () {
  loaded = true;
  
  $('.n_str_1').attr('style','display:block');
  $('.main_menu .menu').find('li').mouseover(function(){
	$('.main_menu .menu li').removeClass('cur');
	$(this).addClass('cur');
	$('.menu_block_r[style*=block]').hide();
	var ghf=$(this).attr('class').split(' ');
	$('.n_'+ghf[0]).show();
  });
  
  $('input[name=mobi_tel],input[name=work_tel],input[name=home_tel],input[name=contact_tel]').mask("+7(***) *** ** **",{placeholder:"*"});
  
  
  $('.view_provision_credit').change(function(){
	if ($(this).val()=='другое')
	$('.other_provision').show().children('input').addClass('required').focus();
	else $('.other_provision').hide().children('input').removeClass('required');
  });
  
    $('.goal_credit').change(function(){
	if ($(this).val()=='другое') 
	$('.other_goal_credit').show().children('input').addClass('required').focus();
	else $('.other_goal_credit').hide().children('input').removeClass('required');
  });
  
  $('.view_activities').change(function(){
	if ($(this).val()=='другое') $('.other_activities').show().children('input').addClass('required').focus();
	else $('.other_activities').hide().children('input').removeClass('required');
  });
  
  $('.cel_get_credit').change(function(){
	if ($(this).val()=='другое') $('.other_get_credit').show().children('input').addClass('required').focus();
	else $('.other_get_credit').hide().children('input').removeClass('required');
  });
  
    $('.goal_credit').change(function(){
	if ($(this).val()=='смешанный') $('.difr_goal_credit').show().children('input').addClass('required').focus();
	else $('.difr_goal_credit').hide().children('input').removeClass('required');
  });
  
    $('.goal_credit').change(function(){
	if ($(this).val()=='другое') $('.other_goal_credit').show().children('input').addClass('required').focus();
	else $('.other_goal_credit').hide().children('input').removeClass('required');
  });

});
 

$(document).mousemove(function(e){
  window.mouseX = e.pageX;
  window.mouseY = e.pageY;
});

function setslideshow(start, group) {
  slideshow = !slideshow;
  if (slideshow) {
    sliid = start;
    $("#link_slideshow").text('остановить');
    slid = window.setInterval(function(){
       setimage(setimage_links[group][sliid]);
       sliid++;
       if (sliid >= setimage_links[group].length) sliid = 0;
    }, 3000);
  } else {
    $("#link_slideshow").text('слайдшоу');
    clearInterval(slid);
  }
}

var setimage_links = {};

function setimage(elm) {
  if (typeof slideshow == "undefined") slideshow = false;

  var jqelm = $(elm);
  var imgsrc = jqelm.attr("href");
  var imgwidth = parseInt(jqelm.data("fullwidth"));
  var imgheight = parseInt(jqelm.data("fullheight"));
  var imgdescr = jqelm.data("descr");
  var group = jqelm.data("imgroup");
  if (typeof imgdescr == "undefined") imgdescr = "";

  var iid = 0;
  if (typeof group != "undefined") {
    if (group=="") group = "default";
    // строим массив элементов той же группы
    if (typeof setimage_links[group] == "undefined") {
      setimage_links[group] = [];
      $("A").each(function() {
        var t = $(this);
        var t_group = t.data("imgroup");
        if (typeof t_group != "undefined") {
          if (t_group=="") t_group = "default";
          if (t_group==group) {
            setimage_links[group][setimage_links[group].length] = t;
          }
        }
      });
    }
    // находим текущий элемент
    for (var i=0; i < setimage_links[group].length; i++) {
      if (setimage_links[group][i].is(jqelm)) {
        iid = i;
        break;
      }
    }
    var imcount = setimage_links[group].length;
  } else {
    var imcount = 1;
  }

  var cont = dialog("<img class='picmain' src='"+imgsrc+"'"+(imgwidth>0 ? " width='"+imgwidth+"'" : "")+(imgheight>0 ? " height='"+imgheight+"'" : "")+" alt='' />"+(imgdescr.length > 0 ? "<div class='fmtitle'>"+imgdescr+"</div>" : "")+"<div class='fmnav'>"+(imcount > 1 ? "Изображение "+(iid+1)+" из "+imcount+".<span class='fmlinks'></span>" : "")+"</div>", imgwidth, true);

  // навигация по картинкам
  if (imcount > 1) {
    var aprev = $("<a href='#'>&laquo; назад</a>");
    aprev.appendTo(cont.find(".fmlinks"));
    aprev.click(function(){setimage(setimage_links[group][iid>0 ? iid-1 : setimage_links[group].length-1]); return false;});
    $("<span>&nbsp;||&nbsp;</span>").appendTo($("#fmlinks"));

    var anext = $("<a href='#'>вперед &raquo;</a>");
    anext.appendTo(cont.find(".fmlinks"));
    anext.click(function(){setimage(setimage_links[group][iid < imcount-1 ? iid+1 : 0]); return false;});

    var aslide = $("<span>&nbsp;&nbsp;&nbsp;&nbsp;</span><a href='#' id='link_slideshow'>"+(slideshow ? "остановить" : "слайдшоу")+"</a>");
    aslide.appendTo(cont.find(".fmlinks"));
    aslide.click(function(){setslideshow((iid < imcount-1 ? iid+1 : 0), group); return false;});
  }


  var dragmove = function() {
    if (allowmove) {
      var curdist = (mouseX-startX)*(mouseX-startX) + (mouseY-startY)*(mouseY-startY);
      if (curdist > distance) distance = curdist;
      cont.css({marginLeft: mouseX - offsX, marginTop: mouseY - offsY});
    }
  }

  var startX = 0;
  var startY = 0;
  var offsX = 0;
  var offsY = 0;
  var allowmove = false;
  var distance = 0;
  var button = "LEFT";
  cont.find(".picmain").mousedown(function(event) {
    if (event.which == null) {
        button = (event.button < 2) ? "LEFT" : ((event.button == 4) ? "MIDDLE" : "RIGHT");
    } else {
        button = (event.which < 2) ? "LEFT" : ((event.which == 2) ? "MIDDLE" : "RIGHT");
    }
    if (button == 'LEFT') {
      startX = mouseX;
      startY = mouseY;
      distance = 0;
      offsX = startX - parseInt(cont.css('margin-left'));
      offsY = startY - parseInt(cont.css('margin-top'));
      allowmove = true;

      $(document).bind("mousemove", dragmove);
      try {
        this.setCapture();
      } catch(eee) {;}

      event.returnValue = false;
      return false;
    }
  });


  cont.find(".picmain").mouseup(function() {
    allowmove = false;
    var curdist = (mouseX-startX)*(mouseX-startX) + (mouseY-startY)*(mouseY-startY);
    if (curdist > distance) distance = curdist;
    $(document).unbind("mousemove", dragmove);
    try {
      this.releaseCapture();
    } catch(eee) {;}
    if (distance < 10) cont.find(".closelink").click();
  });

}



/* Показ диалога */
function dialog(html, width, moir) {
  if (!loaded) return;
  $(".dialog_window .closelink").click();
  var divcart = $("<div class='dialog_window'></div>");
  if ((typeof width != "undefined") && (width > 0)) divcart.css({width: width, marginLeft: -Math.round(width/2)});
  divcart.html("<a href='#' class='closelink' title='Закрыть'>&times;</a><div class='dialog_window_content'>"+html+"</div>");
  divcart.appendTo("body").fadeIn(200);
  divcart.css({marginTop: -Math.round(divcart.outerHeight()/2)});
  divcart.find(".closelink").click(function() {
    divcart.fadeOut(200, function(){$(this).remove();});
    $(".moirdiv").fadeOut(200, function(){$(this).remove();});
    return false;
  });
  if ((typeof moir != "undefined") && (moir)) {
    var moirdiv = $("<div class='moirdiv'></div>");
    moirdiv.css({height: $(document).height(), opacity: 0.3});
    moirdiv.appendTo("body").fadeIn(200);
    moirdiv.click(function(){divcart.find(".closelink").click();});
  }
  return divcart;
}

function emailcheck(email)
{      
var e = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
return e.test(email);
}

function strcheck(str){
var req_str=/^[\sА-ЯA-Zа-яa-z-]{3,100}$/;
return req_str.test(str);
}



function click_validate()
{
	arraymas= new Array();
	ind=0;
	$('.required').each(function(i){
		if ($(this).val()=='') 
		{
			$(this).css({'border':'1px solid #FB5352'}).addClass(''+i+'');
			arraymas[i]=false;
		}	
		else
		{
			$(this).css({'border':'1px solid #116047'}).removeClass(''+i+'');
			arraymas[i]=true;
		}
		ind=i;
	});
	 if (!emailcheck($('input[name=email]').val()))
	 {
		arraymas[ind+1]=false;
		$('input[name=email]').css({'border':'1px solid #FB5352'});
	 }
	 else
	 {
		arraymas[ind+1]=true;
		$('input[name=email]').css({'border':'1px solid #116047'});
	 }
	 
	 if (!strcheck($('input[name=name]').val()))
	 {
		arraymas[ind+2]=false;
		$('input[name=name]').css({'border':'1px solid #FB5352'});
	 }
	 else
	 {
		arraymas[ind+2]=true;
		$('input[name=name]').css({'border':'1px solid #116047'});
	 }

	for(var i=0; i<arraymas.length; i++) {
		if (!arraymas[i]) 
		{
			$('.'+i+'').focus();
			return false;
			};
		}; 
}

$(function(){
			
			$('select.headCh').selectmenu();
				$('select.headCh').change(function(){
					var link=$(this).attr('value');
					var text=$(this).find('option:selected').text();
					window.location.href=link+'#'+text;
				});
				
				$('select.leftCh').selectmenu();
				$('select.leftCh').change(function(){
					var link=$(this).attr('value');
					var text='curr';
					window.location.href=link+'#'+text;
				});
		});		
		
		//a custom format option callback
		var addressFormatting = function(text){
			var newText = text;
			//array of find replaces
			var findreps = [
				{find:/^([^\-]+) \- /g, rep: '<span class="ui-selectmenu-item-header">$1</span>'},
				{find:/([^\|><]+) \| /g, rep: '<span class="ui-selectmenu-item-content">$1</span>'},
				{find:/([^\|><\(\)]+) (\()/g, rep: '<span class="ui-selectmenu-item-content">$1</span>$2'},
				{find:/([^\|><\(\)]+)$/g, rep: '<span class="ui-selectmenu-item-content">$1</span>'},
				{find:/(\([^\|><]+\))$/g, rep: '<span class="ui-selectmenu-item-footer">$1</span>'}
			];
			
			for(var i in findreps){
				newText = newText.replace(findreps[i].find, findreps[i].rep);
			}
			return newText;
		}		