var ie = navigator.appVersion.match(/MSIE/) ? true : false;
var ff = navigator.appName.match(/Netscape/) ? true : false;
var ie8 = navigator.appVersion.match(/MSIE 8\.0/) ? true : false;

var
	slide_pos = 1,
	slide_img = 0,
	slide_offer = 0,
	$slide = $('.open_item .slider ul'),
	bw = 65;

function stopPromo() {
    $('#promo .slider').cycle('pause'); 
}
function onBefore() {
    if ($(this).attr('class') != 'video') {
        stopVideo();
        $('#promo .slider div.video').hide('fast');
    }
    else {
        $('#promo .slider div.content').hide('fast');
    }
}

var bytplayer;
// Stop video
function stopVideo()
{
    if (bytplayer) bytplayer.pauseVideo();
}
// This function is automatically called by the player once it loads
function onYouTubePlayerReady(playerId)
{
    bytplayer = document.getElementById("bytplayer");
    bytplayer.addEventListener("onStateChange", "onPlayerStateChange");
}
// On player state change
function onPlayerStateChange(val) {
    if (val == 0 || val == 1 || val == 2 || val == 3) {
        stopPromo();
    }
}
// Load player
function loadPlayer(videoID, no) {
    var params = {allowScriptAccess: "always"};
    var atts = {id: "bytplayer"};
    swfobject.embedSWF("http://www.youtube.com/v/" + videoID + "?version=3&enablejsapi=1&playerapiid=bytplayer", "vid_no_"+no, "940", "460", "9", null, null, params, atts);
}

$(document).ready(function(){

	country();
	item_href();
	href_hover();
	hover();
	checkUrlType();
	if ($('#promo').length) {
		$('#promo .slider').cycle({
			timeout:   4000,
			fx:        'fade',
			prev:      '#promo .prev',
			next:      '#promo .next',
                        before:     onBefore
		});
		$('#promo .prev, #promo .next').click(function() { 
			stopPromo();
		});
	}
	
	if ($('.new_reviews').length) {
		$('.new_reviews .slider').cycle({
			timeout:   6000,
			fx:        'scrollLeft',
			pager:     '.new_reviews .pager'
		});
		$('.new_reviews .pager a').click(function() { 
			$('.new_reviews .slider').cycle('pause'); 
		});
	}
        
	if ($('.bank').length) {
		$('.bank input').click(function() {
			$('.bank :input').each(function(){
				var css = $(this).parent().attr('class').replace('-active', '-inactive');
				$(this).parent().attr('class', css);
			});
			if ($(this).attr("checked")) {
				var css = $(this).parent().attr('class').replace('-inactive', '-active');
				$(this).parent().attr('class', css);
			}
		});
	}
	
	$('.mailing form > div input, .add_comment form .textarea textarea , .add_comment form .input input').focus(function(){
		if($(this).val() == $(this).attr('title')){
			$(this).val("");
		}
		$(this).parent().addClass('focus');
	}).blur(function(){
		if($(this).val() == ""){
			$(this).val($(this).attr('title'));
		}
		$(this).parent().removeClass('focus');
	})
	
	$('.more_info .comments li').each(function(k){
		if(k%2){$(this).addClass('sel');}
	});
	
	$('.more_info .comments li:last-child, .contact .places ul li:last-child').each(function(){
		$(this).addClass('last');
	});
	
	if ($('.open_item .about').length == '0') {
		$('.open_item .right').addClass('no_about');
	}
	
	$('.open_item .about:empty').each(function(){
		$(this).parent().addClass('no_about');
	})
	
	if ($('.open_item .description').length == '0') {
		$('.open_item .right').addClass('no_description');
	}
	
	$('.open_item .description:empty').each(function(){
		$(this).parent().addClass('no_description');
	})
	
	$('.menu > div').each(function(){
		if ($(this).height() > '40') {
			$(this).addClass('more_row');
		}
	});
	
	$('#basket .bttn a.back').each(function(){
		if ($(this).height() > '20') {
			$(this).addClass('more_row');
		}
	});
	
	$('#basket table .txt').each(function(){
		if (($(this).height() > '20') && ($(this).height() < '40')) {
			$(this).addClass('two_row');
		}
		if (($(this).height() > '40') && ($(this).height() < '60')) {
			$(this).addClass('three_row');
		}
		if ($(this).height() > '60') {
			$(this).addClass('more_row');
		}
	});
	
	$('.filter span').each(function(){
		if ($(this).height() > '20') {
			$(this).parent().parent().addClass('more_row');
		}
	});
	
	$('.link_1 > span').each(function(){
		if ($(this).height() > '30') {
			$(this).addClass('more_row');
		}
	});
	
	$('.latest .img + .content h3').each(function(){
		if (($(this).height() > '70') && ($(this).height() < '90')) {
			$(this).parent().find('div').addClass('two_row');
		}
		if ($(this).height() > '90') {
			$(this).parent().find('div').addClass('one_row');
		}
	});
	
	$('.subscribe .mailing.success .txt div').each(function(){
		$(this).css({'margin-top': ($(this).parent().height() - $(this).height()) / 2});
	});
	
	$('.where img').each(function(){
		$(this).css({'margin-top': ($(this).closest('.clearfix').height() - $(this).height()) / 2});
	});
	
	$('.noformet-body .bank label').click(function(){
		$(this).parent().parent().find('.sel').removeClass('sel');
		$(this).parent().addClass('sel');
		if ($(this).parent().hasClass('sel')) {
			$(this).parent().find('input').attr('checked', 'checked');
		}
		return false;
	});
	
	$('.noformet-body .bank input').click(function(){
		$(this).parent().parent().find('.sel').removeClass('sel');
		$(this).parent().addClass('sel');
	});
/**/
	$('#basket table .remove').bind('click', function() {
		$(this).closest('tr').remove();
		removeFromBasket($(this).closest('tr').find('.cart_index').val());
	});
	$('.counter > span span').bind('click', function() {
            var d = $(this).hasClass('up') ? 1 : -1;
            var input = $(this).closest('.counter').find('input.count');
            var count = parseInt(input.val());
            count = (parseInt(count) + d) >= 0 ? parseInt(count) + d : 1;
            input.val(count);
            if(count == 1) {
                $(this).hide();
            } else {
                $(this).next().show();
            }
            itemTotalPrice($(this));
        });
        $('.counter input').bind('keydown',function(event) {
            if( 
                event.keyCode == 46 ||
                event.keyCode == 8 || 
                event.keyCode == 9 ||
                (event.keyCode >= 37 && event.keyCode <= 40) ||
                (event.keyCode >= 48 && event.keyCode <= 57) ||
                (event.keyCode >= 96 && event.keyCode <= 105)) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if(event.keyCode < 48 || event.keyCode > 57 ) {
                    event.preventDefault();
                }                
            }                            
        });        
        $('.counter input').bind('keyup',function() {
            var val = $(this).val() != 0 || $(this).val() == "" ? $(this).val() : 1;
            val = parseInt(val.substring(0, 1)) != 0 ? val : val.substring(1, val.lenght) ;
            $(this).val(val);
            if(val == 1) {
                $(this).closest('.counter').find('down').hide();
            } else {
                $(this).closest('.counter').find('down').show();
            }
            if($(this).val() != 0 && $(this).val() != "") {
                itemTotalPrice($(this));            
            }
        });
        $('.counter input').bind('focusout',function() {
            var val = $(this).val() == "" ? 1 : $(this).val();
            $(this).val(val);
            itemTotalPrice($(this));  
        });
/**/
	current_vote = 0;
	mouseover_vote = 0;
	$('.add_comment form .vote_list li').mouseover(function(){
		for(i=1;i<=5;i++){
			$('.add_comment form .vote_list li[data-vote-id='+i+']').removeClass('sel');
			$('.add_comment form .vote_list li[data-vote-id='+i+']').removeClass('sel');
		}
		mouseover_vote = $(this).attr('data-vote-id');
		for(i=1;i<=mouseover_vote;i++){
			$('.add_comment form .vote_list li[data-vote-id='+i+']').addClass('sel');
		}
	});
	$('.add_comment form .vote_list li').mouseout(function(){
		for(i=1;i<=5;i++){
			$('.add_comment form .vote_list li[data-vote-id='+i+']').removeClass('sel');
		}
		for(i=1;i<=current_vote;i++){
			$('.add_comment form .vote_list li[data-vote-id='+i+']').addClass('sel');
		}
	});
	$('.add_comment form .vote_list li').click(function(){
		current_vote = $(this).attr('data-vote-id');
		$('#vote_result').val(current_vote);
	});
	
	slide_img = $('.open_item .left ul li').size();
	if (slide_img > 4) {
		$('.open_item .slider .prev').click(function() {slideMe(1)});
		$('.open_item .slider .next').click(function() {slideMe(0)});
	}
	
	$('.refuse .ok div, .refuse .error div').each(function(){
		$(this).css({'padding-top': ($(this).parent().height() - $(this).height()) / 2});
	});
	
	$('.text table').each(function(){
		$(this).attr('cellspacing', '0');
	});
	
	$(function() {
		var offset = 0;
		var bunch;
		while ((bunch = $('.item_list .item h3').slice(offset + 0, offset + 2)).length) {
			$(bunch).each(function() {
				bunch.max = Math.max($(this).height(), bunch.max !== undefined ? bunch.max : 0);
			});
			$(bunch).height(bunch.max);
			offset += 2;
		}
	});
	
	$(function() {
		var offset = 0;
		var bunch;
		while ((bunch = $('.item_list .item').slice(offset + 0, offset + 2)).length) {
			$(bunch).each(function() {
				bunch.max = Math.max($(this).height(), bunch.max !== undefined ? bunch.max : 0);
			});
			$(bunch).height(bunch.max);
			offset += 2;
		}
	});
	
	$(window).bind('scroll resize',function(){        
            var header_height = $('.listing h1').height() + $('#header').height() + 28 + $('.content .tabs').height() + 4 + 2 + 19;
            var footerSize = $('#footer').height() + $('.pos-top-right').height() + 33 + 17 + 2 + 13 + 446;
            var visibleSize = $(document).height() - footerSize;
            var fromTop = $(window).scrollTop();
            if (fromTop > header_height) {
                if (fromTop < visibleSize) {
                    $('.contact .map_sliding').css({
                        'position': 'fixed',
                        'top': '0px',
                        'bottom': 'auto',
                        'margin-top': '3px'
                    });
                }
                else {
                    var boxHeight = visibleSize + 3 - fromTop;
                    $('.contact .map_sliding').css({
                        'position': 'fixed',
                        'top': '0px',
                        'bottom': 'auto',
                        'margin-top': boxHeight + 'px'
                    });
                }
            }
            else {
                $('.contact .map_sliding').attr("style", "");
            }
  });
	
	$('.basket').hover(function() {
		if($(this).hasClass('fix')) {
			$('.basket .content').show("fast");
		}
	}, function() {
		if($(this).hasClass('fix')) {
			$('.basket .content').hide("fast");
		}
	});
	
	$(window).bind('scroll resize',function(){
		var from_Top = $(window).scrollTop();
		if (from_Top > 1) {
			$('.basket .content').hide("fast");
			$('.basket').addClass('fix');
		} else {
			$('.basket .content').show("fast");
			$('.basket').removeClass('fix');
		}
	});
	
	$('#menu .link_1.default').mouseenter(function() {
		$('#menu .link_1.default').hide();//.fadeToggle(200, "swing");
		$('#menu .link_1.hover').fadeToggle("medium", "swing");
	});
	$('#menu .link_1.hover').mouseleave(function() {
		$('#menu .link_1.hover').hide();//.fadeToggle(200, "swing");
		$('#menu .link_1.default').fadeToggle("medium", "swing");
	});

});

function itemTotalPrice(el) {    
    var count = el.closest('.counter').find('input.count').val();
    var pUnit = el.closest('tr').find('.price','tx').text();
    var pIndex = el.closest('.counter').find('input.cart_index').val();
    pUnit = parseFloat(pUnit.replace(",", "."));
    var pTotal = pUnit * count;
    pTotal = pTotal.toFixed(2);
    //pTotal = pTotal.replace(".",",");
    el.closest('tr').find('.sum','td').text(pTotal);

    changeBasketCount(pIndex, count);
}

function country(s) {
	$(document).bind('click', function(e) {
		if (!$(e.target).parents().parents().parents().hasClass('country')) {
			$('.country ul',s).hide();
			$('.country').removeClass('focus');
		}
	});
	if ($('.country dl',s).size()) {
		$('.country dt a',s).click(function() {
			$('.country ul',s).slideToggle(10);
			$('.country').toggleClass('focus');
		});
	}
}

function item_href() {
	$('.item .count, .item a.btn').click(function(e){e.stopPropagation();});
	$('.item').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	}).click(function() {
		window.location = $('h3 a',this).attr('href');
	});
}

function href_hover() {
	$('.latest_list > div, .latest_list > div > div').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	}).click(function() {
		window.location = $('a',this).attr('href');
	});
}

function hover() {
	$('.attach ul a').hover(function() {
		$(this).parent().addClass('hover');
	}, function() {
		$(this).parent().removeClass('hover');
	});
}

function slideMe(r) {
	if ($slide.is(':animated')) return;
	if (!(r?(slide_img-(slide_pos-1)-4):((1-slide_pos)*-1))) {
		if (r) $('li:eq(0)',$slide).appendTo($slide);
		else $('li:last',$slide).prependTo($slide);
		$slide.animate({left:(r?'+':'-')+'='+bw+'px'},0);
	}
	else r ? slide_pos++ : slide_pos--;
	$slide.animate({left: (r?'-':'+')+'='+bw+'px'},65);
}

$(window).load(function() {

	function equalHeight(group) {
		var tallest = 0;
		group.each(function() {
			var thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	 }

	/*equalHeight($('.open_left , .open_right'));*/
	equalHeight($('#promo .promo_items .item h3'));
	equalHeight($('#promo .promo_items .item > div'));
	/*equalHeight($('.where .clearfix div'));*/
	
	function equalWidth(group) {
		var tallest = 0;
		group.each(function() {
			var thisWidth = $(this).width();
			if(thisWidth > tallest) {
				tallest = thisWidth;
			}
		});
		group.width(tallest);
	}
	 
	equalWidth($('#basket .result .fname'));
	equalWidth($('#basket .result .value'));
	 
});

/* Select box dropdown */
function CityDropdown(s) {
        $(document).bind('click', function(e) {
                if (!$(e.target).parents().hasClass('select')) {
                        $('ul',s).hide();
                }
        });
        // city dropdown
        if ($('.select',s).size()) {
                $('dt a',s).click(function() {
                        if (s.attr('class') == 'select-city4') {
                            $('.select-city3 ul').hide();
                        }
                        if (s.attr('class') == 'select-city3') {
                            $('.select-city4 ul').hide();
                        }
                        $('ul',s).slideToggle(100);
                });
                $('ul a',s).click(function() {
                        id = $(this).attr('id');
                        if (s.attr('class') == 'select-city4') $('#shop_city').val(id);
                        if (s.attr('class') == 'select-city3') {
                            if ($('#shopsForm').length && parseInt($('#shop_country').val()) != parseInt(id)) loadCities(id);
                            $('#shop_country').val(id);
                        }
                        if (s.attr('class') == 'select-city2') $('#dCountry').val(id);
                        if (s.attr('class') == 'select-city') $('#bCountry').val(id);
                        $('dt span',s).html($(this).text());
                        $('*[name=location]',s).val(id);
                        $('ul',s).hide();
                });
        }
		
}
$(document).ready(function(){
    //Select term dropdown
	CityDropdown($('.select-city'));
	CityDropdown($('.select-city2'));
	CityDropdown($('.select-city3'));
	CityDropdown($('.select-city4'));
});
/**
 * Check if it is internal/external url,
 * if external then target attribute is set to _blank
 */

function checkUrlType() {
	var comp = new RegExp(location.host);
	
	$('.urlCheck').each(function(){
	   if ($(this).attr('href')) {

		   if(comp.test($(this).attr('href'))){
			// this is internal link, target attribute set to _self            	      	
				$(this).attr('target','_self');
		   }
		   else{
			// this is external link, target attribute set to _blank  
			  $(this).attr('target','_blank');
		   }
	   }
	});	
}

$(".categories_ietekme a").click(function(event){
    var cat = $(this).attr('rel');
    $("#substance").load(domain + "ajax/substance"+cat+".html");
    $("a").removeClass(".categories_ietekme active");
    $(this).addClass('active');
});

