var timeout         = 500;
var closetimer		= 0;
var ddmenuitem      = 0;
var randCK      = 0;
var msg_form;

function getRandomInt(min, max)
{
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


$.validator.setDefaults({
    highlight: function(input) {
        $(input).addClass("ui-state-error");
    },
    unhighlight: function(input) {
        $(input).removeClass("ui-state-error");
    }
});
$.validator.addMethod(
    "captcha",
    function(value, element) {
        if (value.length < 5 || value.length > 5) {
            $.validator.messages.captcha = "Подсказка: на рисунке 5 символов";
            return false;
        } else {
            var myCaptcha = $.ajax({ type: "GET", url: "/captcha/validate/?value="+value+"&code="+$("#id_captcha_0").val(), async: false }).responseText;
            $.validator.messages.captcha = "Неверный код подтверждения.";
            return myCaptcha == "true"
//                $("#id_captcha_0").val(myCaptcha)
//                $("#id_captcha_img").attr("src", "/captcha/"+myCaptcha+".png?"+getRandomInt(1000, 100000))
        }
//        if (valid_captcha)
        return true;
    },
    "Неверный код подтверждения"
);

function jsddm_open(){
    jsddm_canceltimer();
	jsddm_close();
	ddmenuitem = $(".submenu", this);
    ddmenuitem.show()
}

function jsddm_close(){
    if(ddmenuitem)
        ddmenuitem.hide();
}

function jsddm_timer(){
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer(){
    if(closetimer){
        window.clearTimeout(closetimer);
		closetimer = null;
    }
}

$(document).ready(function(){

    $('#top-menu > li').live({
        mouseover: jsddm_open,
        mouseout:  jsddm_timer
    });
//    $('#top-menu > li').bind('mouseout',  jsddm_timer);

	$(".show-hide-link").click(function(){
		showHideText($(this));
		return false;
	});

    var validate_params = {
        errorPlacement: function(error, element) {
            $(".errorlist").remove();
            error.appendTo( element.parent("td").next("td") );
        },
        rules: {
//            "sender": {required: true},
            "email": {required:true, email: true},
            "content": {required: true, minlength: 5}
//            "captcha_1": {
//                required: true,
//                captcha: true
//            }
        },

        messages:{
//            "sender": {required: "Введите, пожалуйста, имя и фамилию"},
            "email": {
                required: "Адрес электронной почты",
                email: "Некорректный электронной почты"
            },
            "content": {required: "Введите, вопрос или сообщение.", minlength: "Слишком короткий текст"}
//            "captcha_1": {
//                required: "Пожалуйста, введите код подтверждения"
//            }
        }
    }

    msg_form = $("#message-form").validate(validate_params);

    $("#message-form-button").button().live({
        click: function(){
            return msg_form.form()
        }
    })

    $("#btn-search").live({
        click: function(){
            $("#search_form").submit();
        }
    });

    $('#message-button').live({
        click: function(){
            var ajax_form;
            $.get('/message', function(data){
                $("#dialog").html(data);
                $emtDialog.dialog({
                    buttons:{
                        'Отправить': function(){

                            if(ajax_form.form()){
                                $("#overlay").show();
                                $('#message-form-ajax').ajaxSubmit({
                                    success:function(data) {
                                        $("#overlay").hide();
                                        $emtDialog.html(data);
                                    },
                                    error:function() {
                                        $("#overlay").hide()
                                        $emtDialog.dialog({buttons:{
                                            'Закрыть': function(){
                                                $emtDialog.dialog('close');
                                            }
                                        }});
                                        $emtDialog.html('При отправке произошла ошибка. Пожалуйста, повторите попытку позднее.');
                                    }
                                });
                            }
                        },
                        'Закрыть': function(){
                            $("#overlay").hide();
                            $emtDialog.dialog('close');
                        }
                    },
                    width:700,
                    height:460
                });
                $emtDialog.dialog('open');
                ajax_form = $('#message-form-ajax').validate(validate_params);
            });
            return false;

        }
    });

    $emtDialog = $("#dialog").dialog({
        autoOpen: false,
        resizable: true,
        modal: true,
        width:300,
        height:150,
        close: function() {
            $("#dialog").dialog({height:150, width:300, buttons:{}})
            $("#dialog").html('');
        }
    });

    $progressDialog = $("#dialog-progress");

    $("#add2bookmarks").live({
        click: function(){
            var url = window.document.location;
            var title = window.document.title;
            var b = getBrowserInfo();
            if (b.type == 'IE' && 7 > b.version && b.version >= 4) window.external.AddFavorite(url,title);
            else if (b.type == 'Opera') {
                $(this).attr("href", url);
                $(this).attr("rel", "sidebar");
                $(this).attr("title", url+','+title);
                return true;
            }
            else if (b.type == "Netscape") window.sidebar.addPanel(title,url,"");
            else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки.");
            return false;
        }
    });

    $(".hideOpenedText").live({
        click: function(){
            return showHideText($(this));
        }
    })

});

document.onclick = jsddm_close;

function searchSubmit() {
	$('#search_form').submit();
}



function refreshCaptcha()
{
	randCK = Math.floor( Math.random()*10000000)
	$("#captchaIMG").attr('src', '/supercap/'+ randCK +'.jpg');
	$("#captchaCK").val(randCK);
}

function getBrowserInfo() {
	 var t,v = undefined;
	 if (window.opera) t = 'Opera';
	 else if (document.all) {
	  t = 'IE';
	  var nv = navigator.appVersion;
	  var s = nv.indexOf('MSIE')+5;
	  v = nv.substring(s,s+1);
	 }
	 else if (navigator.appName) t = 'Netscape';
	 return {type:t,version:v};
}
	 

function showHideText(element){
	var id_text = element.attr('id');
	var showElement = $('#'+id_text+'-content');
	if (showElement.css('display') == 'none'){
		element.attr('id', id_text+'-link');
		var a = $('<a></a>')
        a.text("скрыть");
        a.attr("href", "#")
        a.attr("id", id_text)
        a.addClass("hideOpenedText")
        a.insertAfter(element);
		element.hide();
		showElement.show();
	} else {
		$("#"+id_text+'-link').attr('id', id_text).show();
		element.remove();
		showElement.hide();
	}
	return false;
}
