/**
 *
 */
 
// Create user extension namespace (Application)
Ext.namespace('Application');

Ext.onReady(function(){
   
 	// Create a cart object for order processing
 	Application.cart = {
        /**
         * Add item(s) to the cart
         * 
         * itemObj may be an object width item `id` and ordered `qty` properties
         * or an array of such objects
         */ 	
 		doAction: function(action, itemObj, callback, stopLeftGridUpdate){
 			 if (typeof action == 'undefined')
 			    return false;
 			    
 			 if (typeof itemObj == 'undefined')
 			    itemObj = [];
 			    
 		     if (!(itemObj instanceof Array)) {
 		     	itemObj = [itemObj]
 		     }
 		     
 		     var itemsArr = [];
 		     Ext.each(itemObj, function(item, item_id, all_items){
 		     	if (action == 'delete') {
                    itemsArr.push({
                        id: item.id
                    });
 		     	} else {
                    itemsArr.push({
                        id: item.id,
                        qty: item.qty || 1
                    });
 		     	}
             },this);
 		     Ext.Ajax.request({
                url: '/cart/do'
                ,params: Ext.util.JSON.encode({"items": itemsArr, "action": action})
                ,scope: this
                ,method: 'POST'
                ,callback: function(options, success, response){ 
                    var answer = Ext.util.JSON.decode(response.responseText);
                    if (!success || answer.success == 'false') {
                        Ext.Msg.alert('Нева-Центр', answer.msg);
                        return;
                    } else {
                    	this.updateFields(answer);
                    	this.updateCartTable(answer.lastModifiedItems)
                    	if (typeof callback == "function")
                    	   callback();
                    	// remove old rows if delete action
                        if (action == 'delete') {
                            $.each(itemsArr, function(index, obj) { 
                                $("#nc_cart_row_" + obj.id).remove();
                            });
                            Application.cart.stripeCartTable();
                        }
                        if (action == 'clear') {
                            $("tr.nc_cart_row").remove();
                            Application.cart.stripeCartTable();
                        }
                    }
                    if (typeof stopLeftGridUpdate == 'undefined')
                        V.cartGrid.store.reload();
                }
            });
 		},
 		
 		updateFields: function(summary){
 		     /*$('.nc_cart_totalSumm').html($().number_format(summary.totalSumm, {
                 numberOfDecimals: 0,
                 decimalSeparator: '.',
                 thousandSeparator: ' ',
                 symbol: ''})
              );*/
 		     $('.nc_cart_totalSumm').html(summary.totalSumm);
 		     $('.nc_cart_totalQty').html($().number_format(summary.totalQty, {
                 numberOfDecimals: 0,
                 decimalSeparator: '.',
                 thousandSeparator: ' ',
                 symbol: ''})
             );
 		},
 		
 		updateCartTable: function(rowsToAdd) {
 			jQuery.fn.exists = function(){return jQuery(this).length>0;}
            $.each(rowsToAdd, function(index, item){
               if($('#nc_cart_table #nc_cart_row_' + item.id).exists()) {
               	    $('#cart_item_qty_' + item.id).val(item.qty);
               	    /*$('#cart_item_summ_' + item.id).html($().number_format(item.summ, {
                         numberOfDecimals: 0,
                         decimalSeparator: '.',
                         thousandSeparator: ' ',
                         symbol: ''}
                    ));*/
               	    $('#cart_item_summ_' + item.id).html(item.summ);
                    if (item.excess) {
                    	/* Можно для всех подсвечиваемых элементов сделать один класс вместо разных id 
                    	 * и обращаться к ним, как к набору 
                    	 * */
                    	$("#nc_cart_item_title_" + item.id).addClass("warning");
                    	$("#cart_item_qty_" + item.id).addClass("warning");
                    	$("#nc_cart_qty_item_status_" + item.id).html("(" + item.avail + " шт.)");
                    	$("#nc_cart_qty_item_status_" + item.id).addClass("warning");
                    	
                    } else {
                    	$("#nc_cart_item_title_" + item.id).removeClass("warning");
                    	$("#cart_item_qty_" + item.id).removeClass("warning");
                    	$("#nc_cart_qty_item_status_" + item.id).html("");
                    	$("#nc_cart_qty_item_status_" + item.id).removeClass("warning");
                    }
               } else {
                   	/*item.price = $().number_format(item.price, {
                         numberOfDecimals: 0,
                         decimalSeparator: '.',
                         thousandSeparator: ' ',
                         symbol: ''}
                    );*/
                   	item.price = item.price;
                   	/*item.summ = $().number_format(item.summ, {
                         numberOfDecimals: 0,
                         decimalSeparator: '.',
                         thousandSeparator: ' ',
                         symbol: ''}
                    );*/
                   	item.summ = item.summ;
                    
                    var warning_class = "";
                    var items_avail = ""; 
                    if (item.excess) {
                    	var warning_class = " warning";
                        var items_avail = '(' + item.avail + ' шт.)';
                    } 
                   	var rowHtml = String.format('<tr class="nc_cart_row" id = "nc_cart_row_{0}"> \
                                        <td class="check_column"><input type="checkbox" name="item" value="{0}"></td> \
                                        <td><a href="#/tovar/{0}">{0}</a></td> \
                                        <td id="nc_cart_item_title_{0}" class="{4}">{1}</td> \
                                        <td class="align_right" id="cart_item_price_{0}" >{2}</td> \
                                        <td class="nc_cart_qty_input_row{4}"><input class="qty_input{4}" id="cart_item_qty_{0}"  size="4" type="text" value="'+ item.qty +'"/><span id="nc_cart_qty_item_status_{0}" class="{4}">{5}</span></td> \
                                        <td class="align_right"><span id="cart_item_summ_{0}">{3}</span></td> \
                                        <td></td> \
                                    </tr>', item.id, item.title, item.price, item.summ, warning_class, items_avail);
                     $("#nc_cart_table_body").append(rowHtml);
                     Application.cart.stripeCartTable();
                     Application.cart.bindItemQtyChange();
               }
            });
 		},
 		
 		updatePrices: function(items) {
 		     $.each(items, function(index, item){
 		         $("#cart_item_price_" + item.id).html(item.priceForOne);
 		         $("#cart_item_summ_" + item.id).html(item.totalSumm);
 		     });
 		},
 		
 		switchCurrency: function(newCurr) {
 		     Ext.Ajax.request({
                url: '/switchcurrency'
                ,params: {curr: newCurr}
                ,scope: this
                ,method: 'POST'
                ,callback: function(options, success, response){ 
                    var answer = Ext.util.JSON.decode(response.responseText);
                    if (!success || answer.success == 'false') {
                        Ext.Msg.alert('Нева-Центр', answer.msg);
                        return;
                    } else {
                        this.updateFields(answer);
                        this.updatePrices(answer.items);
                        $("#nc_cart_table th a.option").removeClass("selected");
                        $("#nc_cart_table th a.curr_switch_" + newCurr).addClass("selected");
                    }
                    V.cartGrid.store.reload();
                }
            });
 		},
 		repeatOrder: function(order_id, order_date) {
             Ext.Ajax.request({
                url: '/repeatorder'
                ,params: {order_id: order_id, order_date: order_date}
                ,scope: this
                ,method: 'POST'
                ,callback: function(options, success, response){ 
                    var answer = Ext.util.JSON.decode(response.responseText);
                    if (!success || answer.success == 'false') {
                        Ext.Msg.alert('Нева-Центр', answer.msg);
                        return;
                    } else {
                        this.updateFields(answer);
                        this.updateCartTable(answer.lastModifiedItems);
                    }
                    V.cartGrid.store.reload();
                }
            });		
 		},
 		bindItemQtyChange: function() {
             $(".qty_input").keyfilter(/[\d\-\.]/);        
             $(".qty_input").change(function(){
                 var item_id = $(this).attr("id").split("_").slice(3).join("_");
                 Application.cart.doAction("change", {id: item_id, qty: $(this).val()});
             })        
             $(".orderParam").change(function(){
                Ext.Ajax.request({
                    url: '/cart-save-params'
                    ,params: {comments: $('#cartOrderComments').val(), emails: $('#cartOrderEmails').val()}
                    ,scope: this
                    ,method: 'POST'
                    ,callback: function(options, success, response){ 
                        var answer = Ext.util.JSON.decode(response.responseText);
                        if (!success || answer.success == 'false') {
                            Ext.Msg.alert('Нева-Центр', answer.msg);
                            return;
                        } else {
                            
                        }
                    }
                });     
             })        
        },
 		sendOrder: function(){
 			Ext.Msg.confirm(
               'Корзина'
               ,'Вы закончили формирование заказа?'
               ,function(a){
                   if(a == 'yes') {
                       Ext.Ajax.request({
                            url: '/send-order'
                            ,params: {comments: $('#cartOrderComments').val(), emails: $('#cartOrderEmails').val()}
                            ,scope: this
                            ,method: 'POST'
                            ,callback: function(options, success, response){ 
                                var answer = Ext.util.JSON.decode(response.responseText);
                                if (!success || answer.success == 'false') {
                                    Ext.Msg.alert('Нева-Центр', answer.msg);
                                    return;
                                } else {
                                    if (answer.msg) {
                                        Ext.Msg.alert('Нева-Центр', answer.msg);
                                    }
                                    Application.cart.switchCurrency(648);
                                }
                            }
                        }); 
                   }
               },this);
   
 		},
 		stripeCartTable: function() {
 			 var d = false;
             $(".nc_cart_row").each(function(){
                    $(this).removeClass("bg-e bg-o");
                    if (d == true) {
                        $(this).addClass("bg-o"); d = false;
                    }
                    else {
                        $(this).addClass("bg-e"); d = true;
                    }
             });  
 		}
 	};
 	
 	// Input fields autoselect
    $("input:text").focus(function(){$(this).select();});
 	$(document).ajaxComplete(function(){
       $("input:text").focus(function(){$(this).select();});
    });
    
    Application.highlight = {
        filterBar: function(query, status){
        	$("#filterNewSelector").removeClass('selected');
        	$("#filterDiscountSelector").removeClass('selected');
        	$("#filterFilterSelector").removeClass('selected');
        	if (status) {
                switch (query){
                	case "new":
                	   $("#filterNewSelector").addClass('selected');
                	   break;
                	case "discount":
                	   $("#filterDiscountSelector").addClass('selected');
                	   break;
                	default:
                       $("#filterFilterSelector").addClass('selected');
                }       
        	} 
        }
    }
    
    Application.actForm = {
        details: [],
        addDetail: function(det){
        	var exist = false;
            $.each(Application.actForm.details, function(index, el){
                if (el.id == det.id) {
                	el.qty = parseInt(det.qty) + parseInt(el.qty);
                	exist = true;
                }
            });
            if (!exist) {
            	Application.actForm.details.push(det);
            }
            Application.actForm.updateTable();
            $("#act-form-save-btn").removeAttr('disabled');
        },
        removeDetail: function(id){
        	try {
        	$.each(Application.actForm.details, function(index, el){
                if (el.id == id) {
                    Application.actForm.details.splice(index,1);
                    $("#nc_act_form_row_" + id).remove();
                }
            });
        	} catch (err) {
        		// handle
        	}
            Application.actForm.updateTable();
            $("#act-form-save-btn").removeAttr('disabled');
        },
        updateTable: function(){
            $("#nc_act_form_table_body tr").remove();
            if (this.details.length < 1) {
            	$("#nc_act_form_table_body").append('<tr class="bg-e"><td colspan="5" class="no_items">Нет записей</td></tr>');
            } else {
                $.each(Application.actForm.details, function(index, item){
                    var rowHtml = String.format('<tr class="nc_act_form_row" id = "nc_act_form_row_{1}"> \
                                            <td>{0}</td> \
                                            <td><a href="#/tovar/{1}" class="item_id">{1}</a></td> \
                                            <td>{2}</td> \
                                            <td><span style="display: none" class="item_qty">{3}</span>{3} шт.</td> \
                                            <td style="text-align:right"><a style="text-decoration:none; border-bottom: dotted 1px;" onclick="Application.actForm.removeDetail(\'{1}\')">Удалить</a></td> \
                                        </tr>', index + 1, item.id, item.title, item.qty);
                     $("#nc_act_form_table_body").append(rowHtml);
                });
                Application.actForm.stripeRows();
            }
        },
        stripeRows: function(){
            var d = false;
             $(".nc_act_form_row").each(function(){
                    $(this).removeClass("bg-e bg-o");
                    if (d == true) {
                        $(this).addClass("bg-o"); d = false;
                    }
                    else {
                        $(this).addClass("bg-e"); d = true;
                    }
             });  
        },
        
        sendOrder: function(callback){
            Ext.Msg.confirm(
               'Корзина'
               ,'Вы закончили формирование заказа?'
               ,function(a){
                   if(a == 'yes') {
                        Ext.Ajax.request({
                        url: "/send_order"
                        ,params: {comments: $('#cartOrderComments').val(), emails: $('#cartOrderEmails').val()}
                        ,scope: this
                        ,method: 'POST'
                        ,callback: function(options, success, response){ 
                            var answer = Ext.util.JSON.decode(response.responseText);
                            if (!success || answer.success == false) {
                                Ext.Msg.alert('Нева-Центр', answer.msg);
                                return;
                            } else {
                                $("#act-form-save-btn").attr('disabled', 'disabled');
                                if (answer.msg) {
                                    Ext.Msg.alert('Нева-Центр', answer.msg);
                                }
                                if (typeof(callback) == "function") {
                                    callback(answer);
                                }
                                Application.cart.updateFields();
                                Application.cart.updateCartTable();
                            }
                        }
                    });       
                   }
               },this);
        }
    }
    
    // Form saving function
    Application.saveForm = function(formId, callback){
        // collectiong data
        data = {};

        $("#" + formId + " input").each(function(){
            data[$(this).attr('name')] = $(this).val();
            });

        // send query
        Ext.Ajax.request({
            url: $("#" + formId).attr('target')
            ,params: data
            ,scope: this
            ,method: 'POST'
            ,callback: function(options, success, response){ 
                var answer = Ext.util.JSON.decode(response.responseText);
                if (!success || answer.success == false) {
                    Ext.Msg.alert('Нева-Центр', answer.msg);
                    return;
                } else {
                    $("#act-form-save-btn").attr('disabled', 'disabled');
                	if (answer.msg) {
                		Ext.Msg.alert('Нева-Центр', answer.msg);
                	}
                    if (typeof(callback) == "function") {
                        callback(answer);
                    }
                }
            }
        });        	
    }
    
/**************************************************************************************************************************/
    Application.stripeRows = function(rowClass, tagPropsQty) {
    	if(tagPropsQty == true) {
    		tagPropsQty = 12;
    	} else {
    		tagPropsQty = false;
    	}
    	tagCounter = 0
        var d = false;
        $("." + rowClass).each(function(index){
        	// stripe rows
               $(this).removeClass("bg-e bg-o");
               if (d == true) {
                   $(this).addClass("bg-o"); d = false;
               }
               else {
                   $(this).addClass("bg-e"); d = true;
               }
        });  
        // props print indicator
        if (tagPropsQty != false) {
            // clear
        	$("." + rowClass).each(function(index){
                   $(this).find(".prop_printed").css('display', 'none');
                   $(this).find(".prop_not_printed").css('display', 'inline');
        	});
            // set
            for (pos in {'top':'','bottom':'', 'middle':''}){
                $("." + rowClass).each(function(index){
            	   if ($(this).has("input:checkbox:checked").length > 0 
            	           && tagCounter < tagPropsQty
            	           && $(this).find("input:radio:checked").first().val() == pos) {
            	   	  $(this).find(".prop_printed").css('display', 'inline');
            	   	  $(this).find(".prop_not_printed").css('display', 'none');
                      tagCounter += 1;
            	   } 
                });  
            }
        }
    }
    
    /**
     * @param purpose "add" or "edit"
     */
    Application.propEditForm = function(purpose, item_id, prop_id){
    	
    	// turn on validation errors beside the field globally
        //Ext.form.Field.prototype.msgTarget = 'side';
        
    	//Form items
    	var formItems = [{
                    fieldLabel: 'Название характеристики',
                    emptyText: 'Название характеристики',
                    name: 'prop_title',
                    anchor: '100%'
                },new Ext.form.ComboBox({
                    fieldLabel: 'Тип',
                    hiddenName:'prop_type',
                    store: new Ext.data.ArrayStore({
                        fields: ['prop_type_title', 'prop_type'],
                        data : [['Текст', 'text'], ['Число', 'number'], ['Выбор из списка', 'select']]
                    }),
                    valueField:'prop_type',
                    displayField:'prop_type_title',
                    typeAhead: true,
                    editable: false,
                    mode: 'local',
                    triggerAction: 'all',
                    emptyText:'Выберите тип...',
                    selectOnFocus:true,
                    anchor: '40%'
                }),new Ext.form.ComboBox({
                    fieldLabel: 'Значение',
                    hiddenName:'prop_value',
                    store: new Ext.data.ArrayStore({
                        fields: ['prop_value'],
                        data : []
                    }),
                    valueField:'prop_value',
                    displayField:'prop_value',
                    typeAhead: true,
                    mode: 'local',
                    triggerAction: 'all',
                    emptyText:'Введите или выберите значение...',
                    selectOnFocus:true,
                    anchor: '100%'
                }),new Ext.form.ComboBox({
                    fieldLabel: 'Единицы измерения',
                    hiddenName:'prop_unit',
                    store: new Ext.data.ArrayStore({
                        fields: ['unit_title'],
                        data : []
                    }),
                    valueField:'unit_title',
                    displayField:'unit_title',
                    typeAhead: true,
                    mode: 'local',
                    triggerAction: 'all',
                    emptyText:'Введите или выберите единицу измерения...',
                    selectOnFocus:true,
                    anchor: '90%'
                })
            ];
    	
        if (purpose == "add") {
            formItems[0] = new Ext.form.ComboBox({
                    fieldLabel: 'Название характеристики',
                    hiddenName:'prop_title',
                    store: new Ext.data.ArrayStore({
                        fields: ['prop_title'],
                        data : []
                    }),
                    valueField:'prop_title',
                    displayField:'prop_title',
                    typeAhead: true,
                    mode: 'local',
                    triggerAction: 'all',
                    emptyText:'Введите или выберите из списка...',
                    selectOnFocus:true,
                    anchor: '100%'
                });        	
        }
            
        var fs = new Ext.FormPanel({
            //frame: true,
        	baseCls: 'x-plain',
            labelAlign: 'top',
            labelWidth: 125,
            waitMsgTarget: true,
            border: false,
            autoHeight: true,
            defaultType: 'textfield',
    
            // reusable eror reader class defined at the end of this file
            //errorReader: new Ext.form.XmlErrorReader(),
    
            items: formItems
        });
    
        fs.on({
            actioncomplete: function(form, action){
                if(action.type == 'load'){
                    submit.enable();
                }
            }
        });    
        
        
        win = new Ext.Window({
                //applyTo:'hello-win',
                layout:'fit',
                title:'Редактирование свойства',
                width:350,
                height: 280,
                bodyStyle:'padding:5px;',
                closeAction:'destroy',
                plain: true,
                modal: true,
                items: [fs]
            });
        if (purpose == "add") {
        	win.setTitle('Добавление характеристики');
        }
        if (purpose == "edit") {
        	win.setTitle('Редактирование характеристики');
        }
        // simple button add
        win.addButton('Отмена', function(){
        	win.close();
        });
    
        // explicit add
        var submit = win.addButton({
            text: 'Сохранить',
            disabled:true,
            handler: function(){
                fs.getForm().submit({
                    url:'/save_item_prop', 
                    waitMsg:'Сохранение...', 
                    submitEmptyText: false,
                    params: {item_id: item_id, prop_id: prop_id},
                    success: function(form, action){
                    	if (purpose == "edit") {
                            $('#item_prop_' + prop_id + ' .p_title').html(fs.items.itemAt(0).getValue());
                            $('#item_prop_' + prop_id + ' .p_value').html(fs.items.itemAt(2).getValue() + " " + (fs.items.itemAt(3).getValue() != null ? fs.items.itemAt(3).getValue(): ''));
                    	}
                    	if (purpose == "add") {
                    	   var rowHtml = String.format('<tr id="item_prop_{0}" class="item_prop_row">' +
                                          '<td style="width:250px" class="p_title">{1}</td>' +
                                          '<td class="p_value">{2} {3}</td>' +
                                          '<td style="text-align: center"><input class="item_prop_show" id="item_prop_show_{0}" title="Печатать/не печатать характеристику в ценнике" type="checkbox" {4} value="{5}"/></td>' +
                                          '<td><a onclick="Application.propEditForm(\'edit\', \'{6}\', \'{0}\')" title="Редактировать"><img src="/i/edit.png"></img></a></td>' +
                                          '<td><a onclick="deleteProp(\'{6}\',{0})" title="Удалить"><img src="/i/delete.png"></img></a></td>' +
                                        '</tr>', action.result.prop_id, 
                                                action.result.prop_title, 
                                                action.result.prop_value, 
                                                action.result.prop_unit != null ? action.result.prop_unit : '',
                                                action.result.prop_show == 1 ? 'checked' : '',
                                                action.result.prop_weight,
                                                action.result.item_id);
                           rowsQty = $('.item_prop_row').size();
                           if (rowsQty == 0) {
                           	    $("#price_tag_props").html(rowHtml);
                           	    Application.stripeRows("item_prop_row", true);
                           }
                           $('.item_prop_row').each(function(index){
                                //console.log(this);
                                var currWeight = parseInt($(this).find(".item_prop_show").first().val());
                                if (action.result.prop_weight < currWeight) {
                                	$(this).before(rowHtml);
                                	Application.stripeRows("item_prop_row", true);
                                	return false;
                                }
                                if (index == rowsQty-1) {
                                	$(this).after(rowHtml);
                                	Application.stripeRows("item_prop_row", true);
                                	return false;
                                }
                           });
                        }
                    	win.close();
                    },
                    failure: function(form, action){
                        Ext.Msg.alert('Нева-Центр', action.result.msg);
                        return;
                    }});
            }
        });
                  
        //fs.getForm().load({url:'xml-form.xml', waitMsg:'Loading'});
        win.show();
        
        // retrieve data
        Ext.Ajax.request({
                 url: '/get_item_prop'
                ,params: {purpose: purpose, item_id: item_id, prop_id: prop_id}
                ,scope: this
                ,method: 'POST'
                ,callback: function(options, success, response){ 
                    var answer = Ext.util.JSON.decode(response.responseText);
                    if (!success || answer.success == 'false') {
                        Ext.Msg.alert('Нева-Центр', answer.msg);
                        return;
                    } else {
                        if (answer.msg) {
                            Ext.Msg.alert('Нева-Центр', answer.msg);
                        }
                        // set values
                        if (purpose == "edit") {
                            fs.items.itemAt(0).setValue(answer.prop_title);
                            fs.items.itemAt(1).setValue(answer.prop_type);
                            fs.items.itemAt(2).getStore().loadData(answer.prop_value_set);
                            fs.items.itemAt(2).setValue(answer.prop_value);
                            fs.items.itemAt(3).getStore().loadData(answer.prop_unit_set);
                            fs.items.itemAt(3).setValue(answer.prop_unit);
                        }
                        if (purpose == "add") {
                        	fs.items.itemAt(0).getStore().loadData(answer.props_unused);
                        	fs.items.itemAt(0).on('select', function(el, record){
                        	   fs.items.itemAt(1).setValue(answer.props_unused_types[el.getValue()]);
                        	   fs.items.itemAt(2).getStore().loadData(answer.props_unused_values[el.getValue()]);
                        	   fs.items.itemAt(3).getStore().loadData(answer.props_unused_units[el.getValue()]);
                        	});
                        }
                        submit.enable();
                    }
                }
        });    
        
        return win;
    } // EOF propEditForm fubction

/**************************************************************************************************************/
    
    Application.descrEditForm = function(item_id, prop_id){
    	//Form items
        var formItems = [new Ext.form.TextArea({
                    fieldLabel: 'Описание',
                    emptyText: 'Здесь должно быть краткое описание товара...',
                    name: 'value',
                    anchor: '100%',
                    height: 185
                })];
        
                   
        var fs = new Ext.FormPanel({
            //frame: true,
            baseCls: 'x-plain',
            labelAlign: 'top',
            labelWidth: 125,
            waitMsgTarget: true,
            border: false,
            autoHeight: true,
            defaultType: 'textfield',
    
            // reusable eror reader class defined at the end of this file
            //errorReader: new Ext.form.XmlErrorReader(),
    
            items: formItems
        });
    
        fs.on({
            actioncomplete: function(form, action){
                if(action.type == 'load'){
                    submit.enable();
                }
            }
        });    
        
        
        win = new Ext.Window({
                //applyTo:'hello-win',
                layout:'fit',
                title:'Редактирование описания',
                width:350,
                height: 280,
                bodyStyle:'padding:5px;',
                closeAction:'destroy',
                plain: true,
                modal: true,
                items: [fs]
            });
       
        // simple button add
        win.addButton('Отмена', function(){
            win.close();
        });
    
        // explicit add
        var submit = win.addButton({
            text: 'Сохранить',
            disabled:true,
            handler: function(){
                fs.getForm().submit({
                    url:'/save_item_descr', 
                    waitMsg:'Сохранение...', 
                    submitEmptyText: false,
                    params: {item_id: item_id},
                    success: function(form, action){
                    	var answer = action.result;
                        if (answer.msg) {
                            Ext.Msg.alert('Нева-Центр', answer.msg);
                        }
                        // set values
                        $("#item_descr_text").html(answer.descr);
                        win.close();
                    },
                    failure: function(form, action){
                        Ext.Msg.alert('Нева-Центр', action.result.msg);
                        return;
                    }});
            }
        });
                  
        //fs.getForm().load({url:'xml-form.xml', waitMsg:'Loading'});
        win.show();
        
        // retrieve data
        Ext.Ajax.request({
                 url: '/get_item_descr'
                ,params: {item_id: item_id}
                ,scope: this
                ,method: 'POST'
                ,callback: function(options, success, response){ 
                    var answer = Ext.util.JSON.decode(response.responseText);
                    if (!success || answer.success == 'false') {
                        Ext.Msg.alert('Нева-Центр', answer.msg);
                        return;
                    } else {
                        if (answer.msg) {
                            Ext.Msg.alert('Нева-Центр', answer.msg);
                        }
                        // set values
                        fs.items.itemAt(0).setValue(answer.descr);
                        submit.enable();
                    }
                }
        });    
        
        return win;
    };
    

/**************************************************************************************************************/
    
    Application.addFileForm = function(item_id){
    	//Form items
    	/*var fbutton = new Ext.ux.form.FileUploadField({
            renderTo: 'fi-button',
            buttonOnly: true,
            listeners: {
                'fileselected': function(fb, v){
                    var el = Ext.fly('fi-button-msg');
                    el.update('<b>Selected:</b> '+v);
                    if(!el.isVisible()){
                        el.slideIn('t', {
                            duration: .2,
                            easing: 'easeIn',
                            callback: function(){
                                el.highlight();
                            }
                        });
                    }else{
                        el.highlight();
                    }
                }
            }
        });*/
    	
        var formItems = [{
                    fieldLabel: 'Описание',
                    emptyText: 'Описание содержимого файла...',
                    name: 'fileDescr',
                    anchor: '100%'
                },new Ext.form.ComboBox({
                    fieldLabel: 'Тип',
                    hiddenName:'fileType',
                    store: new Ext.data.ArrayStore({
                        fields: ['file_type_title', 'file_type'],
                        data : [['Не определен', 'undefined'],['Инструкция', 'instruction'], ['Сертификат', 'certificate'], ['Деталировка/ремонт/запчасть', 'detail'], ['Инструкция на двигатель', 'engine_instruction']]
                    }),
                    valueField:'file_type',
                    displayField:'file_type_title',
                    typeAhead: true,
                    editable: false,
                    mode: 'local',
                    triggerAction: 'all',
                    emptyText:'Выберите тип...',
                    selectOnFocus:true,
                    anchor: '60%',
                    value: 'undefined'
                }),{
                    xtype: 'fileuploadfield',
                    id: 'form-file',
                    emptyText: 'Выберите файл',
                    fieldLabel: 'Файл',
                    name: 'filePath',
                    buttonText: '',
                    anchor: '100%',
                    buttonCfg: {
                        iconCls: 'upload-icon'
                    }
                }];
        
                   
        var fs = new Ext.FormPanel({
            //frame: true,
            baseCls: 'x-plain',
            labelAlign: 'top',
            labelWidth: 125,
            fileUpload: true,
            waitMsgTarget: true,
            border: false,
            autoHeight: true,
            defaultType: 'textfield',
    
            // reusable eror reader class defined at the end of this file
            //errorReader: new Ext.form.XmlErrorReader(),
    
            items: formItems
        });
    
        fs.on({
            actioncomplete: function(form, action){
                if(action.type == 'load'){
                    submit.enable();
                }
            }
        });    
        
        
        win = new Ext.Window({
                //applyTo:'hello-win',
                layout:'fit',
                title:'Добавление файла',
                width:350,
                height: 230,
                bodyStyle:'padding:5px;',
                closeAction:'destroy',
                plain: true,
                modal: true,
                items: [fs]
            });
       
        // simple button add
        win.addButton('Отмена', function(){
            win.close();
        });
    
        // explicit add
        var submit = win.addButton({
            text: 'Загрузить',
            disabled:true,
            handler: function(){
                fs.getForm().submit({
                    url:'/save_file', 
                    waitMsg:'Сохранение...', 
                    submitEmptyText: false,
                    params: {item_id: item_id},
                    success: function(form, action){
                    	var answer = action.result;
                        if (answer.msg) {
                            Ext.Msg.alert('Нева-Центр', answer.msg);
                        }
                        // set values
                        var rowHtml = String.format('<tr id="item_file_row_{3}" class="item_file_row">' +
                        		'<td style="width:250px">{0} ({1})</td>' +
                        		'<td><a href="{2}" target="_blank">Загрузить</a></td>' +
                                '<td><a onclick="deleteFile(\'{4}\',{3})" title="Удалить"><img src="/i/delete.png"></img></a></td>',
                        		answer.type, answer.descr, answer.url, answer.id, answer.item_id);
                        $("#item_file_list").append(rowHtml);
                        Application.stripeRows("item_file_row", false);
                        //alert(answer);
                        win.close();
                    },
                    failure: function(form, action){
                        Ext.Msg.alert('Нева-Центр', action.result.msg);
                        return;
                    }});
            }
        });
                  
        //fs.getForm().load({url:'xml-form.xml', waitMsg:'Loading'});
        win.show();
        
        // retrieve data
       /* Ext.Ajax.request({
                 url: '/get_item_descr'
                ,params: {item_id: item_id}
                ,scope: this
                ,method: 'POST'
                ,callback: function(options, success, response){ 
                    var answer = Ext.util.JSON.decode(response.responseText);
                    if (!success || answer.success == 'false') {
                        Ext.Msg.alert('Нева-Центр', answer.msg);
                        return;
                    } else {
                        if (answer.msg) {
                            Ext.Msg.alert('Нева-Центр', answer.msg);
                        }
                        // set values
                        //fs.items.itemAt(0).setValue(answer.descr);
                        submit.enable();
                    }
                }
        });    */
        submit.enable();
        return win;
    }
/**************************************************************************************************************/
    
    Application.addPhotoForm = function(item_id){
    	//Form items
    	
        var formItems = [{
                    fieldLabel: 'Название',
                    emptyText: 'Название фотографии...',
                    name: 'photoTitle',
                    anchor: '100%'
                },{
                    xtype: 'fileuploadfield',
                    id: 'form-file',
                    emptyText: 'Выберите файл',
                    fieldLabel: 'Файл',
                    name: 'filePath',
                    buttonText: '',
                    anchor: '100%',
                    buttonCfg: {
                        iconCls: 'upload-icon'
                    }
                }];
        
                   
        var fs = new Ext.FormPanel({
            //frame: true,
            baseCls: 'x-plain',
            labelAlign: 'top',
            labelWidth: 125,
            fileUpload: true,
            waitMsgTarget: true,
            border: false,
            autoHeight: true,
            defaultType: 'textfield',
    
            // reusable eror reader class defined at the end of this file
            //errorReader: new Ext.form.XmlErrorReader(),
    
            items: formItems
        });
    
        fs.on({
            actioncomplete: function(form, action){
                if(action.type == 'load'){
                    submit.enable();
                }
            }
        });    
        
        
        win = new Ext.Window({
                //applyTo:'hello-win',
                layout:'fit',
                title:'Добавление фотографии',
                width:350,
                height: 180,
                bodyStyle:'padding:5px;',
                closeAction:'destroy',
                plain: true,
                modal: true,
                items: [fs]
            });
       
        // simple button add
        win.addButton('Отмена', function(){
            win.close();
        });
    
        // explicit add
        var submit = win.addButton({
            text: 'Загрузить',
            disabled:true,
            handler: function(){
                fs.getForm().submit({
                    url:'/save_foto', 
                    waitMsg:'Сохранение...', 
                    submitEmptyText: false,
                    params: {item_id: item_id},
                    success: function(form, action){
                    	var answer = action.result;
                        if (answer.msg) {
                            Ext.Msg.alert('Нева-Центр', answer.msg);
                        }
                        // set values
                        var rowHtml = String.format('<div style="display: inline-block; margin-right: 15px;" id="item_photo_{0}">' +
                        		'<a class="item_photo_link" rel="gallery" href="{3}" title="{4}">' +
                        		'<img src="{2}" style="padding: 2px; border: solid 1px #558;" />' +
                        		'</a><a onclick="deletePhoto(\'{1}\',{0})" title="Удалить"><img src="/i/delete.png"></img></a>' +
                        		'</div>',
                        		answer.image_id, answer.item_id, answer.preview_url, answer.image_url, answer.item_title);
                        $("#item_photo_gallery").append(rowHtml);
                        win.close();
                        Application.bindFancyBox();
                    },
                    failure: function(form, action){
                        Ext.Msg.alert('Нева-Центр', action.result.msg);
                        return;
                    }});
            }
        });
                  
        //fs.getForm().load({url:'xml-form.xml', waitMsg:'Loading'});
        win.show();
        
        submit.enable();
        return win;
    }
/**********************************************************************************************************/
    
    Application.bindFancyBox = function(){
         $(".photo-gallery a.item_photo_link").fancybox({
            'transitionIn'  : 'elastic',
            'transitionOut' : 'fade',
            'speedIn'       : 300, 
            'speedOut'      : 200, 
            'overlayShow'   : true,
            'hideOnContentClick': true,
            'titlePosition' : 'inside',
            'titleShow'     : true,
            'showCloseButton': false
        });
    }
}); // EOF onReady fubction
 



