var ua = window.navigator.userAgent.toLowerCase();
var isOpera = ua.indexOf('opera')  > -1;
var isIE = !isOpera && ua.indexOf('msie') > -1;
function getDocumentHeight(){
    return Math.max(document.compatMode != 'CSS1Compat' ? document.body.scrollHeight : document.documentElement.scrollHeight, getViewportHeight());
}
function getViewportHeight(){
    return ((document.compatMode || isIE) && !isOpera) ? (document.compatMode == 'CSS1Compat') ? document.documentElement.clientHeight : document.body.clientHeight : (document.parentWindow || document.defaultView).innerHeight;
}

$(document).ready(function(){            
    function show_sub_menu(currentItem)
    {
        var targetItem = '#sub_menu_' + $(currentItem).attr('id').split('_')[1];
        $(currentItem).addClass('active');
        //console.log(targetItem);
        var b_width = $(targetItem).outerWidth();
        var left = $(currentItem).position().left;
        //Это значение в идеале надо брать автоматически
        //!!!Не забыть переписать
        var parent_width = 987;
        var isScroll = (getDocumentHeight() - getViewportHeight()) > 0;
        //так как рамка вокруг выпадающего меню 1px 
        //то для совмещения ее с границей активного пункта меню
        //задаем смещение в 1px
        var offset = 1;
        var isMozillaOrIe = $.browser.mozilla || $.browser.msie;
        var isDiffWidth = $(currentItem).outerWidth() != $(currentItem).innerWidth(); 
        //Почему то при наличии скрола firefox 4.0 и msie немного иначе высчитывают
        //позицию относительно последнего пункта меню, ниже это исправлем
        if (isDiffWidth && !(isScroll && isMozillaOrIe) ){
            offset = 2;
            if($.browser.msie)
            {
                offset = 1;
            }
        }
        //Для полной радости в ie 9 делаем так, точнее для последнего пунта меню, 
        //при отсутствие скролинкга ставим смещение 3px
        if (isDiffWidth && $.browser.msie && !isScroll && $.browser.version == "9.0")
        {
            offset = 3;
        }
                
        //Если блок вылазит за правую границу
        if (b_width > (parent_width - left) ) {
        //Если ширина больше свободного пространства слева выравниваем по центру
            if (b_width > left) {
                left = (parent_width - b_width) / 2;
            }
            //Выравнимаем по правому краю
            else {
                left = left - b_width + $(currentItem).innerWidth() + offset;
            }
        }

        $(targetItem).css("left", left);
        $(targetItem).css('display','block');
    }
            
    function hide_sub_menu()
    {
        $('.menu_catalog_drop_w').css('display','none');
        var categories = $('#menu_catalog .categories_list .category');
        categories.each(function(){
           if (!$(this).hasClass('current'))
           {
              $(this).removeClass('active');
           }
        });
    }
    
    

    $('.no_js').css('display','none');
    $("#menu_catalog .category").hover(function(){show_sub_menu(this);}, function(){hide_sub_menu();});
    $('.menu_catalog_drop_w').hover(function(){var thisId = $(this).attr('id');var targetId = thisId.split('_')[2];$('#category_'+targetId).addClass('active');$(this).css('display','block');},function(){hide_sub_menu();});
    $('.single_product_page .info_1 .photo_preview img').live('click',function(){
        $('.single_product_page .info_1 .photo img').attr('src', $(this).attr('src_photo')).parent('a').attr('href',$(this).attr('src_photo'));
    });
    $('.single_product_page .info_2_titles .title').live('click',function(){
        $('.single_product_page .info_2_titles .title').removeClass('active');
        $(this).addClass('active');
        var targetElement = $(this).attr('id').split('_get_')[1];
        //$('.single_product_page .info_2_content').html($('.'+targetElement).html());
        $('.info_2_content_hide').hide(0);
        $('.'+targetElement).show();
    });
    $('#pageSize').change(function(){
        $(this).parents('form').submit();
    });
    $('body').delegate('.price_info .q', 'click', function(){
        $('.price_info .a').toggle(0);
    });

    //$(".login_form_small .hide").css('margin-left','-15px');
    $(".login_form_small .hide").css('margin-right','0px');
    $(".login_form_small .hide").change(function(){
        var el = $(".login_form_small input[@type='checkbox'] + label");
        if (el.hasClass('unchecked'))
        {
            el.removeClass('unchecked');
            el.addClass('checked');
        }
        else
        {
            el.removeClass('checked');
            el.addClass('unchecked');
        }
    });
    $(".login_form_small input[@type='checkbox'] + label").addClass("unchecked");
    /*$(".login_form_small input[@type='checkbox'] + label").each( function(){
	    if ( $(this).prev()[0].checked )
		{
            $(this).addClass("checked");
        }
        else
		{
            $(this).addClass("unchecked");        
        }
	})
	.hover( 
		function() { $(this).addClass("over"); },
		function() { $(this).removeClass("over"); }
	)
	.click( function() {
		$(this)
			.toggleClass("checked")
			.prev()[0].checked = !$(this).prev()[0].checked;
		$(this)
			.toggleClass("unchecked")
			.prev()[0].checked = $(this).prev()[0].checked;
	})
	.prev().hide();*/

    $('body').delegate('#header .user_b .login_link','click',function(){
        $('#header .login_form_small').toggle();
        return false;
    });        


	v = $('input[mobilephone="mobile_st"]').val();
	if ((v == '') || (v == 0))  $('input[mobilephone="mobile_st"]').val('7');

	$('input[mobilephone="mobile"]').mask("(999) 999-9999");
	$('input[mobilephone="mobile_st"]').mask("9?999",{placeholder:" "});
	
	$(document).click(function(){
		$('#account_dropdown').hide();
	});

	$('.prefix').click(function(e){
        	$('#account_dropdown').toggle();
		$('input[mobilephone="mobile"]').focus();
		e.preventDefault();
		return false;
	});

	$('#account_dropdown a').click(function(e){

		$('input[mobilephone="mobile_st"]').val($(this).attr('phoneCode'));
		$('.prefix img').attr('src', $(this).find('img').attr('src'));
                $('#account_dropdown').toggle();
		$('input[mobilephone="mobile"]').focus();
                e.preventDefault();
		return false;
	});




});

