var flag_a_i = false;

function index_anim()
{
	if (!flag_a_i)
	{
	$('.img2').animate({
    opacity: 0
  }, 2000, function() {
    index_anim();
  }).delay(5000);
  
  flag_a_i = true;
  }
  else
  {
	$('.img2').animate({
    opacity: 1
  }, 2000, function() {
    index_anim();
  }).delay(5000);
  
  flag_a_i = false;
  }

}

$(document).ready(function() {

	//index animation. sam, deepllc
	
	 index_anim();
	
	//end
	
	blink();

	var position = $('div.menu').position();
    var offset = $('div.menu').offset();
    
    if($('div.menu li.active').length) {	
		var startPos = $('div.menu li.active').position().left;
		$('#logo').css('left', startPos + 'px');
    }
	
	var semaphore = true; //Im using this var to block an animation in case of mouseleave event goes
	
	$('.menu').mousemove(function(e){
	     
	  //   $('#curPos').html('Position<br>Doc: '+e.pageX+','+e.pageY+'<br>Div: '+x+','+y);
						
		if (semaphore && e.pageX < 720) { var x = e.pageX - (offset.left) - 15; $('#logo').css('left', x + 'px'); }
	});
	
	$('.menu').mouseleave(function(){
		if (semaphore)
		{
			semaphore = false;
			$('#logo').animate({left: 0}, 2500, function(){semaphore = true;});
		}
	});
	
	

	//placholder кроссбраузерный
	$('.placeholder P').click(function(){
		$(this).children('label').hide();
		$(this).children('input').focus();
		$(this).children('textarea').focus();
    });
    $('.placeholder input').focus(function(){
		$(this).next('label').hide();
    });
    $('.placeholder input').focusout(function(){
    	if($(this).val() == "")
	    	$(this).next().show();
    });
    $('.placeholder input').each(function(){
    	if($(this).val() == "")
	    	$(this).next().show(); 	
    });
    $('.placeholder textarea').focus(function(){
		$(this).next('label').hide();
    });
    $('.placeholder textarea').focusout(function(){
    	if($(this).val() == "")
	    	$(this).next().show(); 	
    });
    $('.placeholder textarea').each(function(){
    	if($(this).val() == "")
	    	$(this).next().show(); 	
    });
    
    $('.region-choose #man-list a').click( function(){
    	var h = $(this).attr('href');
    	var re = /c_action=set/i;
    	if ( /^\//.test( h ) && (re.exec( h ) != null) ) {
    		setCookie("karexcity", $(this).text(), {expires: 31536000, path: "/"} );
    	}
    });

    var showAjaxBasket = function(resp) {
        alert(resp);
    }

    $('.related-products .ajax').bind('click', function(ev) {
        ev.preventDefault();
        var pid = $(this).attr('data-id');
        $.ajax({
            type: 'POST',
            url: "/ajax/add2basket.php",
            data: {pid: pid},
            success: showAjaxBasket
        });

    });

    
});

var bl_state = false;

function blink()
{
	if (bl_state == false)
	{
		$('#blink').animate({opacity: 1}, 1000, function(){
			bl_state = true; blink();
		});
	}
	
	if (bl_state == true)
	{
		$('#blink').animate({opacity: 0}, 500, function(){
			bl_state = false; blink();
		});
	}
}


function popup(container) {
    var $container=$(container);
    
    if ($container.length) {
        var $popup = $('#popup');
        if (!$popup.length) {
            $('<div id="popup-bg"></div><div id="popup"></div>').hide().appendTo('body');
            $('#popup-bg').css({
                height:$('body').height()+'px',
                width:$('body').width()+'px',
                position:'absolute',
                top:0,
                left:0,
                zIndex:9999,
                background:'#000'
            });

            $('.close','#popup').live('click',function(){
                popup(this);
                return false;
            });
        }

        if ($popup.is(':visible')) {
            $('#popup, #popup-bg').fadeOut(200, function() {
                $('#popup').empty();
                $('select:not(.hidden)').css('visibility','visible');
            });
        } else {
            $container.detach().appendTo('#popup').show();
            var width='598px';
            if ($('#popup .big-gallery').length) width='780px';
            if ($('#popup .action').length) width='auto';

            $('#popup').css({
                width: width,
                top:getBodyScrollTop()+150+'px'
            });

            $('#popup').fadeIn(400);
            $('#popup').css('left',($('body').width()-$('#popup').width())/2+'px');
            $('#popup-bg').fadeTo(400, 0.7);

            $('select:not(.hidden)').css('visibility','hidden');
        }
    }
}

function getBodyScrollTop()  {
  return self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

//возвращает cookie если есть или undefined
function getCookie(name) {
    var matches = document.cookie.match(new RegExp(
      "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
    ));
    return matches ? decodeURIComponent(matches[1]) : undefined; 
}

// уcтанавливает cookie
function setCookie(name, value, props) {
    props = props || {};
    var exp = props.expires;
    if (typeof exp == "number" && exp) {
        var d = new Date();
        d.setTime(d.getTime() + exp*1000);
        exp = props.expires = d;
    }
    if(exp && exp.toUTCString) { props.expires = exp.toUTCString(); }

    value = encodeURIComponent(value);
    var updatedCookie = name + "=" + value;
    for(var propName in props){
        updatedCookie += "; " + propName;
        var propValue = props[propName];
        if(propValue !== true){ updatedCookie += "=" + propValue; }
    }
    document.cookie = updatedCookie;

}

// удаляет cookie
function deleteCookie(name) {
    setCookie(name, null, { expires: -1 });
}

function activateChooseCity(){
	
	$("#choosecity .showlist").eq(0).click( function( event ) {
		event.preventDefault();
		$(this).remove();
		$("#choosecity .close").remove();
		var h = $("#choosecity ul").eq(0).height();
		$("#choosecity div.wrapper").animate({height: ""+h+"px"}, {duration: 400});
		return false;
	});
	$("#choosecity .selected").click( function( event ) {
		event.preventDefault();
		setCookie("karexcity", $(this).text(), {expires: 31536000, path: "/"} );
		$("#popup #form-choose-region .options-list").css("display", "none");
		popup( $("#choosecity") );
		return false;
	});
	$("#choosecity ul li").has("span.alike").click( function() {
	    setCookie("karexcity", $(this).text(), {expires: 31536000, path: "/"} );
	    $("#form-choose-region .options-list").hide();
        window.location.reload();
	    popup( $("#choosecity") ); 
        // reloadPage
	    return false;
    });
	$("#choosecity .close").click( function(){
		$("#choosecity .selected").triggerHandler("click");
	});
}

function showNextPromo(){
	if (animation_completed) {
		animation_completed = false;
		$('ul.promo div.sticker div.bg').addClass('loading');
		active_li = $('ul.promo li.active');
		if ($('ul.promo li.active').next().length > 0) {
		    next_li = $('ul.promo li.active').next();
		} else {
		    next_li = $('ul.promo li:first');
		}
		$('ul.promo li').removeClass('last-active');
		$('ul.promo li.active').removeClass('active').addClass('last-active');
		next_li.find('div.wrapper').fadeTo(0, 0);
		next_li.addClass('active');
		next_li.find('div.wrapper').stop().animate({opacity: 1}, 600, function(){
		    animation_completed = true;
		});
	}
}

//Promo Block
//autor: 1c-bitrix Market, Tires Shop
$(document).ready(function(){
	animation_completed = true;
    window.autoRotatePromo = setInterval( showNextPromo, 5000 );

    //Next
	$('div.promo div.next').click( function(){
		clearInterval(autoRotatePromo);
		showNextPromo();
	});

	// Prev
	$('div.promo div.prev').click(function(){
		clearInterval(autoRotatePromo);
	    if (animation_completed) {
	        animation_completed = false;
	        $('ul.promo div.sticker div.bg').addClass('loading');
	        active_li = $('ul.promo li.active');
	        if ($('ul.promo li.active').prev().length > 0) {
	            next_li = $('ul.promo li.active').prev();
	        } else {
	            next_li = $('ul.promo li:last');
	        }
	        $('ul.promo li').removeClass('last-active');
	        $('ul.promo li.active').removeClass('active').addClass('last-active');
	        next_li.find('div.wrapper').fadeTo(0, 0);
	        next_li.addClass('active');
	        next_li.find('div.wrapper').stop().animate({opacity: 1}, 600, function(){
	            animation_completed = true;
	        });
	    }
	});
	
	// Promo Block Onload
	$('ul.promo li:first').addClass('active');
	$('ul.promo li').css({'display':'block'});
	$('div.promo div.arrow').hover(function(){
	    $(this).addClass('hovered');
	}, function(){
	    $(this).removeClass('hovered');
	});
});

function adjustSectionItems(){
    $('ul.products li:odd').each( function(){
        var $t = $(this);
        var $pr = $t.prev();

        // header
        var th = $t.find('h2').eq(0).height();
        var ph = $pr.find('h2').eq(0).height();
        var maxH = 0;
        if ( th != ph ) {
            maxH = Math.max( th, ph);
            if ( th < maxH ) {
                $t.find('h2').eq(0).height(maxH);
            }
            if ( ph < maxH ) {
                $pr.find('h2').eq(0).height(maxH);
            }
        }

        //body
        th = $t.find('dl').eq(0).height();
        ph = $pr.find('dl').eq(0).height();
        if ( th != ph ) {
            maxH = Math.max( th, ph);
            if ( th < maxH ) {
                $t.find('dl').eq(0).height(maxH);
            }
            if ( ph < maxH ) {
                $pr.find('dl').eq(0).height(maxH);
            }
        }
    });
}

function toggleMenuList( action ){
    var mStyle = document.getElementById('man-list').style;
    var $on = $("#topmenuCityList .sort").eq(0);
    var $off = $("#topmenuCityList .sort").eq(1);
    if ( action == 'show' ) {
        $on.css('visibility', 'hidden');
        $off.css('visibility', 'visible');
        mStyle.display = 'block';
    } else {
        $on.css('visibility', 'visible');
        $off.css('visibility', 'hidden');
        mStyle.display = 'none';
    }
}
