function change (some, id, type) {
	
    if (type == 'status')
    {
        $('#order_status_'+id).attr('value',$(some).val());
    }
    else
    {
        $('#area_comment_'+id).val($(some).val());
    }
}

function newComment (id) 
{
    $.getJSON('/admin.php/order/comment', {
        order_status: $('#order_status_'+id).val(),
        comment: $('#area_comment_'+id).val(),
        order_id: id
    },
    function (data) {
        if (data['result'] == 'ok')
        {
            $('#li_add_carousel_'+id).remove();
				
            //$("#carousel_"+id).jCarouselLite({visible: 4});
				
            width_ul = parseInt(str_replace('px', '', $('#ul_carousel_'+id).css('width'))*1)+260;
            left_ul = parseInt(str_replace('px', '', $('#ul_carousel_'+id).css('left'))*1)-240;
            width_div = parseInt(str_replace('px', '', $('#carousel_'+id).css('width'))*1)+245;
				
            if ($('#carousel_count_'+id).val() >= 4)
            {
                $('#ul_carousel_'+id).css('left', left_ul+'px');
            }
            else
            {
                $('#carousel_'+id).css('width', width_div+'px');
            };
				
            $('#ul_carousel_'+id).css('width', width_ul+'px');
				
            $('#carousel_count_'+id).val(parseInt($('#carousel_count_'+id).val()*1)+1);
				
            $('#ul_carousel_'+id).append('<li style="overflow: hidden; float: left; width: 240px; height: 145px;"><div width="100px" height="100px"><strong>'+data['date_create']+'</strong><br>Статус: <strong>'+data['order_status']+'</strong><br>Коммертарий:<br><strong>'+data['comment']+'</strong></div></li><li id="li_add_carousel_'+id+'" style="overflow: hidden; float: left; width: 240px; height: 145px;"><div width="100px" height="100px"><form onSubmit="newComment('+id+');return false;" method="post" accept-charset="utf-8"><input type="hidden"  value="2" id="order_status_'+id+'"><textarea id="area_comment_'+id+'" style="display:none;"></textarea>Статус:<br><select name="order_status" onchange="change(this, '+id+', \'status\');return false;" size="1"><option value="1">новая</option><option selected="selected" value="2">обработанная</option><option value="3">завершенная</option><option value="4">отклоненная</option></select><br>Коментарий:<br><center><textarea onchange="change(this, '+id+', \'area\');return false;" name="comment" style="width:235px;height:70px;"></textarea></center><p align="right" style="padding:0px;"><input type="submit" name="button" value="отправить"></p></form></div></li>');
				
        }
        else
        {
            alert(data);
        };
    }
    );
}

function makeMeGreen (id) 
{
    if ($('#element_'+id).hasClass('green'))
    {
        $('#element_'+id).removeClass('green')
		
        $.post('/admin_dev.php/element/flag', {
            flag: 0,
            element_id: id
        },
        function (data) {
            if (data == 'error')
            {
                alert(data);
            }
        }
        );
    }
    else
    {
        $('#element_'+id).addClass('green')
		
        $.post('/admin_dev.php/element/flag', {
            flag: 1,
            element_id: id
        },
        function (data) {
            if (data == 'error')
            {
                alert(data);
            }
        }
        );
    };
}

function refreshOrder (sort) 
{
    $.post('/admin.php/order/refresh', {
        sort: sort,
        notin: $('#notin').val(),
        page: $('#page').val(),
    },
    function (data) {
        if (data != 'error')
        {
            if (data != 'null')
            {
                if (sort == 'asc')
                {
                    $('#listing').append(data);
                }
                else
                {
                    $('#listing').prepend(data);
                };
					
                $('#notin').val($('#notin').val()+'|'+$('#notin_new').val());
                $('#notin_new').remove();
            };
        }
        else
        {
            alert('Зови Макса, произошла неведома хня!');
        };
    }
    );
}

function showFiles(id)
{
    if ($('#files_'+id).css('display') == 'none')
    {
        $('#files_'+id).show('slow');
    }
    else
    {
        $('#files_'+id).hide('slow');
    }
}

function applyOrder (id) 
{
    $.getJSON("/admin.php/order/apply", {
        order_id: id
    },
    function(data)
    {
        if (data.result == 'ok')
        {
            $('#order_'+id).removeClass('new');
            $('#order_'+id+'_user').html(data.username);
            $('#order_status_'+id).val(2);
            $('select[name="order_status"]').val(2);
            $('#li_add_carousel_'+id).show('slow');
            $('#ul_carousel_'+id).css('width','240px');
            $('#carousel_'+id).css('width','240px');
        }
        else
        {
            alert(data.error);
            $('#order_'+id).remove();
        };
    }
    );
}

function showAllCategoryElements(id) 
{
    $('body').css('cursor', 'wait');
    $('#hlay').fadeIn('fast');
    $('#category_elemenets').load('/admin.php/element/category?category_id='+id,null, function (data) {
        $('#category_elemenets').html(data);
        $('#category_elemenets').show('slow');
        $('body').css('cursor', 'default');
        $('#hlay').fadeOut('fast');
    });
}

function one_more (count) 
{
    count++;
    $("#add_button").remove();
    $("#elements_count").remove();
    $("#preference").append('<div style="display:none;" id="preference_'+count+'"><a href="" onClick="delete_one('+count+'); return false;" alt="Удалить!" id=""><img width="16" src="/sfPropelPlugin/images/delete.png"></a> <input type="text" id="category_name" value="" name="category_preference['+count+'][name]"/> фильтр: <input type="checkbox" name="category_preference['+count+'][filter_status]" value="1">тип:<select size="1" name="category_preference['+count+'][preference_type]"><option value="1">число</option><option value="2">текст</option><option value="3">да/нет</option></select> ед. изерения: <input type="text" id="" value="" name="category_preference['+count+'][preference_unit]"/><br><br></div><input type="hidden" name="elements_count" value="'+count+'" id="elements_count"><a href="" onClick="one_more('+count+'); return false;" id="add_button"><image width="16" src="/sfPropelPlugin/images/new.png">добавить свойство</a>');
    $("#preference_"+count).show('slow')
}

function one_more_file (count) 
{
    count++;
    $("#add_file_button").remove();
    $("#element_file_count").remove();
    $('#element_file').append('<div style="display:none;padding-bottom:10px;" id="element_file_'+count+'"><a href="" onClick="delete_one_file('+count+'); return false;" alt="Удалить!" id=""><img width="16" src="/sfPropelPlugin/images/delete.png"></a><input type="file" name="element_file['+count+']"></div> <input type="hidden" name="element_files_count" value="'+count+'" id="element_file_count"> <a href="" onClick="one_more_file('+count+'); return false;" id="add_file_button"><image width="16" src="/sfPropelPlugin/images/new.png">добавить еще</a>');
    $("#element_file_"+count).show('slow')
}

function delete_file (id) 
{
    if (confirm('Вы уверены?'))
    {
        $("#file_"+id).hide('slow')
        $("#element_file").append('<input type="hidden" name="element_file['+id+'][delete]" value="1" id="delete">')
    };
}

function delete_one_file (id) 
{
    $("#element_file_"+id).hide('slow');
    setTimeout(function () {
        $("#element_file_"+id).remove();
    }, 1000)
}

function delete_one (id) 
{
    if (typeof($('input.preference_'+id).val()) === 'string')
    {
        if (confirm('Вы уверены?'))
        {
            $("#preference_"+id).hide('slow')
            $("#preference").append('<input type="hidden" name="category_preference['+id+'][delete]" value="1" id="delete">')
        };
    }
    else
    {
        $("#preference_"+id).hide('slow');
        setTimeout(function () {
            $("#preference_"+id).remove();
        }, 1000)
    };
}

function add_preference () 
{
    if ($('#category_parent_id').val() != 0)
    {
        jQuery.getJSON(
            '/admin.php/category/preference',
            {
                "id": $('#category_parent_id').val()
            },
            function(data)
            {
                for (var i=0; i < data.length; i++)
                {
                    count = $("#elements_count").val();
                    count++
					
                    checked_box = ''
                    selected_box = ''
					
                    if(data[i].filter_status == 1)
                    {
                        checked_box = 'checked'
                    }
					
                    if(data[i].filter_status == 1)
                    {
                        selected_box = 'selected'
                    }
					
                    selected_box_preference_type = '';
                    if (data[i].preference_type == 1) {
                        selected_box_preference_type = 'selected'
                    };
                    options = '<option '+selected_box_preference_type+' value="1">число</option>';
                    selected_box_preference_type = '';
                    if (data[i].preference_type == 2) {
                        selected_box_preference_type = 'selected'
                    };
                    options = options+'<option '+selected_box_preference_type+' value="2">текст</option>';
                    selected_box_preference_type = '';
                    if (data[i].preference_type == 3) {
                        selected_box_preference_type = 'selected'
                    };
                    options = options+'<option '+selected_box_preference_type+' value="3">да/нет</option>';
                    selected_box_preference_type = '';
					
                    $("#add_button").remove();
                    $("#elements_count").remove();
					
                    $("#preference").append('<div style="display:none;" id="preference_'+count+'"><a href="" onClick="delete_one('+count+'); return false;" alt="Удалить!" id=""><img width="16" src="/sfPropelPlugin/images/delete.png"></a> <input type="text" id="category_name" value="'+data[i].key+'" name="category_preference['+count+'][name]"/> фильтр: <input type="checkbox" name="category_preference['+count+'][filter_status]" value="'+data[i].filter_status+'" '+checked_box+'> тип:<select size="1" name="category_preference['+count+'][preference_type]">'+options+'</select> ед. изерения: <input type="text" id="" value="'+data[i].preference_unit+'" name="category_preference['+count+'][preference_unit]"/> <input id="category_preference['+count+'][id]" class="preference_'+count+'" type="hidden" value="0" name="category_preference['+count+'][id]"/><br><br></div><input type="hidden" name="elements_count" value="'+count+'" id="elements_count"><a href="" onClick="one_more('+count+'); return false;" id="add_button"><image width="16" src="/sfPropelPlugin/images/new.png">добавить свойство</a>');
                    $("#preference_"+count).show('slow')
                };
            }
            );
    };
}

function add_preference_control() 
{
    if($('#category_parent_id').val() == 0)
    {
        $('#add_preference_button').hide('slow')
    }
    else
    {
        $('#add_preference_button').show('slow')
    }
}

function change_preference (select) 
{
	
    $("#preference").hide('slow');
	
    $("#preference").html('');
	
    $.getJSON(
        '/admin.php/category/preference',
        {
            "id": $('#element_category_id').val()
        },
        function(data)
        {
            for (var i=0; i < data.length; i++)
            {
                value_field = '<input type="text" name="element_preference['+i+'][value]" value="" id="element_preference['+i+']"/>'
				
                if (data[i].preference_type == 3)
                {
                    checked_box = '';
					
                    if (data[i].value == 1) {
                        checked_box = 'checked'
                    };
					
                    value_field = '<input type="checkbox" name="element_preference['+i+'][value]" value="1" id="element_preference['+i+']" checked_box/>'
                }
				
                value_field = value_field+' '+data[i].preference_unit;
				
                $("#preference").append('<div class="sf_admin_form_row sf_admin_text sf_admin_form_field_company_price"><div><label for="element_preference">'+data[i].key+'</label><div class="content">'+value_field+'<input type="hidden" id="element_preference['+i+'][id]" value="0" name="element_preference['+i+'][id]"/><input type="hidden" id="element_preference['+i+'][category_preference_id]" value="'+data[i].id+'" name="element_preference['+i+'][category_preference_id]"/></div></div></div>');
            };
        }
        );
	
    $("#preference").show('slow');
}

function add_company () 
{
    if ($('#element_company').val() == 'new')
    {
        $('#element_company_new').html(' &nbsp;&nbsp;&nbsp; Название: <input type="text" name="element_company[name]"> Агент: <input type="text" name="element_company[agent]"> Тел.: <input type="text" name="element_company[phone]"> Сайт: <input type="text" name="element_company[site]">');
		
        $('#element_company_new').show('slow')
    }
    else
    {
        $('#element_company_new').hide('slow')
    };
}

function go2ElementPage (category_name, element_id) 
{
    var newUrl = '/catalog/'+category_name+'/'+element_id+'#order_form';
    setTimeout(function()
    {
        window.location = newUrl;
    }, 0);
}

function go2Element (element_id) 
{
    window.location = '/admin.php/element/'+element_id+'/edit';
}

function showCompanyData () 
{
    $.getJSON(
        '/admin.php/company/data',
        {
            "company_id": $('#element_company').val()
        },
        function(data)
        {
            $('#element_company_view').html('');
            $('#element_company_view').append('<br><br><p><a href="http://'+data.site+'" target="_blank">'+data.site+'</a> Тел.: <input id="company_phone" value="'+data.phone+'">  Город: <input id="company_city" value="'+data.city+'"> </p><p> Наш коментарий <textarea id="company_our_comment" style="width:300px;height:35px">'+data.our_comment+'</textarea> <input onClick="saveCompanyData();return false;" type="submit" value="изменить"></p>');
            $('#element_company_view').show('slow');
        }
        );
}

function saveCompanyData()
{
    $.post('/admin.php/company/save', {
        "company_id": $('#element_company').val(),
        "company_phone": $('#company_phone').val(),
        "company_our_comment": $('#company_our_comment').val(),
        "company_city": $('#company_city').val(),
    },
    function  (data)
    {
        if (data == 'ok')
        {
            alert('Информация сохранена!');
        }
        else
        {
            alert('Ошибка! Зови Макса!');
        };
    }
    );
}

function new_order () {
    if ($('#phone').val() == '')
    {
        alert('Поле Телефон обязательно для заполнения!');
    }
    else
    {
        $('#order_form').submit();
    }
}

function showElementInfo (element_id) {
    $('#elementInfo_'+element_id).show();
}

function hideElementInfo (element_id) {
    $('#elementInfo_'+element_id).hide();
}

function filterChange (category_id) {
    $.getJSON('http://lk-broker.ru/category/filter?category_id='+category_id+'&brand='+$('select[name="brand"]').val()+'&year_from='+$('select[name="year_from"]').val()+'&year_to='+$('select[name="year_to"]').val()+'&city='+$('select[name="city"]').val(),
        function(data){
			
            if ($('select[name="city"]').val() == 0)
            {
                $('select[name="city"]').html('<option value="0">Не имеет значения</option>');
				
                $.each(data.citys, function(i,city){
                    $('select[name="city"]').append('<option value="'+i+'">'+i+'</option>');
                });
            };
			
            if ($('select[name="year_from"]').val() == 0 && $('select[name="year_to"]').val() == 0)
            {
                $('select[name="year_from"]').html('<option value="0">Любой</option>');
                $('select[name="year_to"]').html('<option value="0">Любой</option>');
			
                $.each(data.years, function(i,city){
                    $('select[name="year_to"]').append('<option value="'+i+'">'+i+'</option>');
                    $('select[name="year_from"]').append('<option value="'+i+'">'+i+'</option>');
                });
            }
			
            if ($('select[name="brand"]').val() == 0)
            {
                $('select[name="brand"]').html('<option value="0">Не имеет значения</option>');
				
                $.each(data.brands, function(i,city){
                    $('select[name="brand"]').append('<option value="'+i+'">'+i+'</option>');
                });
            };
        }
        );
}

function str_replace ( search, replace, subject ) 
{
    if(!(replace instanceof Array))
    {
        replace=new Array(replace);
        if(search instanceof Array)
        {
            while(search.length>replace.length)
            {
                replace[replace.length]=replace[0];
            }
        }
    }

    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length)
    {
        replace[replace.length]='';
    }

    if(subject instanceof Array)
    {
        for(k in subject)
        {
            subject[k]=str_replace(search,replace,subject[k]);
        }
			
        return subject;
    }

    for(var k=0; k<search.length; k++)
    {
        var i = subject.indexOf(search[k]);
        while(i>-1)
        {
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }
		
    return subject;
}

function makeBanner (id) 
{
	
    if ($('#banner_element_'+id).attr('src') == '/sfBrokerBannerPlugin/images/add.png')
    {
        //alert('da '+created);
        $('#banner_element_'+id).attr('src', '/sfBrokerBannerPlugin/images/delete.png');
        created = 0;
    }
    else
    {
        $('#banner_element_'+id).attr('src', '/sfBrokerBannerPlugin/images/add.png');
        created = 1;
    }
	
    $.post('/admin.php/element/banner',
    {
        banner: created,
        element_id: id
    },
    function(data)
    {
        //alert(data);
        if(data != 'ok')
        {
            alert('Упс! Что-то пошло не так!')
        }
    }
    );
}

function setSort(id)
{
    if ($('#element_sort_'+id).val() != '')
    {
        $.post('/admin.php/element/sort',
        {
            'sort': $('#element_sort_'+id).val(),
            'element_id': id,
        },
        function(data)
        {
            if(data != 'ok')
            {
                alert('Упс! Что-то пошло не так!')
            }
            else
            {
                $('#element_sort_'+id).css('background-color', '#005500')
                $('#element_sort_'+id).css('color', '#ffffff')
            }
        }
        );
    };
}

$(document).ready(function  () {
    $(document).bind('keydown', '*', function (evt){
        $('#art').focus();
        return false;
    });
    $('#element_category_id').attr('onChange', 'change_preference()');
    //$('#element_company').attr('onChange', 'add_company()');
	
    if ($("#have_preference").val() == 1) {
        change_preference();
    };

    $('.starred').each(function() {
        $(this).bind('click', function() {
            ref = $(this).attr('ref')
            title = $(this).attr('title')
            if (ref > 5) {
                $(this).removeClass('p'+ref)
                ref = 0
            } else {
                $(this).removeClass('p'+ref)
                ref++
            }
            $(this).addClass('p'+ref)
            $(this).attr('ref', ref)
            $.post('/admin.php/'+ title +'/starred',
            {
                'starred': ref,
                'id':      $(this).attr('id')
            },
            function(data)
            {
                if(data != 'ok')
                {
                    alert('Упс! Что-то пошло не так!')
                }
            }
            );
        });
    });

    $('.dstarred').each(function () {
        $(this).bind('click', function() {
            ref = $(this).attr('ref');
            if (ref){
            document.location.href = "/admin.php/element?starred=true&star="+ref;
                return false;
            } else {
                return false;
            }
        });
    });

});
