function write_mt(x, y, z){ document.write('<a href="mailto:', y, '@', x, '">', z, '</a>'); }
function write_ml(x, y){ document.write('<a href="mailto:',y,'@',x,'">',y,'@',x,'</a>'); }

function isEmail(string) {
    return string.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,6}$/) != -1;
}

function load(){
	document.getElementById('vname').style.display = "inline";
	document.getElementById('vmsg').style.display = "inline";
	document.getElementById('vmail').style.display = "inline";
}	


function myvalid(target, type)
{
	if (type == 1){
		if (target.length>1)
			document.getElementById('vname').style.display = "none";
		else
			document.getElementById('vname').style.display = "inline";
	}
	if (type == 2){
	
	if (target.length>5)
			document.getElementById('vmsg').style.display = "none";
		else
			document.getElementById('vmsg').style.display = "inline";
	}
	if (type == 3){
	
	if (isEmail(target))
			document.getElementById('vmail').style.display = "none";
		else
			document.getElementById('vmail').style.display = "inline";
	}
}

var formSnippet = '<form action = "/" method = "post" class = "b-form-thanks"><h1>Регистрация <strong>прошла успешно</strong></h1><div><input type = "submit" value = "Закрыть окно" class = "close image" /></div></form>';

/*
    Popup
*/
function showPopup(text) {
	load();
    var arr = ___getPageSize();
        $('.overlay').css('height', arr[1]);

    $('#senk').hide();
	$('#ask-form').show();
    $('.b-form .success').html('<span>•</span> &mdash; Обязательные поля заполнены');
    $('.b-form .controls').css('visibility', 'visible');
    $('.b-form').show();
    cleanupForm();
    validateForm();
    $('.overlay').css('display', 'block');
   // $('.popup').animate({opacity:1}, 1000);
	$('.popup').show();
	if (text) document.getElementById('msg').value=text;
}

function closePopup() {
   /* $('.popup').animate({opacity:0}, 300, function() {
        $('.overlay').css('display', 'none');
        $('.b-form-thanks').remove();
    });
	*/
	$('.overlay').css('display', 'none');
	$('.popup').hide();
	 $('.overlay').hide();
}

/*
    Validation :)
*/


function isValidField(field) {
    isValid = false;
    
    var parent = $(field).parents('p:first()');
    
    if($(parent).hasClass('required')) {
        isValid = field.value.length > 2;
    }
    if($(parent).hasClass('name')) {
        isValid = /^([а-я]|[a-z]| |.){2,}$/.test(field.value);
        //isValid = field.value.search(/^([а-я]|[a-z])*?$/i);
    }
    if($(parent).hasClass('email')) {
        isValid = isEmail(field.value);
    } 
    if($(parent).hasClass('phone')) {
        isValid = /^\+?\d{6,}$/.test(field.value.replace(/ /g, ''));
    }
    if($(parent).hasClass('date')) {
        isValid = /^\d{1,2}\.\d{1,2}\.\d{4}$/.test(field.value);
    }
    if($(parent).hasClass('message')) {
        isValid = field.value.replace(/ /g, '').length >= 10;
    } 
    
    if(!isValid) {
        $(parent).addClass('invalid');
        $(parent).children('.status').show();
    } else {
        $(parent).removeClass('invalid');
        $(parent).children('.status').hide();
    }
    
    return isValid;
}

function validateForm() {
    allOk = true;
    $('.b-form input[type=text], .b-form textarea').each(function() {
         if($(this).parents('p:first()').hasClass('required') && !isValidField(this)) {
             allOk = false;
         }
    });
    
    if(allOk) {
        $('.failed').hide();
        $('.success').show();
        //$('.b-form input[type=submit]').removeAttr('disabled');
        $('.b-form input[type=submit]').removeClass('disabled');
    } else {
        $('.success').hide();
        $('.failed').show();
        //$('.b-form input[type=submit]').attr('disabled', 'disabled');
        $('.b-form input[type=submit]').addClass('disabled');
    }
    
};

function cleanupForm() {
    $('.b-form').trigger('reset');
    validateForm();
}

$(document).ready(function() {
    
    $('.l-wrap').addClass('js');
    
    $('.signup').click(function() {
        showPopup();
        return false;
    });
    
    $('.close').click(function() {
        closePopup();
        return false;
    });
    
    $('.b-form').submit(function() {
        $('.controls').css('visibility', 'hidden');
        $('.success').html('Обработка данных...');
        var user = $('#username').attr('value');
        var email = $('#email').attr('value');
        var msg = $('#msg').attr('value');

        if (email == '' || user == '' || msg == '' || msg.length<5 || user.length<5 || !isEmail(email)) return false;


        $.post('/mail.php', {username:$('#username').attr('value'), signupEmail:$('#email').attr('value'), signupPhone:$('#phone').attr('value'), msg:$('#msg').attr('value') }, function(data) {
           // closePopup();
	$('#ask-form').hide();
	$('#senk').show();
            if(data.indexOf('success') != -1) {
                $('.b-form').slideUp('fast');
                /*$('.b-form-thanks').slideDown('fast');*/
                $(formSnippet).insertAfter('.b-form').slideDown('fast');
                $('.b-form-thanks input[type=submit]').click(function() {
                    closePopup();
                    return false;
                });
            }
        });
        return false;
    });
    
    $('.b-form input[type=submit]').click(function() {
        if($(this).hasClass('disabled')) {
            return false;
        }
    });
    
    $('.b-form input[type=reset]').click(function() {
        cleanupForm();
        return false;
    });
    
    $('.b-form input[type=text], .b-form textarea').bind('blur keyup focus', function() {
        validateForm();
    });
    
    $(document).bind('keyup', function(e) {
        switch(e.keyCode) {
            case 27: closePopup(); break;
        }
    });
    
});

function ___getPageSize() {
    var xScroll, yScroll;
    if (window.innerHeight && window.scrollMaxY) {    
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    var windowWidth, windowHeight;
    if (self.innerHeight) {    // all except Explorer
        if(document.documentElement.clientWidth){
            windowWidth = document.documentElement.clientWidth; 
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }    
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else { 
        pageHeight = yScroll;
    }
    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){    
        pageWidth = xScroll;        
    } else {
        pageWidth = windowWidth;
    }
    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
    return arrayPageSize;
};
