var USE_FLOAT_MENU = true;

//-- HACK for the IE7 !!!
var isTheFuckingMSIE = false;
var menuCloseDelay = 500; // ms
var menuCloseId = null;
//var menuMinWidth = null;

$(document).ready(function()
{
	$("#logo").unbind('mousedown');
	$('#logo').mousedown(function() {
		//window.location = '/'+LANGUAGE+'/main';
		window.location = '/';
	});
	
	//$(".page_combobox").selectbox();

	/*
	//$('#mcs_container_countries').css('display', 'none');
	//$("#combobox_countries").disableSelection();
	$("#page_combobox_countries").myselectbox({
		trObjClass:"mcs_option",
		optionsListId:"mcs_container_countries",
		inputObjId:"combobox_countries"
	});
	alignComboboxCountries();
	*/

	//$("#page_combobox_lang").disableSelection();
	$("#page_combobox_lang").myselectbox({
		trObjClass:"mcs_option",
		optionsListId:"mcs_container_lang",
		inputObjId:"combobox_lang"
	});
	alignComboboxLang();


	if(isMainPage || isPartnersPage || isDealersPage || isContactsPage) {
		//$("#page_combobox_city").disableSelection();
		$("#page_combobox_city").myselectbox({
			trObjClass:"mcs_option",
			optionsListId:"mcs_container",
			inputObjId:"combobox_city"
		});

		$("#page_combobox_city").mousedown(function() {
			toggleNewsZIndex();
			//alert($('#combobox_city').css('display'));
		});

		alignComboboxCity();
	}
	
	$("#browser").treeview({
		mainClass: "treeview",
		/*animated: "slow",*/
		/*collapsed: true,*/
		toggle: function() {
			//console.log("%s was toggled.", $(this).find(">span").text());
		}
	});

	/*
	if($("#partners").length != 0) {
		$("#partners").treeview({
			mainClass: "treeview3"
		});
  
		$('#partners li ul.content div').each(function() {
			if(typeof($(this).attr('id')) == 'undefined') {
				return false;
			}
			var loc = $(this);
			var id = loc.attr('id');
			if(id.substr(0, 9) == 'location_') {
				var ids = id.substr(9);
		    var lat = $('#location_lat_'+ids).val();
		    var lng = $('#location_lng_'+ids).val();
				$(this).click(function() {
					initGoogleMap(lat, lng, loc.html());
				});
			}
		});
	}
	*/

	/*
	if($("#faq").length != 0) {
		$("#faq").treeview({
			mainClass: "treeview4"
		});
	}
	*/

	$(".faq_title").each(function() {
		var id = $(this).attr('id');
		var div_id = $(this).attr('id')+'div';

		$("#"+id).click(function() {
			$("#"+div_id).toggle();
		});
		/*
		$("#"+id).treeview({
			mainClass: "treeview4"
		});
		*/
	});
	

	/*
	$('#combobox1').change(function() {
		var url = $(this).val();
		var ajaxUrl = '/'+LANGUAGE+'/changecountry';
		var dt = new Date();
		$.post(
      ajaxUrl,
      {dt:dt.getTime(), url:url},
      function(redirectUrl) {
      	window.location = redirectUrl;
      }
    );
		
	});

	$('#combobox2').change(function() {
		window.location = $(this).val();
	});
	*/

	//-- click CITY (PARTNER) choice
	$('#myselectcity tr td').each(function() {
		$(this).unbind('mousedown');
		$(this).mousedown(function() {
			var id = $(this).attr('id');
			//console.warn($(this).attr('id')+' -> '+$(this).html());
			window.location = '/'+LANGUAGE+'/contacts/'+id;
		});
	});
	//-- click COUNTRY choice
	$('#myselectcountry tr td').each(function() {
		$(this).unbind('mousedown');
		$(this).mousedown(function() {
			var url = $(this).attr('id');
			//console.warn(url);
			var ajaxUrl = '/'+LANGUAGE+'/changecountry';
			var dt = new Date();
			$.post(
        ajaxUrl,
        {dt:dt.getTime(), url:url},
        function(redirectUrl) {
        	window.location = redirectUrl;
        }
      );
    });
	});
	//-- click LANGUAGE choice
	$('#myselectlang tr td').each(function() {
		$(this).unbind('mousedown');
		$(this).mousedown(function() {
			var id = $(this).attr('id');
			//console.warn(id);
			window.location = id;
		});
	});

	clickHandlers();
	//checkDivSize();
	initSocialLinks();

	/*
	var sb = hasScrollBar();
	$('#scrollbar_emul').css('display', sb ? 'none' : '');

	var sb = hasScrollBar();
	$('#scrollbar_emul').css('display', sb ? 'none' : '');

	var v1 = $(document).height();
	var v2 = $(window).height();

	$('#debug').html('<h2>'+sb+' ('+v1+' - '+v2+')</h2>');
	*/

	comboHandler();

	if(USE_FLOAT_MENU) {
		//chkClientHeightScrollTimer();
	}

});

function comboHandler()
{
	$('#page_combobox_city').mousedown(function() {
		$('#body').unbind('mousedown');
		closeComboxes('#mcs_container');
	}).mouseleave(function() {
		closeComboxes();
	});

	/*
	$('#page_combobox_countries').mousedown(function() {
		$('#body').unbind('mousedown');
		closeComboxes('#mcs_container_countries');
	}).mouseleave(function() {
		closeComboxes();
	});
	*/

	$('#page_combobox_lang').mousedown(function() {
		$('#body').unbind('mousedown');
		closeComboxes('#mcs_container_lang');
	}).mouseleave(function() {
		closeComboxes();
	});
}

function toggleNewsZIndex()
{

	var list = $('#mcs_container');
	var news = $('#main_block_news3');
	var news_title = $('#main_block_news3_title');
	//var bottom = $('#main_block_bottom');
	
	var zIndex = (list.css('display') == 'none') ? '0' : '-1000';

	news.css('z-index', zIndex);
	news_title.css('z-index', zIndex);
	//bottom.css('z-index', zIndex);
}

function closeComboxes(except)
{
	var a = new Array('#mcs_container', '#mcs_container_countries', '#mcs_container_lang');
	$('#body').mousedown(function() {
		for(var i=0;i<a.length;i++) {
			if(typeof(except) != 'undefined' && a[i] == except) {
				continue;
			}
			$(a[i]).css('display', 'none');
		}
		toggleNewsZIndex();
	});
	toggleNewsZIndex();
}

function destroyMenu()
{
	if(menuCloseId == null) {
		return false;
	}

	$('#main_frame').attr('style', 'top:-100000px;display:none;');

	/*
	$("#page_combobox_div1").unbind('mousedown');
	$('#page_combobox_div1').mousedown();

	$("#page_combobox_div2").unbind('mousedown');
	$('#page_combobox_div2').mousedown();
	*/

	$('body *').enableSelection();
	$('#body').enableSelection();
}
function createMenu()
{
	var s = USE_FLOAT_MENU ? $(window).scrollTop() : 0;
	s = 0;

	var absTop = s + 33;
	var absShadow = 36;
	
	var clientWidth = parseInt(document.body.clientWidth / 3) + absShadow;
	//var clientHeight = document.body.clientHeight - absTop + s - 1;
	var clientHeight = document.body.clientHeight - absTop + s;
	var realMenuWidth = clientWidth - absShadow - 1;

	//$('#debug').html('<h2>absTop = '+absTop+'</h2>');

	$('#main_frame').attr('style', 'top:'+absTop+'px;left:0px;display:;');

	//$('#chat_frame').css('width', clientWidth - absShadow - 1).css('height', clientHeight - 1).css('float', 'right');
	//$('#chat_panel').css('width', clientWidth - absShadow - 1).css('height', clientHeight - 35);
	if(isMainPage) {
		changeChatWinSize();
	}

	$('#loadme').css('width', clientWidth).css('height', clientHeight);
	$('#browser').css('width', clientWidth);

	$('.treeview').css('width', clientWidth - absShadow - 1).css('height', clientHeight-1);

	//$('#debug').html('<h2>clientHeight = '+clientHeight+' ('+document.body.clientHeight+')</h2>');

	//-- HACK for the IE7 !!!
	if($.browser.msie) {
		var fixedTopObj = $('#fixed_1');
		var topObj = $('.filetree span.top');
		
		var num_entries = $('#fixed_1 li').length;
		var chkHeightFixed1 = (num_entries + 1) * parseInt(topObj.css('height'));
		var realHeightFixed1 = fixedTopObj.height();

		if(chkHeightFixed1 < realHeightFixed1) {
			//alert(chkHeightFixed1+' - '+realHeightFixed1);
			//alert($.browser.version)
			topObj.css('margin-top', '-13px');
			isTheFuckingMSIE = true;
		}
	}

	//console.warn($('.treeview').width());

	//var percent33 = getPercent33();
	//$('#issues_pictures_left').width(percent33);

	$('body *').disableSelection();
	$('#body').disableSelection();
}

function initTimer()
{
  killTimer();
	menuCloseId = setTimeout('destroyMenu();', menuCloseDelay);
}
function killTimer()
{
	clearTimeout(menuCloseId);
	menuCloseId = null;
}

function menuOpen()
{
	$("#menu_link").unbind('mousedown');
	$("#menu_link").mousedown(function() {
		//$('#combobox1').selectbox('close');
		//$('#combobox2').selectbox('close');
		createMenu();
	});
}
function menuClose()
{
	$(".filetree span.maintop").unbind('mousedown');
	$(".filetree span.maintop").mousedown(function() {
		$(this).unbind('dblclick');
		menuCloseId = 666;
		destroyMenu();
	});
}

function chatOpen()
{
	$("#chat_link").unbind('mousedown');
	$("#chat_link").mousedown(function() {
		showChatFrame();
	});
}

function clickHandlers()
{
	$("#main_frame").unbind('dblclick');
	$("#chat_frame").unbind('dblclick');
	
	menuOpen();
	menuClose();
	chatOpen();
	
	$(".filetree span.file").unbind('mousedown');
	$(".filetree span.file").mousedown(function() {
		menuCloseId = 666;
		destroyMenu();

		var $kids = $(this).children('a');
		var url = $kids.attr('href');
		if(url != null && typeof(url) != 'undefined') {
			window.location = url;
		}
	});

	$(".filetree .topline").unbind('mousedown');
	$('.filetree .topline').mousedown(function() {
		$(this).parent().click();
	});
	
	$("#menu_link .topline").unbind('mousedown');
	$('#menu_link .topline').mousedown(function() {
		$(this).parent().click();
	});

	$('.filetree span').each(function() {
		$thisCls = $(this).attr('class');
		$parentCls = $(this).parent().attr('class');
		if($thisCls == 'top') {
			//$(this).mousedown();
			$(this).unbind('mousedown');
			$(this).unbind('click');
		}
	});

	$("#main_frame").unbind('mouseleave');
	$("#main_frame").unbind('mouseenter');
	$("#main_frame").unbind('dblclick');

	$('#main_frame').mouseleave(function() {
		initTimer();
	}).mouseenter(function() {
		killTimer();
	}).dblclick(function() {
		return false;
	});

	$('li.fixed').each(function() {
		$(this).unbind('mousedown');
		$(this).unbind('click');
	});

}
                       
function getAbsolutePos(obj) {
	//alert(obj.id+' -> '+obj.offsetLeft+','+obj.offsetTop);
	var SL = 0, ST = 0;
	var r = {x:obj.offsetLeft-SL, y:obj.offsetTop-ST};
	if(obj.offsetParent) {
		var tmp = getAbsolutePos(obj.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}

function offsetPosition(element)
{
	var offsetLeft = 0, offsetTop = 0;
	do {
		offsetLeft += element.offsetLeft;
		offsetTop  += element.offsetTop;
	} while(element = element.offsetParent);
	return [offsetLeft, offsetTop];
}



function showLocationFrame(id)
{
	var url = '/'+LANGUAGE+'/contacts/'+id;
	window.location = url;
	return false;
	
	var locationPanel = $("#location_panel");
	//locationPanel.attr('href', '/contacts/'+id);
	locationPanel.attr('href', '#inline'+id);

	locationPanel.fancybox({
		'width' : '400',
		'height' : $('#inline'+id).height(),
		//'autoScale' : true,
		'transitionIn' : 'none',
		'transitionOut' : 'none',
		'overlayShow'	: false
	});

	locationPanel.click();
	return false;
}

function initSocialLinks()
{
	//-- ICONS UNDER IMAGES
	$('a').each(function() {
		var id = $(this).attr('id');
		var suff = id.substr(0, 11);
		if(suff == 'span_social') {

			var img = $(this).children('img');

			//-- each SPAN link
			var name = id.substr(11);
			
			$(this).unbind('mouseover');
			$(this).unbind('mouseout');

			$(this).mouseover(function() {
				var s = img.attr('src').replace('.png', '_over.png');
				img.attr('src', s);
			}).mouseout(function() {
				var s = img.attr('src').replace('_over.png', '.png');
				img.attr('src', s);
			});
		}
	});
}

function initIconsLink()
{
	return false;
	
	//-- ICONS UNDER IMAGES
	$('span').each(function() {
		var id = $(this).attr('id');
		var suff = id.substr(0, 11);
		if(suff == 'span_menu0_' || suff == 'span_menu1_' || suff == 'span_menu2_') {

			//-- each SPAN link
			var name = id.substr(11);
			
			$(this).unbind('mousedown');
			$(this).mousedown(function() {
				mouseDownNews(id.replace('span_', 'tr_'), name);
			});
		}
	});

	$('div').each(function() {
		var id = $(this).attr('id');
		var suff = id.substr(0, 11);
		if(suff == 'span_menu0_' || suff == 'span_menu1_' || suff == 'span_menu2_') {

			//-- each SPAN link
			var name = id.substr(11);
			
			$(this).unbind('mousedown');
			$(this).mousedown(function() {
				mouseDownNews(id.replace('span_', 'tr_'), name);
			});
		}
	});
}

var Utf8 = {
	// public method for url encoding
	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;
	},
	// public method for url decoding
	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;
	}
}

function getX20()
{
	//-- the whole page width (client's width)
	var W = document.body.clientWidth;

	//-- delimiter size (as a part of the client's WIDTH
	// for instance, width = 1280, x20 = 1280 / 64 = 20px)
	var x20 = parseInt(W / 64);

	return x20;
}

function getPercent33()
{
	//-- the whole page width (client's width)
	var W = document.body.clientWidth;
	
	var x20 = getX20();

	//-- DELIMITERS ROWS & COLUMNS
	$('.h20').height(x20);
	$('.h40').height(x20 * 2);
	$('.w20').width(x20);
	$('.w40').width(x20 * 2);

	var percent33 = parseInt((W - x20 * 6) / 3);

	return percent33;
}

function set3ColumnsCalculator()
{
	var percent33 = getPercent33();

	$('#welcome_block').width(percent33);
	$('#main_block').width(percent33);
	$('#news_block').width(percent33);
	$('#issues_pictures_left').width(percent33);

	return percent33;
}

function set2ColumnsCalculator(returnX20)
{
	var percent33 = getPercent33();

	var big_frame = percent33 * 2;

	$('#welcome_block').width(percent33);
	$('#main_block').width(big_frame);

	var x20 = getX20();
	var half_big_frame = parseInt((big_frame - x20 * 2) / 2);

	$('#details_text_block').width(half_big_frame);
	$('#details_image_block').width(half_big_frame);
	

	var mainWidth = $('#main_block').width() - x20 * 2;
	var col1Width = parseInt(mainWidth / 2);
	var col2Width = mainWidth - col1Width;

	$('#column1').width(col1Width);
	$('#column2').width(col2Width);
	$('#issues_pictures_left').width(percent33);

	return returnX20 ? x20 : percent33;
}

function setEquipmentsList()
{
	$('div.regular_welcome').each(function() {
		$('li.Node').each(function() {
			var span = $(this).children('span');
			var img = $(this).children('img');

			$(this).unbind('mousedown');
			$(this).unbind('mouseover');
			$(this).unbind('mouseout');

			$(this).mousedown(function() {
				var id = span.attr('id').substr(10)
				window.location = '/'+LANGUAGE+'/equipment/'+id;
			}).mouseover(function() {
				span.css('color', '#ffa042');
				$(this).css('list-style-image', 'url("../images/arrow_right_over.png")');
				var s = img.attr('src').replace('arrow_right.png', 'arrow_right_over.png');
				img.attr('src', s);
			}).mouseout(function() {
				span.css('color', '#465B6B');
				$(this).css('list-style-image', 'url("../images/arrow_right.png")');
				var s = img.attr('src').replace('arrow_right_over.png', 'arrow_right.png');
				img.attr('src', s);
			});
		});
	});
}

var waitForFinalEvent = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = "Don't call this twice without a uniqueId";
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();


/*
(function($, resize){
  if ($.browser.msie) {
    var

// Boolean пометка, загружен ли документ или нет
      documentIsLoaded,

// Сохраняем в переменную экземляр jQuery элемента window
// Пользуясь случаем сразу добавляем обработчик onload
      $window = $(window).one("load", function(){
// Если документ загружен, то устанавливаем значение 1 (true)
        documentIsLoaded = 1;
      });

// Возвращает назначение обработчиков onresize в исходное состояние
    function backToNative () {
      $.event.special[resize] = undefined;
      var events = $window.data("events"),
// Сохраняем структуру обработчиков, если таковые есть.
        eventStack = events && events[resize];
// Если есть обработчики событий, то убираем из кэша событий.
      if (eventStack) {
        events[resize] = undefined;
      }
// Назначаем одинарный обработчик onresize, дабы последующие события были делегированы с помощью нативный методов addEventListener/attachEvent
      $window.one(resize, $.noop);
// Если есть сохраненные обработчики, то возвращаем их на место.
      if (eventStack) {
        events[resize] = eventStack;
      }
    }
    
// Добавляем special событие в jQuery
    $.event.special[resize] = {
      setup: function () {
        if (documentIsLoaded) {
          backToNative();
// Возвращаем false чтобы событие было стандартными средствами для данного события
          return !documentIsLoaded;
        }
        var
// Идентификатор setInterval запущенной проверки размеров окна
          checking,
// Определяем текущую ширину окна
          prevWidth = $window.width(),
// Определяем текущую высоту окна
          prevHeight = $window.height();
          
// Собственно сама функция проверки
        (function handler (){
          if (documentIsLoaded) {
            window.clearInterval(checking);
            backToNative();
            return;
          }

          var
            width = $window.width(),
            height = $window.height();

// Проверяем изменились ли размеры окна
// Если изменили, то вызываем хэндлеры по событию
          if (width != prevWidth || height != prevHeight) {
            prevWidth = width;
            prevHeight = height;
            $window.trigger(resize);
          }

// Если проверка не запущена, то запускаем
          if (!checking) {
            checking = window.setInterval(handler, 100);
          }
        })();
      },
      teardowm: $.noop
    };
  }
})(jQuery, "resize");
*/

$(document).ready(function(){

	/*
	$(window).smartresize(function() {
		console.warn('smartresize');
    waitForFinalEvent(function() {
      //console.info('waitForFinalEvent after onresize');
      createMenu();
      checkDivSize();
      menuCloseId = 666;
			destroyMenu();
    }, 500, (new Date()).getTime());
  });
  */
	
	/*
	document.body.onresize = function () {
		console.warn('onresize body');
    waitForFinalEvent(function() {
      console.info('waitForFinalEvent after onresize');
      createMenu();
      checkDivSize();
      menuCloseId = 666;
			destroyMenu();
    }, 500, (new Date()).getTime());
  };
  */
	
	/*
	$(window).resize(function () {
    
		$.data(this, "currentWidth", $(this).width()); 
  
		console.warn('onresize');
    
    waitForFinalEvent(function() {
      console.info('waitForFinalEvent after onresize');
      createMenu();
      checkDivSize();
      menuCloseId = 666;
			destroyMenu();
    }, 500, (new Date()).getTime());
	});
	*/

	// доложить Игорю, уточнить насчет сроков ?

	/*
	window.onresize = function() {
	  console.warn('resizeend');
    waitForFinalEvent(function() {
      console.info('waitForFinalEvent after resizeend');
      createMenu();
      checkDivSize();
      menuCloseId = 666;
			destroyMenu();
    }, 500, (new Date()).getTime());
	};
	*/
	
	/*
	$(window).bind('resizeend', function() {
		
	});
	*/


	var MAIN_WINDOW_W = $(window).width();
	var MAIN_WINDOW_H = $(window).height();

	$(window).resize(function() {
		
		var W = $(window).width();
		var H = $(window).height();

		//-- no main window resizing
		if(W == MAIN_WINDOW_W && H == MAIN_WINDOW_H) {
			return false;
		}

		//waitForFinalEvent(function() {
      checkDivSize();
      createMenu();
      menuCloseId = 666;
			destroyMenu();
    //}, 500, (new Date()).getTime());

    //if(isVideosPage) {
    //	changeVideoWinSize();
    //}

    MAIN_WINDOW_W = W;
    MAIN_WINDOW_H = H;
		
	});

	/*
	function resize_viewport() {
	  $.event.remove(this, "resize", resize_viewport);

	  //console.log($(window).width()+' x '+$(window).height());

	  //waitForFinalEvent(function() {
      //console.info('waitForFinalEvent after onresize');
      createMenu();
      checkDivSize();
      menuCloseId = 666;
			destroyMenu();
    //}, 500, (new Date()).getTime());
	  
	  // do what you need to do
  	$.event.add(this, "resize", resize_viewport);
	}
	*/

	// and in the document ready event

	// Bind resize event to the window
	//$(window).resize(resize_viewport())

	$(window).load(function () {
    //console.error('onload');
    //Initial resizing
		//resize_viewport();
 
    //waitForFinalEvent(function() {
      checkDivSize();
      createMenu();
      menuCloseId = 666;
			destroyMenu();
    //}, 500, (new Date()).getTime());

	});

});


/*
handleOnLoad = function(evt)
{
	var docResizeHandler = null;
	if (myVars.browser.name == "MSIE")
	{
		docResizeHandler = (document.body.onresize) ? document.body.onresize : null;
		document.body.onresize = null;
	}

	if (myVars.browser.name == "MSIE")
	{
		document.body.onresize = docResizeHandler;
	}
}

handleResize = function(evt)
{
	var ieEvt = window.event;

	if (myVars.browser.name != "MSIE" || ieEvt.type == "resize")
	{
		// Handle resizing
		waitForFinalEvent(function() {
      console.info('waitForFinalEvent after onresize');
      createMenu();
      checkDivSize();
      menuCloseId = 666;
			destroyMenu();
    }, 500, (new Date()).getTime());
	}
};
*/
function setComboboxCountriesHeight(idx)
{
	var h = $('#mcs_container_countries .mcs_option').css('height');
	var allH = parseInt(h) * idx;
	$('#myselectcountry').height(allH);
	$('#mcs_container_countries').height(allH);
}
function alignComboboxCountries()
{
	var box = $('#combobox_countries');
	var h = box.height() + parseInt(box.css('padding-top')) + 1;
	var w = 0;
	var mcs = $('#mcs_container_countries');

	mcs.css('top', box.position().top + h).css('left', box.position().left + w);
}

function setComboboxLangHeight(idx)
{
	var h = $('#mcs_container_lang .mcs_option').css('height');
	var allH = parseInt(h) * idx;
	$('#myselectlang').height(allH);
	$('#mcs_container_lang').height(allH);
}
function alignComboboxLang()
{
	var box = $('#combobox_lang');
	var h = box.height() + parseInt(box.css('padding-top')) + 1;
	var w = 0;
	var mcs = $('#mcs_container_lang');

	mcs.css('top', box.position().top + h).css('left', box.position().left + w);
}

function setComboboxCityHeight(idx)
{
	var h = $('#mcs_container .mcs_option').css('height');
	var allH = parseInt(h) * idx;
	$('#myselectcity').height(allH);
	//$('#mcs_container').height(allH);
}
function alignComboboxCity()
{
	var box = $('#combobox_city');
	var h = box.height() + parseInt(box.css('padding-top')) + 1;
	var w = 0;
	var mcs = $('#mcs_container');

	if(isDealersPage) {
		mcs.css('top', box.position().top + h - 13).css('left', box.position().left + w - 1);
	} else {
		mcs.css('top', box.position().top + h).css('left', box.position().left + w);
	}
}

function hasScrollBar()
{
	return $(document).height() != $(window).height();
}
function checkPlugin(name)
{
	name = name.toLowerCase();
	for(var i=0;i<navigator.plugins.length;i++) {
		var pluginName = navigator.plugins[i].name.toLowerCase();
		if(pluginName.substr(0, name.length) == name) {
			return true;
		}
	}
	return false;
}

jQuery.fn.extend({
	disableSelection : function() {
		this.each(function() {
			//-- IE, Chrome, Safari
			this.onselectstart = function() { return false; };
			//-- IE, Opera
			this.unselectable = "on";
			//-- FF
			jQuery(this).css('-moz-user-select', 'none');
		});
	},
	enableSelection : function() {
		this.each(function() {
			this.onselectstart = function() {};
			this.unselectable = "off";
			jQuery(this).css('-moz-user-select', 'auto');
		});
	}
});

var chkScrollTimer = null;
function chkClientHeightScroll()
{
	//console.info('chkClientHeightScroll');
	
	//clearInterval(chkScrollTimer);

	var isHasScrollBar = hasScrollBar();
	if(!isHasScrollBar) {
		//return false;
	}

	var w = $(window).height();
	var d = $(document).height();
	var s = $(window).scrollTop();
	s = 0;


	if(isMainPage) {
		$('#main_block_top').css('top', s+'px');
		$('#main_block_top_shadow').css('top', (s + 33)+'px');
	} else {
		$('#page_top').css('top', s+'px');
		$('#page_top_shadow').css('top', (s + 33)+'px');
	}

	$('#main_block_top').css('position', 'fixed');
	$('#main_block_top_shadow').css('position', 'fixed');
	$('#page_top').css('position', 'fixed');
	$('#page_top_shadow').css('position', 'fixed');
	
	$('#menu_link_bg').css('top', (s + 33)+'px');
	$('#chat_link_bg').css('top', (s + 33)+'px');
	//console.log('#chat_link_bg : '+$('#chat_link_bg').css('top'));
	//$('#page_combobox_countries').css('top', (s + 5)+'px');
	$('#page_combobox_lang').css('top', (s + 5)+'px');


	$('#debug').css('top', (s + 80)+'px');

	var m = $('#main_frame').css('top');

	var p = $('#page_top').css('top');

	//console.log(p);

	$('#debug').html('<h2>page_top = '+p+'</h2>');

	//chkScrollTimer = setInterval("chkClientHeightScroll();", 500);
}
function chkClientHeightScrollTimer()
{
	if(!USE_FLOAT_MENU) {
		return false;
	}

	clearInterval(chkScrollTimer);

	chkClientHeightScroll();

	chkScrollTimer = setInterval("chkClientHeightScrollTimer();", 500);
}
$(window).scroll(function () { 
	if(USE_FLOAT_MENU) {
		//chkClientHeightScroll();
	}
});

