$(document).ready(function(){
    $('textarea[limit]').limit();

    testFileCount(4); 
    testFotoCount(10);
    $('.j-price-target').hide();
    $('.j-descr-target').hide();

            $('.j-price').toggle(
                     function(event){
                         $(this).parents('dl').next('.j-price-target').show();
                         $(this).css('color', '#419639');
                         $(this).css('borderColor', '#419639');
                         },
                     function(event){
                         $(this).parents('dl').next('.j-price-target').hide();
                         $(this).css('color', '#396EA9');
                         $(this).css('borderColor', '#396EA9');
                         }
           );
           $('.j-descr').toggle(
                     function(event){
                         $(this).parents('dl').next('dl').next('.j-descr-target').show();
                         $(this).css('color', '#419639');
                         $(this).css('borderColor', '#419639');
                         },
                     function(event){
                         $(this).parents('dl').next('dl').next('.j-descr-target').hide();
                         $(this).css('color', '#396EA9');
                         $(this).css('borderColor', '#396EA9');
                         }
           );
     if($("#r71").val() && $("#r71").val()!='0')
    {
        $("#nedvig_price_link").click(); 
    }
    if($("#nedvig_description").val())
    {
        $("#nedvig_descr_link").click(); 
    } 
    if($("#oborud_price_input").val() && $("#oborud_price_input").val()!='0')
    {
        $("#oborud_price_link").click(); 
    }
    if($("#oborud_descr_input").val())
    {
        $("#oborud_descr_link").click(); 
    }
    if($("#nomat_price_input").val() && $("#nomat_price_input").val()!='0')
    {
        $("#nomat_price_link").click(); 
    }
    if($("#nomat_descr_input").val())
    {
        $("#nomat_descr_link").click(); 
    }  
    

                                                                                                                 




	$('#selCatMain').click(function(){
		$.post("/xajax/xajax.php", {
			func: "getRbCategory",
			id_main_category: this.value
		}, function(data){
            $('#selCatLabel').hide();
            $('#selCat').show();
			$('#selCat').html(data);
		}, 'html');
		
	});
	$('#logo_container a.black').live('click', function(){
		deleteFile(this.title);
		$('#logo_container').html('');
		return false;
	});
    $("#logo_open").click(function(){
       $("#logo_input").show();
       $("#logo_error_ul").hide();
       $("#logo_status_ul").hide();
       return false;
    });
    $("#logo_close").click(function(){
       $("#logo_input").hide();
       $("#logo_error_ul").hide();
       $("#logo_status_ul").hide();
       return false;
    });	

	$.mask.masks.integer = {
		mask: '9',
		type: 'repeat'
	};
	
	$.mask.masks.text1000 = {
		mask: '*',
		type: 'repeat',
		maxLength: 4
	};
	$('input:text').setMask();
	$('textarea').setMask();
	
    //Фото товаразаливалка
    if ($('#show_input').length > 0) {
        var logo_upload = new AjaxUpload('show_input', {
            action: '/xajax/xajax.php',
            autoSubmit: true,
            data: {
                func: 'uploadUserFile',
                responseType: 'xml',
                span: 'span',
                width: 320,
                height: 240,
                watermark: 1
            },
            onChange: function(file, ext){
                if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
                    return false;
                }
            },
            onSubmit: function(file, ext){
                showWaitWindow();
            },
            onComplete: function(file, response){
                closeWaitWindow();
                $("#logo_input").hide();
                if ($('error', response).text()) {
                    $("#logo_error").html($('error', response).text());
                    $("#logo_error_ul").show();
                } else {
                    var fname = $('filename', response).text();
                    $("#div_submit").hide();
                    $("#logo_input").hide();
                    $("#logo_container").html('<img src="/showimg.php?img=temp/' + fname + '&w=320&h=240" width="320" />' +
                    '<input type="hidden" name="logo" value="' +
                    fname +
                        '"/>');
                    $("#logo_status").html('Фотография загружена. Продолжите заполнение формы.');
                    $("#logo_status_ul").show();
                }
            }
        });
    }	

	$('#show_input_foto').click(function(){
		$('#input_foto').show();
        closeFotoStatusWindows();
		return false;
	});
    $('#show_input_foto2').click(function(){
        $('#input_foto').hide();
        closeFotoStatusWindows();
        return false;
    });
    $('#input_foto').hide();
    
    $('#addfile_open').click(function(){
        $('#addfile_input').show();
        $("#file_error_id_ul").hide();         
        $("#file_status_id_ul").hide();         
        $("#file_input_text").html('');
        $("#file_input").val('');
        $("#file_desc").val('');
        return false;
    });
    $('#addfile_close').click(function(){
        $('#addfile_input').hide();
        return false;
    });    
    $('#addfile_input').hide();
    $('#obrabotka_zaprosa').hide();
	$('div.delete_file a.black').live('click', function(){
        $("#file_error_id_ul").hide();         
        $("#file_status_id_ul").hide();         
        closeFotoStatusWindows();
		var str = this.title;
		deleteFile(str);
		var str2 = str.replace(/\./, "\\.");
		$('#fc_' + str2).after('<ul class="message status foto-del"><li>Фотография удалена</li></ul>');
        $('#fc_' + str2).remove();
        testFotoCount(10);
		return false;
	});
	//Фотозаливалка
	if ($("#rb_foto").length > 0) {
		var foto_uploader = new AjaxUpload('rb_foto', {
			action: '/xajax/xajax.php',
			autoSubmit: true,
			data: {
				func: 'uploadUserFile',
                span: 'span',
				width: 320,
				height: 240,
                ext: 'jpg|png|jpeg|gif',
                watermark: 1
			},
			onChange: function(file, ext){
                closeFotoStatusWindows();
				if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
                    $("ul.foto-error").html('<li>Неверный тип файла</li>');
                    $(".foto-error").show();
					return false;
				}
			},
			onSubmit: function(file, ext){
                if(!testFotoCount(10))
                {
                    $("ul.foto-error").html('<li>Слишком много файлов</li>');
                    $(".foto-error").show();
                    return false;
                }

                showWaitWindow();
			},
			onComplete: function(file, response){
                closeWaitWindow();
				if ($('error', response).text()) {
					$("ul.foto-error").html('<li>' + $('error', response).text() + '</li>');
                    $(".foto-error").show();
					$("div.loading").hide();
				} else {
					var fname = $('filename', response).text();
					$("#list_foto").append('<div id="fc_' + fname + '" class="fransh-foto foto-tovar upl_foto_item">' +
					'<img src="/showimg.php?img=temp/' +
					fname +
					'&w=140&h=105" />' +
					'' +
                    '<input type="text" name="foto_opis[]" id="eaddress" class="gray89" value="Введите описание файла" onfocus="if(this.value==\'Введите описание файла\') this.value=\'\'" onblur="if(this.value==\'\') this.value=\'Введите описание файла\'"/>' +                    
					'<div class="delete_file">' +
					'<input type="hidden" name="foto[]" value="' +
					fname +
					'" style="display: none;"/><br/>' +
					'<a href="" title="' +
					fname +
					'" class="black">Удалить</a>' +
                    '</div>');
				}
				$("#foto_stat").show();
				$('#input_foto').hide();
                testFotoCount(10);
			}
		});
	}
	//********************** TOVAR **********************
	$('#show_input_tovar').click(function(){
		$('#input_tovar').slideToggle();
		return false;
	});
	$('div.delete_file a.black').live('click', function(){
		var str = this.title;
		deleteFile(str);
		
		var str2 = str.replace(/\./, "\\.");
		$('#fc_' + str2).remove();
		return false;
	});
	//Фото товаразаливалка
	if ($("#rb_tovar").length > 0) {
		var foto_uploader = new AjaxUpload('rb_tovar', {
			action: '/xajax/xajax.php',
			autoSubmit: true,
			data: {
				func: 'uploadUserFile',
                responseType: 'xml',
				width: 800,
				height: 600
			},
			onChange: function(file, ext){
				if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
					return false;
				}
			},
			onSubmit: function(file, ext){
				$("div.loading").show();
			},
			onComplete: function(file, response){
				if ($('error', response).text()) {
					$("#tovar_stat").html('<div class="red_block s11">' + $('error', response).text() + '</div>');
					$("div.loading").hide();
				} else {
					var fname = $('filename', response).text();
					$("#list_tovar").append('<span id="fc_' + fname + '">' +
					'<div class="padd_bot10 f-left">' +
					'<img src="/showimg.php?img=/temp/' +
					fname +
					'&w=160&h=160" width="160"/>' +
					'</div>' +
					'<div class="delete_file">' +
					'<input type="text" name="tovar_opis[]" id="eaddress" class="gray89" value="Введите описание файла" onfocus="if(this.value==\'Введите описание файла\') this.value=\'\'" onblur="if(this.value==\'\') this.value=\'Введите описание файла\'"/>' +
					'<input type="hidden" name="tovar[]" value="' +
					fname +
					'" style="display: none;"/><br/>' +
					'<a href="" title="' +
					fname +
					'" class="black">Удалить файл</a>' +
					'</div>' +
					'<div class="clear"></div>' +
					'<div class="line2"></div>' +
					'<div class="padding_b20"></div></span>');
					$("#tovar_stat").html('<div class="green_block s11 lh14">Фотография загружена. Продолжите заполнение формы.</div>');
				}
				$("#tovar_stat").show();
				$('#input_tovar').slideToggle();
			}
		});
	}
	//*********************************** Video **********************************
	$('#list_video a.black').live('click', function(){
		deleteFile(this.title);
		$('#list_video').hide('');
		return false;
	});
	
	$('#show_input_video').click(function(){
		$('#input_video').show();
        $("ul.video-error").hide();
        $("ul.video-status").hide();
        $("#video_messages_dl").hide();
		return false;
	});
    $('#show_input_video2').click(function(){
        $('#input_video').hide();
        $("ul.video-error").hide();
        $("ul.video-status").hide();
        $("#video_messages_dl").hide();
        return false;
    });	
    $('#input_video').hide();
	//Видеозаливалка
	if ($("#rb_video").length > 0) {
		var uploader = new AjaxUpload('rb_video', {
			action: '/xajax/xajax.php',
			autoSubmit: true,
			data: {
				func: 'uploadUserFile',
                responseType: 'xml',
                span: 'span',
				maxsize: 10240,
                ext: 'flv'
			},
			onChange: function(file, ext){
                
				if (!(ext && /^(flv)$/.test(ext))) {
                    $("ul.video-error").html('<li>Неверный тип файла</li>');
                    $("ul.video-error").show();
                    $("#video_messages_dl").show();					
                    return false;
				}
			},
			onSubmit: function(file, ext){
                $("ul.video-error").hide();
                $("ul.video-status").hide();
                $("#video_messages_dl").hide();
                showWaitWindow();
				//	$("div.loading").show();
			},
			onComplete: function(file, response){
                closeWaitWindow();
				if ($('error', response).text()) {
					$("ul.video-error").html('<li>' + $('error', response).text() + '</li>');
                    $("ul.video-error").show();
                    $("#video_messages_dl").show();
					//$("div.loading").hide();
				} else {
				
					var fname = $('filename', response).text();
                    $("#videoFnameInput").removeAttr( 'value' );
                    $("#videoFnameInput").attr('value',fname);
                    fname = '/temp/'+fname;
                    var w=320;
                    var h=240;
                    var param = 'file=' + fname + '&w=' + w + '&h=' + h + '';

					$("#list_video").html('<div id="myContent_'+fname+'"></div><script type="text/javascript">'+
                            'var flashvars = false;'+
                            'var params = {'+
                            '  allowFullScreen: "true",'+
                            '  menu: "false",'+
                            '  quality: "high",'+
                            '  bgcolor: "#fffff",'+
                            '  flashvars: "'+param+'"'+
                            '};'+
                            'var attributes = {'+
                            '  id: "myDynamicContent",'+
                            '  name: "myDynamicContent"'+
                            '};'+
                            'swfobject.embedSWF("/player.swf", "myContent_'+fname+'", "'+w+'", "'+(h+60)+'", "9.0.0","/expressInstall.swf", flashvars, params, attributes);'+
                            '</script>');
					
					$("ul.video-status").html('<li>Видео загружено. Продолжите заполнение формы.</li>');
                    $("ul.video-status").show();
                    $("#video_messages_dl").show();
                    $("#list_video").show();
				}
                $('#input_video').hide();
                $("ul.video-error").hide();
                $("ul.video-status").hide();
                $("#video_messages_dl").hide();
			}
		});
	}
	  //файло
             var file_uploader = new AjaxUpload('file_input', {
            action: '/xajax/xajax_rb.php',
            autoSubmit: false,
            data: {
                func: 'rbUploadUserFile',
                span: 'span',
                id: $('#item_id').attr('value'),
                filetype: $("#file_type").val(),
                file_desc: $("#file_desc").val()
            },
            onChange: function(file, ext){
                $("#file_input_text").html(file);
            },
            onSubmit: function(file, ext){
                if (!(ext && /^(doc|pdf|txt|docx|xlsx|xlsx)$/.test(ext))) {
                    $("#file_error_id_ul").html('<li>Неверный тип файла</li>');
                    $("#file_error_id_ul").show();
                    $('#addfile_input').hide();
                    $("#div_submit").hide();                    
                    return false;
                }
                if(!testFileCount(4))
                {
                    return false;
                } 
                this.setData({
                    'func': 'rbUploadUserFile',
                    'span': 'span',                    
                    'id':$('#item_id').attr('value'),
                    'filetype':$("#file_type").val(),
                    'file_desc':$("#file_desc").val()
                });
                showWaitWindow();
            },
            onComplete: function(file, response){
                closeWaitWindow();
                if ($('error', response).text()) {
                    $("#file_error_id_ul").html('<li>' + $('error', response).text() + '</li>');
                    $("#file_error_id_ul").show();
                } else {
                    $("#uploaded_files").append(response);
                }
                $('#addfile_input').hide();
                $("#div_submit").hide();
                $("#file_desc").val('');
                testFileCount(4);
            }
        });
        $("#addfile_upload").click(function(){file_uploader.submit();});
    /*setFileUploader();
	$("#file_type").change(function(){
        setFileUploader();
        return false;
    });
    $("#file_desc").keyup(function(){
        setFileUploader();
        return false;
    }); */
    $('div.upl_file_item span.del-pole a').live('click', function(){
        var file = this.id;
        deleteUploadFile(file);
        return false;
    });	
	
});

function testFileCount(max_count)
{
    cur_count=$("div.upl_file_item").size();
    $("#files_count").val(cur_count);
    if(cur_count>=max_count)
    {
        $("div.nomax_file_upl").hide();
        $("#addfile_input").hide();
        $("em.max_file_upl").show();
        return false;
    }
    else
    {
        $("div.nomax_file_upl").show();
        $("em.max_file_upl").hide();
        $("#addfile_input").hide();
        return true;
    }
}
function testFotoCount(max_count)
{
    cur_count=$("div.upl_foto_item").size();
    if(cur_count>=max_count)
    {
        $(".nomax_foto_upl").hide();
        $("#input_foto").hide();
        $("em.max_foto_upl").show();
        
        return false;
    }
    else
    {
        $(".nomax_foto_upl").show();
        $("#input_foto").hide();
        $("em.max_foto_upl").hide();
        return true;
    }
}
function deleteUploadFile(id)
{
        showWaitWindow();
        $.post("/xajax/xajax_rb.php", {
            func: "rbDeleteUploadFile",
            file_id: id
        }, function(data){
            closeWaitWindow();
            if(data=="success")
            {
                $("#f"+id).remove();
            }
            testFileCount(4);
        }, 'html');    
}
function closeFotoStatusWindows()
{
    $(".foto-del").remove();
    $(".foto-error").hide();
    $(".foto-status").hide();
}

