/**
 *  Включение/выключение списка для формы поиска по
 *  регионам
 */

var change_region = function(id){
  // список регионов
  var elt = document.getElementById('select_region');
//  var elt = $('#select_region');
  elt.disabled = true;

  if (id>0) {

    change_city(id, 0);
	// если есть options, то удаляем
    for(i=elt.options.length-1;i>0;i--) elt.remove(i);

    for (i in fo[id])
    {
	 if ((fo[id][i]+'').indexOf('return') == -1){
        var optn = document.createElement('option');
        optn.text = fo[id][i];
        optn.value = i;
        elt.options.add(optn);
	 }
    }
    elt.disabled = false;
    $('tr.tr_region').show();
	elt.style.display = 'inline';
  } else if (id == 0){
    $('tr.tr_region').hide();
    $('tr.tr_city').hide();
    $('#select_region option:first').attr('selected','yes');
    $('#select_city option:first').attr('selected','yes');
  }

}
/* меняем город */
var change_city = function(fo, region){
  var elt = document.getElementById('select_city');
  elt.disabled = true;

  if (region > 0) {
    for(i=elt.options.length-1;i>0;i--) elt.remove(i);

    for (i in regions[fo][region])
    {
     if ((regions[fo][region][i]+'').indexOf('return') == -1){
        var optn = document.createElement('option');
        optn.text = regions[fo][region][i];
        optn.value = i;
        elt.options.add(optn);
      }
    }
    elt.disabled = false;
    $('tr.tr_city').show();
  } else if (region == 0){
    $('tr.tr_city').hide();
    $('#select_city option:first').attr('selected','yes');
  }

}


var change_region2 = function(id){
  // список регионов
  var elt = document.getElementById('select_region2');
  //var elt = $('#select_region');
  elt.disabled = true;

  if (id>0) {

    change_city2(id, 0);
	// если есть options, то удаляем
    for(i=elt.options.length-1;i>0;i--) elt.remove(i);

    for (i in fo[id])
    {
	 if ((fo[id][i]+'').indexOf('return') == -1){
        var optn = document.createElement('option');
        optn.text = fo[id][i];
        optn.value = i;
        elt.options.add(optn);
	 }
    }
    elt.disabled = false;
    $('tr.tr_region2').show();
	elt.style.display = 'inline';
  } else if (id == 0){
    $('tr.tr_region2').hide();
    $('tr.tr_city2').hide();
    $('#select_region2 option:first').attr('selected','yes');
    $('#select_city2 option:first').attr('selected','yes');
  }

}
/* меняем город */
var change_city2 = function(fo, region){
  var elt = document.getElementById('select_city2');
  elt.disabled = true;

  if (region > 0) {
    for(i=elt.options.length-1;i>0;i--) elt.remove(i);

    for (i in regions[fo][region])
    {
     if ((regions[fo][region][i]+'').indexOf('return') == -1){
        var optn = document.createElement('option');
        optn.text = regions[fo][region][i];
        optn.value = i;
        elt.options.add(optn);
      }
    }
    elt.disabled = false;
    $('tr.tr_city2').show();
  } else if (region == 0){
    $('tr.tr_city2').hide();
    $('#select_city2 option:first').attr('selected','yes');
  }

}


/**
 *  для формы регистрации нового пользователя
 */

var posting;
var warnText;
function next_step(id1,id2) {
	if(id1 == 'step1'){
		posting = 1;
		warnText = '';
                /*
                 *if ($('input#step').val() == '0'){
                 *    $('input#step').val(1);
                 *    posting = 0;
                 *    warnText += 'Email уже существует.<br>';
                 *}
                 */

	/*	if(!$('#agree_box').attr('checked')) {
		*	posting = 0;
         *               $('input#step').val(0);
		*	warnText += 'Необходимо согласиться с условиями!<br>';
		}*/
		var re = /(\w+@[a-zA-Z_0-9-]+?\.[a-zA-Z]{2,6})/;
		var str = $('#Email').val();
		if(!re.test(str)){
			posting = 0;
                        $('input#step').val(0);
			warnText += 'Необходимо ввести корректный электронный адрес!<br>';
		}
		if($('#pass1').val().length < 6){
			posting = 0;
                        $('input#step').val(0);
			warnText += 'Пароль должен быть не менее 6-ти символов!<br>';
		}
		if($('#pass1').val() != $('#pass2').val()){
			posting = 0;
                        $('input#step').val(0);
			warnText += 'Пароли не совпадают!<br>';
		}
		if($('#LastName').val() == ''){
			posting = 0;
                        $('input#step').val(0);
			warnText += 'Необходимо ввести фамилию!<br>';
		}
		if($('#ForumName').val() == ''){
			posting = 0;
                        $('input#step').val(0);
			warnText += 'Необходимо ввести имя!<br>';
		}

                $.get(
                    'http://www.metalloprokat.ru/netcat/modules/default/get_companies_list.php',
                    {e: $('#Email').val()},
                    function (data){
                    //alert(data);
                       if (data == 'yes') {
                            posting = 0;
                            warnText += "Пользователь с таким e-mail адресом уже зарегистрирован!<br />";
                            if(!posting){
                                    $('#javaWarn').html(warnText);
                                    $('#javaWarn').show();
                                    window.scrollTo(0,0);
                                    return false;
                            }
                       } else {
                            if(!posting){
                                    $('#javaWarn').html(warnText);
                                    $('#javaWarn').show();
                                    window.scrollTo(0,0);
                                    return false;
                            }
                           $('#'+id1).hide();
                           $('#javaWarn').hide();
                           $('#'+id2).show();
                       }
                    }
                );
	}
}

/**
 *  перемещение элементов select
 */

moveOption = function(src, dst) {
        var fromObj   	   = document.getElementById(src);
        var toObj     	   = document.getElementById(dst);
        var newOption 	   = null;
        var selectedOption = null;

        while (true) {
                try {
                        selectedOption = fromObj.options[fromObj.selectedIndex];
                        newOption = new Option(selectedOption.text, selectedOption.value, false, false);
                        toObj.options[toObj.options.length] = newOption;
                        fromObj.options[fromObj.selectedIndex] = null;
                } catch (e) { break; }
        }
        $("#left_cat").dblclick(function(){
           moveOption("left_cat", "right_cat");

    	});
        $("#right_cat").dblclick(function(){
           moveOption("right_cat", "left_cat");
    	});
		 $("#right_cat option").each(function(el) {
                $(this).attr("selected", "selected");
            });
           // alert("in");
        return false;
}

/**
 *  Установка cookie
 */
function setCookie(name, value, path, domain, expires, secure){

 var today = new Date();
 today.setTime(today.getTime());

 /**
  * Для установки времени в часах удалить * 24,
  * для минут - удалить * 60 * 24
  */
 if(expires){
  //expires = expires * 1000 * 60 * 60 * 24;
  expires = expires * 1000 * 60 * 60;
 }
 var expires_date = new Date( today.getTime() + (expires) );

 document.cookie = name + "=" +escape( value ) +
  ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
  ( ( path ) ? ";path=" + path : "" ) +
  ( ( domain ) ? ";domain=" + domain : "" ) +
  ( ( secure ) ? ";secure" : "" );
}


/**
 *
 * @access public
 * @return void
 **/
function changeFldPrice(fName, short){
 /*Прайс-листы - модерирование пользователем*/
	//$("#Pts4All").change(function(){
	//	alert("in");
			$("input:checked").each(function() {
				name = $(this).attr("name");
				name=name.replace("del","");
				name=name.replace("]","\\]");

			//	selopt = $('select[id=datas'+name+'[Pts]]');

				$("#datas\\"+name+"\\["+short+"\\]").val($("#"+fName).val())  ;
				//alert(name);
			});
	//});
}
/**
 *
 * @access public
 * @return void
 **/
function ClearCheckB(value){

			$("input[type='checkbox']").each(function(){
				if ($(this).attr("name").substr(0,4)!="delA") {
					$(this).attr('checked',value);
				}
			});

}


$(function(){
if ($(".scrollable") instanceof jQuery) {
	$(".scrollable").scrollable({ size:1,circular: false, clickable: false })

}


$(".css-tabs").tabs(".css-panes > div");
//	$(".css-tabs:first").tabs(".css-panes:first > div");
	$('#compMenu').click(function(){
					//		if (!$('#compMenuAll').show()) {
								$('#compMenuAll').toggle();
					//		}
					//	else
						//		$('#compMenuAll').show();

		});
	$(".emailSend").click(function (event){

			var url = $(this).attr("href");
				var windowName = "popUp";
										//var windowSize = windowSizeArray[ $(this).attr(\"rel\") ];

			    window.open(url, windowName, "width=590,height=600");

				event.preventDefault();

		});


    $('input#top_search_hint').focus(function(){
        if ($('input#top_search_hint').val() == 'Введите название товара или компании'){
            $('input#top_search_hint').val('');
            $('input#top_search_hint').attr('class','top_search_hintIn');
        }
    });
    $('input#top_search_hint').blur(function(){
        if ($('input#top_search_hint').val() == ''){
            $('input#top_search_hint').val('Введите название товара или компании');
            $('input#top_search_hint').attr('class','top_search_hint');
        }
    });

    // если выбрана компания, то не показывать форму
    $('#company_select').change(function(){
            //console.log($(this).val());
            if($(this).val() != 0)
                    $('#inside_step2').hide();
            else
                    $('#inside_step2').show();
    });

    // показывать пункты характеристики компании только для продавцов
    $('#sell_checkbox').click(function(){
            //console.log($(this).attr('checked'));
            $('#charac_header, #charac_body').toggle();
    });

    // показывать пункты характеристики компании только для продавцов
    $('#sell_checkbox_comp').click(function(){
            //console.log($(this).attr('checked'));
            $('#charac_header_comp, #charac_body_comp').toggle();
    });

    // отменить регистрацию
    $('input.back_button').click(function(){
            window.location.href = '/';
    });

    /**
     *  Форма авторизации сверху
     */
    $('input#login_email').focus(function(){
            if ( $(this).val() == 'e-mail' )
                    $(this).val('');
    });
    $('input#login_email').blur(function(){
            if ( $(this).val() == '' )
                    $(this).val('e-mail');
    });
    $('input#login_pass').focus(function(){
            if ( $(this).val() == 'Пароль' )
                    $(this).val('');
    });
    $('input#login_pass').blur(function(){
            if ( $(this).val() == '' )
                    $(this).val('Пароль');
    });


    /**
     *  Региональные предпочтения пользователей
     *  Настройка в профайле
     */
    //$("input[name='fo']").click(function(){
    $("input.fo_input").click(function(){
            //alert($(this).parent().parent().attr('class'));
            var checked = $(this).attr('checked');
            $("input[type='checkbox']",$(this).parent().parent()).attr('checked', checked);
    });

    $(".multi").click(function(){
            $("#right_cat option").each(function(el) {
                $(this).attr("selected", "selected");
            });
    });
    /*$("#left_cat option").click(function() {
                            alert(1);
        					});*/
    $("#left_cat").dblclick(function(){
           moveOption("left_cat", "right_cat");
    });
    $("#right_cat").dblclick(function(){
           moveOption("right_cat", "left_cat");
    });

    /* Профиль компании */
    $('table#company_table tr:nth-child(even)').addClass('even');
    $('table.user_list tr:nth-child(even)').addClass('even');
    /*$('table.search_list tr:nth-child(even)').addClass('active');*/
    $('table#company_details tr:nth-child(even)').addClass('even');

    /* Актульные/архивные заявки */
    $('a#show_active').click(function(){
            $('input#arch').val(0);
            $(this).addClass('bold_simple');
            $('a#show_archive').removeClass('bold_simple');
            return false;
    });
    $('a#show_archive').click(function(){
            $('input#arch').val(1);
            $(this).addClass('bold_simple');
            $('a#show_active').removeClass('bold_simple');
            return false;
    });


});

