//VOTING
function voting(id)
{
    var quote;
    quote = $('#'+id).serialize();
    if(quote=='') alert('Выберите ответ');
    else
    {
         $.ajax({
           type: "POST",
           url: "/ajax",
           data: "vote=add_vote&" + quote,
           success: function(msg){
                  if(msg.substr(0,1)=='1')
                  {
                        $('#voting_wrap').html(' ');
                        $('#voting_result').show();
                        $('#voting_result').html(msg.substr(1));
                  }
                  else alert(msg);
           }
         });
    }
}

function showVotingRes()
{
    $.ajax({
        type: "POST",
        url: "/ajax",
        data: "vote=show_result",
        success: function(msg){
               if(msg.substr(0,1)=='1')
               {
                    $('#voting_wrap').hide();
                    $('#voting_result').show();
                    $('#voting_result').html(msg.substr(1));
               }
               else alert(msg);
         }
     });
}

function back()
{
      $('#voting_wrap').show();
      $('#voting_result').hide();
}
//END VOTING

//MESSAGES
function showMsg(msg, type) {

if(type==1) type = 'ok';
if(type==0) type = 'err';

    $('#mesBox').remove();
    $('#msgWrap').prepend('<div id="mesBox" class="mesBox '+type+'">'+msg+'</div>');
    $('#mesBox').show("slow").dblclick(function(){
        $(this).slideUp();
    });
    return false;
}

$(document).ready(function(){
        $('#mesBox').show("slow").dblclick(function(){
            $(this).slideUp();
        });
});

//CART
function add2cart(id,obj)
{
    if(obj.hasClass('btn_blue_fixed')) return false;
    $.ajax({
        type: "POST",
        url: "/ajax",
        data: "cart=add&id="+id,
        async: false,
        success: function(msg){
               if(msg.substr(0,1)=='1')
               {
                    //showMsg('Продукт добавлен в корзину',1);
                    //alert(msg.substr(1));
                    var count = parseInt($('#cart_count').html());
                    $('#cart_count').html(count+1);
                    var summ = msg.substr(2);
                    $('#cart_summ').html(summ);

                    $(obj).attr('class','btn_blue_fixed').attr('title','товар был отправлен в корзину').html('Добавлен');
                    //setTimeout(moveScroll,500);
               }
               else showMsg(msg,0);
         }
     });
     return false;
}

function moveScroll()
{
    var s = $(document).scrollTop();
    if (s<=0) return false;
    $(document).scrollTop(s-15);
    setTimeout(moveScroll,1);
}

function recalculate(obj,id)
{
    var count = parseInt($(obj).val());
    if(count<1||count>1000||isNaN(count)) return false;
    //alert(parseInt(count));
    var price = $('#product_price_'+id).html();
    var summ  = $('#product_summ_'+id).html();
    $('#product_summ_'+id).html(number_format(count*price,2,'.',''));
    var all_summ = $('#summ').html();
    $('#summ').html(number_format(all_summ-summ+count*price,2,'.',''));

    var price_discount = $('#product_price_discount_'+id).html();
    var summ_discount  = $('#product_summ_discount_'+id).html();
    if(parseInt(price_discount)<1) price_discount = price;
    $('#product_summ_discount_'+id).html(number_format(count*price_discount,2,'.',''));
    var all_summ_discount = $('#summ_discount').html();
    $('#summ_discount').html(number_format(all_summ_discount-summ_discount+count*price_discount,2,'.',''));

}

function checkUrl(sour,dest)
{
        var url = document.getElementById(sour).value;
        var url = url.toLowerCase();
        var url = url.replace(/\s+/g, "-");
        var url = translit(url);
        var url = url.replace(/[^a-z0-9_-]/g,"");
        document.getElementById(dest).value = url;
}

function translit(sear) {
 	var trans = {
		"а":"a", "б":"b", "в":"v", "г":"g", "д":"d", "е":"e", "ё":"e", "ж":"j", "з":"z", "и":"i", "й":"i", "ы":"i",  "к":"k", "л":"l", "м":"m", "н":"n", "о":"o", "п":"p", "р":"r", "с":"s", "т":"t", "у":"y", "ф":"f", "х":"x", "ц":"c", "ч":"ch", "ш":"sh", "щ":"sh", "ь":"", "ъ":"", "э":"e", "ю":"u", "я":"ya",
		"А":"A", "Б":"B", "В":"V", "Г":"G", "Д":"D", "Е":"E", "Ё":"E", "Ж":"J", "З":"Z", "И":"I", "Й":"i", "Ы":"I", "К":"K", "Л":"L", "М":"M", "Н":"N", "О":"O", "П":"P", "Р":"R", "С":"S", "Т":"T", "У":"Y", "Ф":"F", "Х":"X", "Ц":"C", "Ч":"CH", "Ш":"SH", "Щ":"SH", "Ь":"", "Ъ":"", "Э":"E", "Ю":"U", "Я":"YA"};
    var eng="";
    for (var pos=0; pos < sear.length; pos++)
     {
          var repl = sear.substr(pos,1);
          var extr = trans[repl];
              if (extr==undefined) {var extr = repl;}
           var eng = eng + extr;
	 }
          return eng;
}

//PRODUCT IMAGEs
//function change

//SLIDER
var slideWidth = 215;
var t;
var animate = 0;

function slider_init()
{
    var slider = $('#slider_container');
    var count = slider.find('.slide').length;
    if(count<4) return false;
    slider.css('width',slideWidth*count+30+'px');
    t = setTimeout(function(){slider_move(0)},5000);
}

function slider_move(direction)
{
    var slider = $('#slider_container');
    animate = 1;
    if(direction==1)
    {
        slider.find('.slide:last').prependTo('#slider_container').parent().css('left','-'+slideWidth+'px');
        slider.animate({left:'0px'},1000,'swing',function(){
            animate = 0;
            t = setTimeout(function(){slider_move(1)},5000);
        });
    }
    else
    {
        slider.animate({left:'-'+slideWidth+'px'},1000,'swing',function(){
            slider.find('.slide:first').appendTo('#slider_container').parent().css('left','0px');
            animate = 0;
            t = setTimeout(function(){slider_move(0)},5000);
        });
    }
}

function slider_click(direction)
{
    if(animate==0)
    {
        var count = $('#slider_container .slide').length;
        if(count<4) return false;

        clearTimeout(t);
        if(direction==1) slider_move(1);
        else             slider_move(0);
    }
}

var product_id = 0;

$(document).ready(function(){

    /* LOGIN BOX */
     var obj = $('#login_bg');
     $('#login_toggle').click(function(){
          if($(obj).css('bottom')=='0px') $(obj).animate({bottom:'62px'});
          else $(obj).animate({bottom:'0px'});
     });

     /* MENU POPUP */
     $('.menu_wrap').mouseover(function(){
             $('.popup').hide();
             $(this).find('.popup').show();
     });

     $('.menu_wrap').mouseout(function(){
             $(this).find('.popup').hide();
     });

     /* SLIDER */
     slider_init();
     $('#slider_left_btn').click(function(){slider_click(1)});
     $('#slider_right_btn').click(function(){slider_click(0)});

     if(product_id&&already_rated=="0")
     {   /* STARS */
         $('.starsOne span').css('cursor','pointer');

         $('.starsOne span').hover(
              function(){
                 var index = $(this).parent().find('span').index(this);
                 $(this).parent().find('span:lt('+(index+1)+')').addClass('hover1');
                 $(this).parent().find('span:gt('+(index)+')').addClass('hover0');
              },
              function(){
                 $(this).parent().find('span').removeClass('hover1').removeClass('hover0');
              }
         );

         /* RATING */
         $('.starsOne span').click(function(){

              var index = $(this).parent().find('span').index(this);
              $.ajax({
                  type: "POST",
                  url: "/ajax",
                  data: "rate="+(index+1)+"&id="+product_id,
                  async: false,
                  success: function(msg){
                         if(msg.substr(0,1)=='1')
                         {
                              $('.starsOne span').unbind('mouseenter').unbind('mouseleave').unbind('click').css('cursor','default');
                              showMsg('Ваш голос засчитан',1);
                         }
                         else if (msg=='') {}
                         else showMsg(msg,0);
                   }
               });
               return false;
         });
     }
});

     //FOR FANCYBOX
$(document).ready(function(){
     $("a.fancybox").fancybox({
         onComplete: function()  { clearTimeout(t); },
         onClosed: function() { t = setTimeout(function(){slider_move(0)},5000);}

     });
});


function number_format( number, decimals, dec_point, thousands_sep ) {
    // Formats a number with grouped thousands
    //
    // version: 902.1517
    // discuss at: http://phpjs.org/functions/number_format
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // %        note 1: For 1000.55 result with precision 1 in FF/Opera is 1,000.5, but in IE is 1,000.6
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;

    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;

    var abs = Math.abs(n).toFixed(prec);
    var _, i;

    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;

        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');

        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }

    return s;
}
