img = new Array();

img[0] = new Image();

var img_count = 1;
var url = '';
var current_block_name = '#block1';
var fontsize = 12;
var run_slide = false;

$(function() {
    $( "#dialog:ui-dialog" ).dialog( "destroy" );
    slideShow();
    
    var name = $( "#name" ),
        phone = $( "#phone" ),
        allFields = $( [] ).add( name ).add( phone ),
        tips = $( ".validateTips" );    
    
    
    $('#bg-change').click(function() {
        url = 'url(' + img[count].src + ')';
        $('#text-span').text(img[count].src);
        $('#slider').css('background', url);
        count++;
        if (count > 7) { count = 0; } 
    } );
    
    
    $('#previos-image').click(function() {
        changeImage(false, true);
        run_slide = false;      
    }
    );
    
    
    $('#next-image').click(function(){
        changeImage(true, true);
        run_slide = false;
    });
    
    function changeImage(next_img) {
        if (next_img) {
            img_count == 5 ? img_count = 1 : img_count++;
        }
        else {
            img_count == 1 ? img_count = 5 : img_count--;
        }
        $(current_block_name).slideUp('slow');
        current_block_name = '#block' + img_count;
        $(current_block_name).slideDown('slow');
    }
    
    function slideShow() {
        if (run_slide) { 
            changeImage(true);
        }
        run_slide = true;
        setTimeout(slideShow, 5000);
    }
    
    function updateTips( t ) {
			tips
				.text(t)
				.addClass("ui-state-highlight");
			setTimeout(function() {
				tips.removeClass("ui-state-highlight", 1500);
			}, 500 );
    }    
    
    function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Длина " + n + " не может быть меньше " +
					min + " символов и не больше " + max + " символов." );
				return false;
			} else {
				return true;
			}
    }   
    
    function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}     
   
    $('#claim-form').dialog({ 
        autoOpen: false,
        modal: true,
        title: "Заявка на звонок",
        width: 450,
        height: 330,
        show: "slide",
        hide: "explode",
        buttons: {
            "Отправить": function() {
                var bValid = true;
                bValid = bValid && checkLength( name, "имени", 3, 16 );
                bValid = bValid && checkLength( phone, "телефона", 7, 20 );
                bValid = bValid && checkRegexp( name, /^([а-яА-Я ])+$/i, "Имя должно состоять только из букв а-я и/или А-Я" );
                bValid = bValid && checkRegexp( phone, /^[0-9+-]/, "В поле телефон используйте только цифры" );
                if (bValid) {
                    $(this).dialog("close");
                    sendMessage();                    
                }
            },
            "Отмена": function() {
                $(this).dialog("close");
            }            
        }        
    });
    
    function sendMessage()
    {
        var data = 'type=sendCallClaim';
        $('#claim-form').find('input, textarea').each(function(){
            var value = $(this).val();
            var type = $(this).attr('name');
            data += '&' + type + '=' + value;
        });        
        $.ajax({
            url: 'ajax.php',
            type: 'post',
            data: data,
            success: function (data)
            {
                if (data.length == 0)
                {
                    $('#claim-form').dialog('close').text('Сообщение отправлено').dialog({
                        resizable: false,
                        modal: true,
                        title: 'Сообщение',
                        width : 250,
                        height : 150,
                        buttons: {
                            Ok:function (){
                                $(this).dialog('close');
                            }
                        }
                    });
                }
                else
                    error(data);
            }
        });
    } // end function

function error(message)
{
    if ($('#error_message').length == 0)
        $('body').append('<div id="error_message">'+message+'</div>');
    else
        $('#error_message').html(message);

    $('#error_message').dialog({
        resizable: false,
        title: 'Отправка заявки',
        modal: true,
        buttons: {
            Ок: function ()
            {
                $( this ).dialog( "close" );
            }
        }
    });

    return false;
}
    
    $('#claim').click(function() {
        $('#claim-form').dialog("open");
    });
    
}
);
