function show_menu(element, id) {
    $('#menu_block').css('position', 'absolute');
    $('#menu_block').css('z-index', '1001');
	$('#producer_popup').hide('fast');

    var left_offset_position = element.offset().left; //это координата left
	var top_offset_position = element.offset().top; //это координата top
    $('#window').css('left', left_offset_position + 231);
    $('#window').css('top', top_offset_position);
    
	if($('#group' + id).html())
		$('#menu_content').html('<ul>' + $('#group' + id).html() + '</ul>');
	else
		$('#menu_content').html('');
	
	if($('#specials' + id).html())
		$('#special_content').html('<h2>Популярные товары:</h2><ul>' + $('#specials' + id).html() + '</ul>');
	else
		$('#special_content').html('');
	
	$('#window').show('fast');
    $('#overlay').fadeTo(0, 0.6);
}

function close_menu() {
    $('#window').hide('fast');
    $('#overlay').fadeOut('fast');
    $('#menu_block').css('position', 'relative');
    $('#menu_block').css('z-index', '0');
	$('#producer_popup').hide('fast');
	$('#quick_buy_form').slideUp('fast');
}

function sw(url) {
    x = 900;
    y = 550;
    cx = screen.width/2 - x/2;
    cy = screen.height/2 - y/2;
    window.open(
                    url,
                    '',
                    "toolbar=no, status=no, directories=no, menubar=no, resizable=no, width="+x+", height="+y+", scrollbars=yes, top="+cy+", left="+cx
                );
}

function pw(url) {
    x = 1010;
    y = 550;
    cx = screen.width/2 - x/2;
    cy = screen.height/2 - y/2;
    window.open(
                    url,
                    '',
                    "toolbar=no, status=no, directories=no, menubar=no, resizable=no, width="+x+", height="+y+", scrollbars=yes, top="+cy+", left="+cx
                );
}

var ua = 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;
}

/**
 * Создаём cookie
 */
function setCookie(name, value, expires, path, domain, secure) {
    if (!name || !value) return false;
    var str = name + '=' + encodeURIComponent(value);
    
    if (expires) str += '; expires=' + expires.toGMTString();
    if (path)    str += '; path=' + path;
    if (domain)  str += '; domain=' + domain;
    if (secure)  str += '; secure';
    
    document.cookie = str;
    return true;
}

/**
 * Получаем cookie
 */
function getCookie(name) {
    var pattern = "(?:; )?" + name + "=([^;]*);?";
    var regexp  = new RegExp(pattern);
    
    if (regexp.test(document.cookie))
    return decodeURIComponent(RegExp["$1"]);
    
    return false;
}

/**
 * Удаляем cookie
 */
function deleteCookie(name, path, domain) {
    setCookie(name, null, new Date(1), path, domain);
    return true;
}

/**
*
*  Base64 encode / decode
*
**/
var Base64 = {
    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
  
    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;
  
        input = Base64._utf8_encode(input);
  
        while (i < input.length) {
            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);
  
            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;
  
            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }
  
            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
        }
        return output;
    },
  
    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
  
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        while (i < input.length) {
            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));
  
            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;
  
            output = output + String.fromCharCode(chr1);
  
            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }
        }
        output = Base64._utf8_decode(output);
        return output;
    },
  
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
  
        for (var n = 0; n < string.length; n++) {
  
            var c = string.charCodeAt(n);
  
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },
  
    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
  
        while ( i < utftext.length ) {
  
            c = utftext.charCodeAt(i);
  
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

/**
 * Крутилка заглушек банеров на главной, если не поддерживается флеш
 */
var bannerNumber;
function bannersRotation(bannerNumber) {
    $('#mb' + bannerNumber).fadeOut(700);
    bannerNumber = bannerNumber == 3 ? 1 : bannerNumber + 1;
    $('#mb' + bannerNumber).fadeIn(700);
    setTimeout(function() { bannersRotation(bannerNumber) }, 5000);
}

var charValWidth; // Для сравнения товаров
var acRightWidth; // Для плашки сравнения товаров
var searchResElem = []; 	// Для навигации по результатам поиска при помощи клавиатуры - массив елементов
var searchResElemSelected = -1; // Для навигации по результатам поиска при помощи клавиатуры - текущий элемент
var searchResElemHref = ''; // Для навигации по результатам поиска при помощи клавиатуры - url выбранного элемента

function tidy_compare() {
    acRightWidth = ($( "#ac_right table" ).outerWidth() - 689);
    acLeftHeight = $( "#ac_left" ).outerHeight();
	$( "#ac_right" ).css('min-height', acLeftHeight);
    if ($.browser.webkit) {
		$('#ac_right').css('margin', 0);
	}
    if(acRightWidth > 0) {
        $( "#ac_slider" ).slider({
            value: 0,
            min: 0,
            max: acRightWidth,
            slide: function( event, ui ) {
                $( "#ac_right table" ).css('margin-left', -ui.value);
                $('body').css('cursor', 'pointer');
            },
            stop: function( event, ui ) {
                $('body').css('cursor', 'auto');
            }
        });
        //$( "#ac_right table" ).css('margin-left', -$( "#ac_slider" ).slider( "value" ));
    }
}

//табы в товаре
function show_tab(number) {
    if (number == 1) {
        $('#tab1t').attr('class', '').addClass('tab_sel');
        $('#tab2t, #tab3t, #tab4t, #tab5t').attr('class', '').addClass('tab');

        $('#tab1c').show();
        $('#tab2c, #tab3c, #tab4c, #tab5c').hide();
	}

	if (number == 2) {
		$('#tab2t').attr('class', '').addClass('tab_sel');
        $('#tab1t, #tab3t, #tab4t, #tab5t').attr('class', '').addClass('tab');

		$('#tab2c').show();
        $('#tab1c, #tab3c, #tab4c, #tab5c').hide();
	}

	if (number == 3) {
        $('#tab3t').attr('class', '').addClass('tab_sel');
        $('#tab1t, #tab2t, #tab4t, #tab5t').attr('class', '').addClass('tab');

        $('#tab3c').show();
        $('#tab1c, #tab2c, #tab4c, #tab5c').hide();
    }

    if (number == 4) {
        $('#tab4t').attr('class', '').addClass('tab_sel');
        $('#tab1t, #tab2t, #tab3t, #tab5t').attr('class', '').addClass('tab');

        $('#tab4c').show();
        $('#tab1c, #tab2c, #tab3c, #tab5c').hide();
    }

    /*if (number == 5) {
        $('#tab5t').attr('class', '').addClass('tab_sel');
        $('#tab1t, #tab2t, #tab3t, #tab4t').attr('class', '').addClass('tab');

        $('#tab5c').show();
        $('#tab1c, #tab2c, #tab3c, #tab4c').hide();
    }*/
    
}

//добавление в корзину
function add_to_cart(id) {
	if($('#buy' + id).prevAll('#buy').hasClass('bought')) {
		location.href='http://www.entuziast.ru/cart/';
	}else{
		$('#buy' + id).fadeIn();
		xajax_add_to_cart(id);
		setTimeout("$('#buy" + id + "').fadeOut().prevAll('#buy').addClass('bought');", 1500);
	}
}

//добавление к сравнению
function add_to_compare(id) {
	$('#compare' + id).fadeIn();
	xajax_add_to_compare(id);	
	setTimeout("$('#compare" + id + "').fadeOut();", 1500);
}

function show_pointer(el) {
	$('.window').fadeOut();
	if($(el).find('.window').css('display') == 'none') $(el).find('.window').fadeIn();
	else $(el).find('.window').fadeOut();
}

//филтр по производителю
function filter_old() {
	var path = $('#filter_path').val();
	var producer = $('#filter_producer').val();
	
	if(!producer) producer = 'www';
	
	location.href = 'http://' + producer + '.entuziast.ru/' + path;
}

//mouseover на результат поиска
function sel_result(el) {
    //$(el).removeClass('result_value');
    $(el).addClass('result_value_selected');
}

//mouseout на результат поиска
function unsel_result(el) {
    $(el).removeClass('result_value_selected');
    //$(el).addClass('result_value');
}

function isNotEmpty (elem) {
            var str = elem.value;
            var re = /.+/;
            if (!str.match(re)) { alert("Незаполнен телефон!"); return false;}
            else {return true;}
}

function isEmpty (elem) {
   var str = elem.value;
   var re = /.+/;
   if (!str.match(re)) return true;
   else return false;
}

function validateForm (form) {
	// Проверка телефона
	var flag = true;
	if($('#main_phone input[name=phone]').attr('type') == 'text') {
		if($('#main_phone input[name=phone]').val() == '' || $('#main_phone input[name=phone]').hasClass('example_phone')) {
			flag = false;
		}
	}else if($('#main_phone input[name=phone]').attr('type') == 'checkbox') {
		if($('#main_phone input:checked').length == 0) {
			flag = false;
			$('.extra_phone input[name*=extra_phone]').each(function() {
				if($(this).val() != '' && !$(this).hasClass('example_phone'))
					flag = true;
			});
		}			
	}else{
		flag = false;
	}
	
	if(flag) {
		$('#form input.example_phone').val('');
		return true; 
	}else {
		alert('Не укзан телефон!'); 
		return false;
	}
}

function clickme(cl_id) {
	var obj = $('.'+cl_id);
	var obj2 = $('#'+cl_id);
	if (obj.hasClass('clickme')) {
		obj.addClass('clickme_open');
		obj.removeClass('clickme');
		obj2.show();
	} else {
		obj.addClass('clickme');
		obj.removeClass('clickme_open');
		obj2.hide();
	}
}

function hideblock () {
	$(document).ready(function() {
		alert('1');
	});
}

