var product_id = 0;

$(document).ready(function(){
	$('#mesBox').show("slow").dblclick(function(){
		$(this).slideUp();
	});
	
    /* LOGIN BOX */
     var obj = $('.login_form');
     $('#login_toggle').click(function(){
          if($(obj).css('top')=='0px') $(obj).animate({top:'-61px'});
          else $(obj).animate({top:'0px'});
     });

     /* SLIDER */
     slider_init();
     $('.slide_left').click(function(){slider_click(1)});
     $('.slide_right').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(str_vote_counted, 1);
                         }
                         else if (msg=='') {}
                         else showMsg(msg,0);
                   }
               });
               return false;
         });
     }
     
     
     $("a.fancybox").fancybox({
         callbackOnShow: function()  { clearTimeout(t); },
         callbackOnClose: function() { t = setTimeout(function(){slider_move(0)},5000);}
     });
     
     
     $('#menu .item').hover (
     	function () {
     		$(this).children('.top_submenu').css('display', 'block');
     	}, 
     	function () {
     		$(this).children('.top_submenu').css('display', 'none');
     	}
     );
});



//VOTING
function submit_voting(id, lang)
{   
    var quote;
    quote = $('#'+id).serialize();
    if(quote=='') alert(str_choose_answer);
    else
    {
         $.ajax({
           type: "POST",
           url: "/ajax",
           data: "vote=add_vote&"+quote+"&lang="+lang,
           success: function(msg){
                  if(msg.substr(0,1)=='1')
                  {
                        $('#voting_wrap').html('').hide();
                        $('#voting_result').show();
                        $('#voting_result').html(msg.substr(1));
                  }
                  else alert(msg);
           }
         });
    }
}

function showVotingRes(lang)
{
    $.ajax({
        type: "POST",
        url: "/ajax",
        data: "vote=show_result&lang="+lang,
        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;
}

//CART
function add2cart(id, obj, text)
{
    $.ajax({
        type: "POST",
        url: "/ajax",
        data: "cart=add&id="+id,
        async: false,
        success: function(msg){
			if(msg.substr(0, 1) == '1') {
				var count = parseInt($('#cart_count').html());
				$('#cart_count').html(count+1);
				var summ = msg.substr(2);
				$('#cart_summ').html(summ);
				
				var className = obj.attr('class');
				var addClassName = '';
				if (className) {
					addClassName = ' class="'+className+'"';
				}
				
				obj.replaceWith('<span'+addClassName+' title="'+str_product_has_been_added+'">'+text+'</span>');
			} 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 all_count = 0;
	var this_count = 0;
	$('.products_counts', $('.cart_table')).each( function () {
		this_count = parseInt(this.value);
		if (!isNaN(this_count)) {
			all_count += this_count;
		}
	});
	
    var count = parseInt($(obj).val());
    if(isNaN(count)) count = 0;
    //alert(parseInt(count));
    var price = $('#product_price_'+id).html();
    var second_price = $('#product_second_price_'+id).html();
    var summ  = $('#product_summ_'+id).html();
    var second_summ  = $('#product_second_summ_'+id).html();
    
    $('#product_summ_'+id).html(number_format(count*price, 2, '.', ''));
    $('#product_second_summ_'+id).html(number_format(count*second_price, 2, '.', ''));
    var all_summ = $('#summ').html();
    var all_second_summ = $('#second_summ').html();
    $('#summ').html(number_format(all_summ-summ+count*price, 2, '.', ''));
    $('#second_summ').html(number_format(all_second_summ-second_summ+count*second_price, 2, '.', ''));
    
    $('#count').html(all_count);
}


//PRODUCT IMAGEs
//function change

//SLIDER
var slideWidth = 150;
var t;
var animate = 0;
var slides_count = 5;

function slider_init()
{
    var slider = $('.slider_container');
    var count = slider.find('.slide').length;
    if(count<slides_count) return false;
    slider.css('width',slideWidth*count+12+'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<slides_count) return false;

        clearTimeout(t);
        if(direction==1) slider_move(1);
        else             slider_move(0);
    }
}

function getCities (country_id) {
	$.ajax({
        type: "POST",
        url: "/ajax",
        data: "act=get_cities&country_id="+country_id,
        success: function(result){
        	$('#city_select_block').html(result);
			$('#city_block').show();
         }
     });
}


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;
}