

       jQuery(document).ready(function(){
     //jQuery('html').pngFix( );
     $(".mirror_block_open").click(function(){ toogle = $(".mirror_block").css('display'); if(toogle == 'block'){ $(".mirror_block").hide(); }else{ dialog_destroy(); dialog($(".mirror_block").html(),400,250);} });
     $("#TB_overlay_close").live("click",function(){dialog_destroy();});


// Создание диалогового окна
function dialog(value,width,height)
{
  $(document).ready(function(){
  	//Тень для диалоговых окон
    if(!$("body").find("#TB_overlay").is("div")) /* если фон уже добавлен не добавляем повторно */
    {
     if(!jQuery.browser.msie) /* если браузер не ИЕ фоном будет div */
     $("body").append("<div id='TB_overlay_div'><div id='TB_overlay_close'></div></div>").append("<div id='TB_overlay'></div>");
     else /* иначе добавляем iframe */
     $("body").append("<div id='TB_overlay_div'><div id='TB_overlay_close'></div></div>").append("<div id='TB_overlay'><iframe id='TB_overlay_iframe' scrolling='no' frameborder='0' style='position: absolute; top: 0; left: 0; width: 100%; height: 100%;filter:alpha(opacity=0)'></iframe></div>");
    }
     $("#TB_overlay_div").css({'width':width,'height':height});
     $("#TB_overlay_div").append(value);

     window_centr('#TB_overlay_div');
     $("#TB_overlay").mousedown(function(){dialog_destroy();});
     $('#TB_overlay_div').corner("20px");
  	});
}
// Центрирование  (диалогового окна)
function window_centr(div_name)
 {
 	$(window).resize(function(){
        $(div_name).css({
			position:'absolute',
			left: ($(window).scrollLeft() + $(window).width() - $(div_name).outerWidth())/2,
			top: ($(window).scrollTop() + ($(window).height() - $(div_name).height())/2)
		});
     });
     $(window).resize();
 }
// Уничтожение диалогового окна
function dialog_destroy()
 {
 	$("#TB_overlay_div").hide().remove(); $("#TB_overlay").hide().remove();

 }

if (jQuery('ul.product_cart').length){product_move();};

jQuery('.your_rating a').live('click', function() {
    obj=$(this);
    if(this.text=='+') {
        rating=1;
    } else {
        rating=-1;
    }
    this_id = $(this).parent('div').attr('id').substr(8);

    jQuery.ajax
            ({
              beforeSend: function()
                {
                },
              type: "POST",
              url: 'http://'+window.location.host+'/comment/changeRating',
              data: {id:this_id,rating:rating},
              cache: false,
              success: function(data)
                {
                rate = parseInt(obj.parent('div').prev().text().replace(/\+/, ''));
                rate = rate + rating;
                if((rate)>0) {
                    rate= '+'+rate;
                }
                obj.parent('div').prev().html(rate);
                obj.parent('div').remove();
                }
            });
   return false;
});

jQuery(".baboo-hover").live("mouseover", function(){
jQuery(this).addClass('hover');
});

jQuery(".baboo-hover").live("mouseout", function(){
jQuery(this).removeClass('hover');
});

//Очистка инпутов
$(function() {
    $.fn.autoClear = function () {
        // сохраняем во внутреннюю переменную текущее значение
        $(this).each(function() {
            $(this).data("autoclear", $(this).attr("value"));
        });
        $(this)
            .bind('focus', function() {   // обработка фокуса
                if ($(this).attr("value") == $(this).data("autoclear")) {
                    $(this).attr("value", "").addClass('autoclear-normalcolor');
                }
            })
            .bind('blur', function() {    // обработка потери фокуса
                if ($(this).attr("value") == "") {
                    $(this).attr("value", $(this).data("autoclear")).removeClass('autoclear-normalcolor');
                }
            });
        return $(this);
    }
});

$(function() {
// привязываем плагин ко всем элементам с классом "autoclear"
    $('.autoclear').autoClear();
});


/*Меню*/
jQuery("td.links ul li a").live("mouseover", function(){
jQuery(this).parent('li').addClass('hover');
});

jQuery("td.links ul li a").live("mouseout", function(){
jQuery(this).parent('li').removeClass('hover');
});
/**/



/*Добавление товара в корзину*/
jQuery(".add_to_basket").live("click", function(){
good_id=jQuery(this).attr('id');
good_id=good_id.substr(6);
var count = jQuery('#count_'+good_id).val();

            jQuery.ajax
            ({
              beforeSend: function()
                {
                },
              type: "POST",
              url: 'http://'+window.location.host+'/shop/basket/add_good',
              data: {good_id:good_id, count:count },
              cache: false,
              success: function(data)
                {
                jQuery('.basket_load').html(data);
                }
            });

this_obj=jQuery(this);
this_obj.hide();
this_obj.next('div').fadeIn(1000,function(){this_obj.next('div').hide(); this_obj.show();});
});
/**/

/*Удаление товара из корзины*/
jQuery(".remove_from_basket").live("click", function(){
good_id=jQuery(this).attr('id');
good_id=good_id.substr(6);

            jQuery.ajax
            ({
              beforeSend: function()
                {
                },
              type: "POST",
              url: 'http://'+window.location.host+'/shop/basket/remove_good',
              data: {good_id:good_id },
              cache: false,
              success: function(data)
                {
                jQuery('.basket_load').html(data);
                }
            });

});
/**/

/*Прибавление товара в корзину*/
jQuery(".plus_to_basket").live("click", function(){
good_id=jQuery(this).attr('id');
good_id=good_id.substr(6);

            jQuery.ajax
            ({
              beforeSend: function()
                {
                },
              type: "POST",
              url: 'http://'+window.location.host+'/shop/basket/plus_good',
              data: {good_id:good_id },
              cache: false,
              success: function(data)
                {
                jQuery('.basket_load').html(data);
                jQuery('.basket_window').show();
                }
            });

});
/**/




/*Показ содержимого корзины*/
jQuery("#basket_detailed").live("click", function(){
if (jQuery('.basket_window').is(':hidden'))
    {
    jQuery('.basket_window').show();
    }
else
    {
    jQuery('.basket_window').hide();
    };
});
jQuery("#close_basket").live("click", function(){
jQuery('.basket_window').hide();
});


$('.open_modal').live("click", function(){
if (jQuery('.another_phone').is(':hidden'))
    {
    jQuery('.another_phone').show();
    }
else
    {
    jQuery('.another_phone').hide();
    };
});

jQuery(".close_modal").live("click", function(){
jQuery('.another_phone').hide();
return false;
});

$('.open_emony').live("click", function(){
this_id = $(this).attr('id').substr(11);
if (jQuery("div[id='emony_"+this_id+"']").is(':hidden'))
    {
    jQuery("div[id='emony_"+this_id+"']").show();
    }
else
    {
    jQuery("div[id='emony_"+this_id+"']").hide();
    };
});

$('.close_emoney').live("click", function(){
$(this).parents('.emoney').hide();
return false;
});



 /*Показ окна с картой*/

$('#ship_cost').live("click", function(){
if (jQuery('#map_popup').is('hide'))
    {
    $("#map_popup").addClass('show');
    }
else
    {
    $("#map_popup").removeClass('hide');
    };

});

$('#close_map_popup').live("click", function(){
$("#map_popup").addClass('hide');
return false;
});





/*Отправка формы*/
jQuery('input[name="submit"]').live("click", function(){      submit_form(); return false;});
jQuery('input[name="send"]').live("click", function(){      submit_form(); return false;});
/**/

       });

//Обновление корпзины
function update_basket()
    {
            jQuery.ajax
            ({
              beforeSend: function()
                {
                },
              type: "POST",
              url: 'http://'+window.location.host+'/shop/basket/load',
              data: {},
              cache: false,
              success: function(data)
                {
                jQuery('.basket_load').html(data);
                }
            });
    };



//*Основная функция отправки формы*//
function submit_form(callback)
    {

    //setTimeout(function(){submit_form();},2000);
    //Переписываем WYSIWYG в textarea поля для отправки
            if (jQuery("#form_edit textarea[name^='wysiwyg']").length )
                {
                jQuery("#form_edit textarea[name^='wysiwyg']").each(function ()
                    {
                    var wysiwyg_id=jQuery(this).next('input').attr('value');
                    jQuery(this).attr('value',tinyMCE.get(wysiwyg_id).getContent());
                    });
                };
    //


    var options_form_dtable = {
      target:'.form_edit-result',
      type:'POST',
      beforeSubmit:function() {
      $('#form_edit input[type="submit"]').attr('disabled','disabled');
      $('.form_edit-result').html('<div class="loader-small"></div>');
      },
      success: function() {
      if (jQuery('li.form_messages-error').length==0)
        {
          if (jQuery('#form_edit').hasClass('comment-form'))
            {
            $('#form_edit input[type="submit"]').removeAttr('disabled');
            update_comment(jQuery('#comment_page_number').val()+'_'+jQuery('#comment_on_page').val(),'max');
            }; //обновление комментариев
          if (jQuery('#form_edit').hasClass('new_comment-form')){
                  if (jQuery("#form_edit textarea[name^='wysiwyg']").length )
                    {
                    jQuery("#form_edit textarea[name^='wysiwyg']").each(function ()
                        {
                        var wysiwyg_id=jQuery(this).next('input').attr('value');
                        tinyMCE.get(wysiwyg_id).setContent('');
                        });
                    };
           };
        if ($('input[name="callback"]').length){eval($('input[name="callback"]').val());};
        if ($("#dialog").length){$("#dialog").dialog('close');};
        }
      else
        {
        $('#form_edit input[type="submit"]').removeAttr('disabled');
        };

      }
    };
        jQuery('#form_edit').ajaxSubmit(options_form_dtable);
    };



//��������� ����������� �����
function implode (glue, pieces) {
    var i = '', retVal='', tGlue='';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (pieces instanceof Array) {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    }
    else {
        return pieces;
    }
}




function product_move(){
    jQuery(function() {
        jQuery(".product_cart").sortable({
        revert: true
        });




       jQuery('.product_cart').bind('sortupdate', function(event, ui) {

       task_id_array= new Array();
       task_pos_array= new Array();
       ui.item.parent('ul').children('li').each(function ()
            {
            var id=jQuery(this).children('input[name="pos"]').attr('id'); id=id.substr(5);
            var pos=jQuery(this).children('input[name="pos"]').val();
            task_id_array[task_id_array.length]=id;
            task_pos_array[task_pos_array.length]=task_pos_array.length;
            });
       task_id_array_implode=implode(',',task_id_array);
       task_pos_array_implode=implode(',',task_pos_array);
       //task_pos_array_implode=$('.product_cart').sortable('serialize');


           jQuery.ajax
            ({
              beforeSend: function()
                {
                },
              type: "POST",
               url:  'http://'+window.location.host+'/shop/sortable',
              data: { task_id:task_id_array_implode,task_pos:task_pos_array_implode },
              cache: false,
              success: function(data)
                {
                   //alert(data);
                }
            });


        });




    });
}





