$.fn.setCursorPosition = function(position){
    if(this.lengh == 0) return this;
    return $(this).setSelection(position, position);
}

$.fn.setSelection = function(selectionStart, selectionEnd) {
    if(this.lengh == 0) return this;
    input = this[0];

    if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    } else if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }

    return this;
}

$.fn.focusEnd = function(){
    this.setCursorPosition(this.val().length);
}


jQuery(document).ready(function()
{
if ($('.filtr_price_list').length){filtr_price();};

if(jQuery('input[name="card"]').length){card_image();};
if (jQuery('.calculate-sum').length){calculate_sum();};

//изменения внутри товара
jQuery('.amount input').keyup(function(e) { e.target.value = e.target.value.replace(/[^\d,]/g, ''); calculate_sum();});
jQuery('.amount input').click(function() {calculate_sum();});
jQuery('.amount input').blur(function(e) {
	if(e.target.value == '' || parseInt(e.target.value) == 0) {
		alert('Вы ввели неверное количество. Чтобы удалить товар из корзины нажмите кнопку "Удалить"');
		e.target.value = 1;
	}
	calculate_sum();});

//изменения в угловой корзине
$('.basket_product_count').live('keyup', function() {
	id = $(this).attr('id').substr(6);

	this_count = $(this).val().replace(/[^\d,]/g, '');
	index = $('.basket_product_count').index(this);
	if(parseInt(this_count)) {
	$.ajax({
              type: "POST",
              url: 'http://'+window.location.host+'/shop/basket/change_good_count',
              data: {id:id, count:this_count},
              cache: false,
              success: function(data) {
		jQuery('.basket_load').html(data);
		jQuery('.basket_window').show();

		//$('.basket_product_count:eq('+index+')').focus();
		//a = parseInt($('.basket_product_count:eq('+index+')').val());
        //$('.basket_product_count:eq('+index+')').val(9);
        //$('.basket_product_count:eq('+index+')').val(a);
        $('.basket_product_count:eq('+index+')').focusEnd();

		}
            });
	}
});

function to_end(el) {
            var len = el.value.length || 0;
            if (len) {
                if ('setSelectionRange' in el) el.setSelectionRange(len, len);
                else if ('createTextRange' in el) {// for IE
                    var range = el.createTextRange();
                    range.moveStart('character', len);
                    range.select();
                }
            }
        }


function sendCursorToEnd(obj) {
    var value =  $(obj).val(); //store the value of the element
    var message = "";
    if (value != "") {
        message = value;
     };
    $(obj).focus().val(message);
    $(obj).unbind();
 }


//Изменение данных в input
jQuery('input.calculate-input').keyup(function(e) { e.target.value = e.target.value.replace(/[^\d,]/g, ''); calculate_sum();});
jQuery('input.calculate-input').click(function() {calculate_sum();});
jQuery('input.calculate-input').blur(function(e) {
	if(e.target.value == '' || parseInt(e.target.value) == 0) {
		alert('Вы ввели неверное количество. Чтобы удалить товар из корзины нажмите кнопку "Удалить"');
		e.target.value = 1;
	}
	calculate_sum();});


/*Фильтр по ценам*/
jQuery(".filtr_price_list .c1").live("click", function(){
if ($(this).hasClass('active'))
    {
    $(this).removeClass('active');
    }
else
    {
    jQuery(".filtr_price_list .c1").removeClass('active');
    $(this).addClass('active');
    this_pc=$(this).attr('id');this_pc=this_pc.substr(3);
    $('.good_li').hide();
    jQuery(".input_good_price").each(function ()
    {
        if (this_pc=='500' && $(this).val()>0 && $(this).val()<=500){$(this).parent('li').show();};
        if (this_pc=='1000' && $(this).val()>500 && $(this).val()<=1000){$(this).parent('li').show();};
        if (this_pc=='2000' && $(this).val()>1000 && $(this).val()<=2000){$(this).parent('li').show();};
        if (this_pc=='5000' && $(this).val()>2000 && $(this).val()<=5000){$(this).parent('li').show();};
    });
    };

});



//Выбор типа товара на странице товара
jQuery('.good-img-border').hide();
jQuery('.good-img-border:first').show();
jQuery('.good_type-title:first').addClass('good_type-selected');

jQuery(".good_type-title span").live("click", function(){
    this_id=jQuery(this).attr('id');
    this_id=this_id.substr(10);
    window.location.hash=this_id;
    jQuery('.good-img-border').hide();
    jQuery('.good_type-title').removeClass('good_type-selected');
    jQuery(this).parent('td').addClass('good_type-selected');
    jQuery('#good_type_img_'+this_id).show();
    price=jQuery(this).parent('td').next('td').html();

    jQuery('.amount .cena').html(price);
    $('.good_button').attr('id','agood_'+this_id);
})

if ($('.good').length && window.location.hash!='')
    {
    this_id=window.location.hash;
    this_id=this_id.substr(1);
    $('#good_type_'+this_id).click();
    };
//




//Галочка "Упаковать"
jQuery('#packing').change(function() {
if (jQuery(this).is(':checked'))
    {
    jQuery('#calculate_input_0').val(1);
    jQuery('#deliver_packing_tr').show();
    }
else
    {
    jQuery('#calculate_input_0').val(0);
    jQuery('#deliver_packing_tr').hide();
    };
calculate_sum();
});
//

//Галочка "Добавить открытку"
jQuery('#add_card').change(function() {
if (jQuery(this).is(':checked'))
    {
    jQuery('#add_card_window').show();
    jQuery('#add_card_tr').show();
    }
else
    {
    jQuery('#add_card_window').hide();
    jQuery('#add_card_tr').hide();
    };
});
//


//Выбор способа получения заказа
jQuery('input[name="reception"]:eq(0)').change(function() {obj=$(this);
jQuery('.reception').hide();
jQuery('#reception').show();
district_change();
obj.val(jQuery('select[name=district]').children('option:selected').attr('id').substr(5));
jQuery('#reception_title_view').html(jQuery('select[name=district]').children('option:selected').text());

calculate_sum();
validation();
reception_view();
});

jQuery('input[name="reception"]:eq(1)').change(function() {obj=$(this);
jQuery('.reception').hide();
jQuery('#reception_office').show();
jQuery('.reception_pay_view').html(0);
obj.val(0);
calculate_sum();
validation();
reception_view();
});

jQuery('select[name=district]').change(function() {obj=$(this);
jQuery('input[name="reception"]:eq(0)').attr('checked','checked');
district_change();
/*jQuery('.reception_pay_view').html(jQuery('select[name=district]').children('option:selected').val());*/
jQuery('#reception_title_view').html(jQuery('select[name=district]').children('option:selected').text());
calculate_sum();
validation();
reception_view();
});
//



//Выбор способа оплаты
jQuery('input[name="paytype"]').change(function() {
this_val=jQuery(this).val();
jQuery('.paytype').hide();
jQuery('#paytype_'+this_val).show();
jQuery('.paytype_pay_view').html(jQuery('#paytype_pay_'+this_val).html());
jQuery('#paytype_title_view').html(jQuery('#paytype_title_'+this_val).html() );
if (jQuery('#paytype_pay_'+this_val).html()!='0')
    {
    jQuery('#paytype_tr').show();
    }
else
    {
    jQuery('#paytype_tr').hide();
    };
validation();
calculate_sum();
});
//


//Доставить в подарочной упаковке окошечко

jQuery('#deliver_packing').click(function() {jQuery('#deliver_packing_window').toggle();});
jQuery('#deliver_packing_close').click(function() {jQuery('#deliver_packing_window').hide();});
//


/*Навигация по страницам*/
jQuery('.next_page').click(function() {
this_id=jQuery('.lenta span.active').attr('id');
this_id=this_id.substr(4);
this_id=new Number(this_id);
view_id=this_id+1;

if (jQuery('#tab_'+view_id).length)
    {
    jQuery('.lenta span').removeClass('active');
    jQuery('#tab_'+view_id).addClass('active');
    jQuery('.pages').hide();
    jQuery('#page_'+view_id).show();
    };
validation();
district_change();
reception_view();
window.scrollTo(0, 0);
});

jQuery('.prev_page').click(function() {
this_id=jQuery('.lenta span.active').attr('id');
this_id=this_id.substr(4);
this_id=new Number(this_id);
view_id=this_id-1;

if (jQuery('#tab_'+view_id).length)
    {
    jQuery('.lenta span').removeClass('active');
    jQuery('#tab_'+view_id).addClass('active');
    jQuery('.pages').hide();
    jQuery('#page_'+view_id).show();
    };
validation();
paytype_view();
window.scrollTo(0, 0);
});
/**/

/*Текст открытки*/
jQuery('textarea[name="card_text"]').keyup(function() {view_card_text();});
jQuery('textarea[name="card_text"]').click(function() {view_card_text();});
jQuery('textarea[name="card_text"]').blur(function() {view_card_text();});
/**/

/*Имя*/
jQuery('input[name="username"]').keyup(function() {jQuery('#username').html(jQuery('input[name="username"]').val());});
jQuery('input[name="username"]').click(function() {jQuery('#username').html(jQuery('input[name="username"]').val());});
jQuery('input[name="username"]').blur(function() {jQuery('#username').html(jQuery('input[name="username"]').val());});
/**/

/*Телефон*/
jQuery('input[name="telephone"]').keyup(function() {jQuery('#telephone').html(jQuery('input[name="telephone"]').val());});
jQuery('input[name="telephone"]').click(function() {jQuery('#telephone').html(jQuery('input[name="telephone"]').val());});
jQuery('input[name="telephone"]').blur(function() {jQuery('#telephone').html(jQuery('input[name="telephone"]').val());});
/**/

/*Адрес доставки*/
jQuery('input.reception_class').keyup(function() {reception_view();validation();});
jQuery('input.reception_class').click(function() {reception_view();validation();});
jQuery('input.reception_class').blur(function() {reception_view();validation();});
/**/

/*Способ оплаты*/
jQuery('input.paytype_class').keyup(function() {paytype_view();validation();});
jQuery('input.paytype_class').click(function() {paytype_view();validation();});
jQuery('input.paytype_class').blur(function() {paytype_view();validation();});
/**/


/*Проверка обязательных полей*/
jQuery('.obligatory').keyup(function() {validation();});
jQuery('.obligatory').click(function() {validation();});
jQuery('.obligatory').blur(function() {validation();});
/**/

//выбор открытки
jQuery('input[name="card"]').change(function() {card_image();});

// ++++ Удаление позиции товара из корзины
jQuery('.recycle_minus').live('click',function() {
   id = $(this).attr('id').substr(8);
   $.ajax({
              type: "POST",
              url: 'http://'+window.location.host+'/shop/basket/remove_one_good',
              data: {pos_id:id},
              cache: false,
              success: function(data) {
		jQuery('.basket_load').html(data);
		jQuery('.basket_window').show();
		}
            });
});

//удаление позиции товара
jQuery('.remove_position').click(function() {
was_do=0;
redirect=0;
    pos_id=jQuery(this).attr('id');
    pos_id=pos_id.substr(16);
if (jQuery('.remove_position').length==1)
    {
if (confirm('Действительно удалить оставшийся товар ?')) {was_do=1;redirect=1;};
    }
else
    {
    was_do=1;
    jQuery('.position_'+pos_id).remove();
    calculate_sum();
    };

if (was_do==1)
    {
            jQuery.ajax
            ({
              beforeSend: function()
                {
                },
              type: "POST",
              url: 'http://'+window.location.host+'/shop/basket/remove_one_good',
              data: {pos_id:pos_id},
              cache: false,
              success: function(data)
                {
                jQuery('.basket_load').html(data);
                if (redirect==1)
                    {
                    window.location='.';
                    };
                }
            });
    };

});

//


});

function district_change() {
    if(jQuery('input[name="reception"]:eq(0)').is(':checked')) {
        id = jQuery('select[name=district]').children('option:selected').attr('id').substr(5);
        sum = jQuery('.calculate-sum:eq(1)').text();
        cost = jQuery('select[name=district]').children('option:selected').val();
        free = jQuery('.free_table').children('input[id="dstrt_'+id+'"]').val();
        if(parseFloat(sum)>parseFloat(free) && free!=0) {cost = 0;}
        /*alert('sum:'+sum+' cost:'+cost+' free:'+free);*/
        jQuery('.reception_pay_view').html(cost);
        jQuery('select[name=district]').parent('li').prev().find('input[type=radio]').val(jQuery('select[name=district]').children('option:selected').attr('id').substr(5));
    }
}

//подсчёт итоговой суммы
function calculate_sum()
    {
    sum=0;
    jQuery(".calculate-slog").each(function ()
    {
     this_sum=jQuery(this).html();
     slog_id=jQuery(this).attr('id');
     slog_id=slog_id.substr(15);
	count = parseInt(jQuery('#calculate_input_'+slog_id).val());/*
if(count<1 || (isNaN(count) && jQuery('#calculate_input_'+slog_id).val()!='')) {
//
jQuery('#calculate_input_'+slog_id).val(1);
count = 1;
alert('Вы ввели неверное количество. Чтобы удалить товар из корзины нажмите кнопку "Удалить"');
jQuery('#calculate_input_'+slog_id).live('click');
calculate_sum();
}*/
     if (jQuery('#calculate_input_'+slog_id).length){this_sum=this_sum*count;};
     jQuery('#calculate_number_'+slog_id).html(jQuery('#calculate_input_'+slog_id).val());
     sum=sum+this_sum;
     });
     jQuery('.calculate-sum').html(sum);

      district_change();

     calculate_sum_finish=jQuery('#calculate_sum_finish').html();
     var calculate_sum_finish=new Number(calculate_sum_finish);



     reception_pay_view=jQuery('.reception_pay_view').html();reception_pay_view=new Number(reception_pay_view);
     paytype_pay_view=jQuery('.paytype_pay_view').html();paytype_pay_view=new Number(paytype_pay_view);
     calculate_sum_finish=calculate_sum_finish+reception_pay_view+paytype_pay_view;
     calculate_sum_finish=jQuery('#calculate_sum_finish').html(calculate_sum_finish);

    };


/*копирование текста открытки*/
function view_card_text()
    {
    text_val=jQuery('textarea[name="card_text"]').val();
    text_val=text_val.replace(/<\/?[^>]+>/g, '');
    jQuery('#card_text_view').html(text_val);
    }

/*Показ картинки выбранной открытки*/
function card_image()
    {
    card_id=jQuery('input[name="card"]:checked').val();
    jQuery('#card_image_view').html(jQuery('#card_image_'+card_id).html());
    jQuery('#card_title_view').html(jQuery('#card_title_'+card_id).html());
    jQuery('#card_image_view img').width(100);
    }


function validation()
    {
    empty=false;
    jQuery(".obligatory:visible").each(function ()
    {
    if (jQuery(this).val()==''){empty=true;};
    });
    if (empty==true)
        {
        jQuery('.next_page:visible').prev('span').html('Заполните поля, отмеченные <b>*</b> ');
        jQuery('.next_page:visible').attr('disabled','disabled');
        }
    else
        {
        jQuery('.next_page:visible').prev('span').html('');
        jQuery('.next_page:visible').removeAttr('disabled');
        };

    }




function reception_view()
    {
    this_val=jQuery('input[name="reception"]:checked').val();
    reception_view_text='';
    if (this_val!='0' || this_val=='2' || this_val=='4' || this_val=='5'){
    reception_view_text="<strong>Доставка курьером</strong> ("+jQuery('option[id="dstr_'+this_val+'"]').html()+")<br /><strong>Дата и время доставки:</strong> "+jQuery('input[name="reception_date_1"]').val()+"<br />";
    };

    if (this_val=='0'){
    reception_view_text="<strong>Получение в офисе:</strong> ул.Техническая, 18Б<br /><strong>Дата и время получения:</strong> "+jQuery('input[name="reception_0"]').val()+"<br />";
    };
    jQuery('#reception_title_view').html(reception_view_text);
    jQuery('#reception_view').html(reception_view_text);
    }



function paytype_view()
    {
    this_val=jQuery('input[name="paytype"]:checked').val();
    paytype_view_text='';
    if (this_val=='1'){
    paytype_view_text="Наличный расчёт";
    };

    if (this_val=='2'){
    paytype_view_text="Вызов курьера для оплаты наличными. "+jQuery('input[name="paytype_2_address"]').val()+" ("+jQuery('input[name="paytype_2_time"]').val()+")";
    };

    if (this_val=='3'){
    paytype_view_text="Электронные деньги";
    };

    if (this_val=='4'){
    paytype_view_text="Оплата через терминал";
    };

    if (this_val=='5'){
    paytype_view_text="Банковский перевод";
    };

    jQuery('#paytype_view').html(paytype_view_text);
    }




function filtr_price()
    {
    //$('.filtr_price_list').remove();
    var pc_500=false;
    var pc_1000=false;
    var pc_2000=false;
    var pc_5000=false;

    jQuery(".input_good_price").each(function ()
    {
        if ($(this).val()>0 && $(this).val()<=500){$('#pc_500').attr('class','c1');};
        if ($(this).val()>500 && $(this).val()<=1000){$('#pc_1000').attr('class','c1');};
        if ($(this).val()>1000 && $(this).val()<=2000){$('#pc_2000').attr('class','c1');};
        if ($(this).val()>2000 && $(this).val()<=5000){$('#pc_5000').attr('class','c1');};
    });

    }

