var baseURL = 'http://' + window.location.host; // + '/evropa';

var init = function(){

    window.globalNS = {};
	globalNS.baseURL = baseURL;
    
						   
	var activeCompany = 'empty';	
	
	function getAbsolutePos(el)	{
    	var r = { x: el.offsetLeft, y: el.offsetTop };
    	if (el.offsetParent) {
    		var tmp = getAbsolutePos(el.offsetParent);
    		r.x += tmp.x;
    		r.y += tmp.y;
    	}
    	return r;
	}
	
	
	globalNS.toggle4leftpanel = function(id) {
		$('#'+id).slideToggle(250, globalNS.initBells); 
	}
	
	globalNS.bell = function(id) {
	    //initBell(id, selfId);
		var w = $('#'+id).width();
		var d = -(w/4);
		$('#'+id).animate({ left:d }, 200 );		
	}	
		
	globalNS.unbell = function(id) {
		var w = $('#'+id).width();
		var d = -(w-(w/4));
		$('#'+id).animate({ left:d }, 200 );		
	}
	
	//$('#bell_target').css({top:400px;});
	//$('#search_technics_container').hover(globalNS.bell('bell_target'),globalNS.unbell('bell_target'));
	
	globalNS.totalbell = function(id, selfId) {
		$('#'+id).show();
		var w = $('#'+id).width();
		var d = -(w/4);
	 	$('#'+id).animate({ left:d }, 300 );		
	}	
	
	globalNS.totalunbell = function(id) {
		/*var w = $('#'+id).width();
		var d = -(w-(w/4));
		$('#'+id).animate({ left:d }, 200 );*/
		$('#'+id).hide();
	}
		
    globalNS.initBell = function(id, selfId) {
		var h = $('#'+id).height();
		var r = getAbsolutePos(document.getElementById(selfId));
		document.getElementById(id).style.top = eval(r.y-(h/3))+"px";	
		var w = $('#'+id).width();
		var d = -(w-(w/4));
		document.getElementById(id).style.left = d+"px";	
	}	
		
	globalNS.initBells = function() {
		globalNS.initBell('bell_target', 'search_technics_link');
		globalNS.initBell('bell_wheel', 'auto_salers_link');
		globalNS.initBell('bell_bolt', 'service_salers_link');
		globalNS.initBell('bell_money', 'leasing_salers_link');
	}	
	
	//$('#search_technics_container').hover(globalNS.bell('bell_target'),globalNS.unbell('bell_target'));
		
	globalNS.hideCompaniesBells = function() {
//		if ($('#companies_container').is(':visible')) {
//			globalNS.totalunbell('bell_wheel');
//			globalNS.totalunbell('bell_bolt');
//			globalNS.totalunbell('bell_money');
//			} else {
//			globalNS.totalbell('bell_wheel');
//			globalNS.totalbell('bell_bolt');
//			globalNS.totalbell('bell_money');
//		}
		$('#bell_wheel').toggle()
		$('#bell_bolt').toggle()
		$('#bell_money').toggle()		
	}
		
	globalNS.hideSearchBells = function() {
		if ($('#search_technics_container').is(':visible')) {
			globalNS.totalunbell('bell_target');
		} else {
			globalNS.totalbell('bell_target');
		}
//		$('#bell_wheel').toggle()	
	}		
	
	function initSeparators() {
		globalNS.initBell('bell_target', 'search_technics_link');
		globalNS.initBell('bell_wheel', 'auto_salers_link');
	}	
		
	
	globalNS.toggle = function(id) {
		$('#'+id).slideToggle('normal'); 
		
		//поправим вид карты в ие6
		if($.browser.msie) {
			if(id == 'map_container') {
				$('#'+id).ifixpng();
				$('.sub_map_img2').css('margin-top','-471px');
				
			}
		}
		//setTimeout(globalNS.initModerations, 300);
		//что это значит, не понимаю. но после закомментирования пред. строки все нормально работает И в ИЕ ТОЖЕ
	}
		
	
		
	function getAbsolutePos(el)	{
    	var r = { x: el.offsetLeft, y: el.offsetTop };
    	if (el.offsetParent) {
    		var tmp = getAbsolutePos(el.offsetParent);
    		r.x += tmp.x;
    		r.y += tmp.y;
    	}
    	return r;
	}	
		
	globalNS.showSelect = function() {
		
		var bName = navigator.appName;
		var bVer = navigator.appVersion;
		
		$(".choose_type").show();
		
		var r = getAbsolutePos(document.getElementById('add_record'));
		
		if (bName == "Netscape") {
		    //	document.getElementById('choose_type').style.top = eval(r.y - document.getElementById('choose_type').offsetHeight)+"px";
			document.getElementById('choose_type').style.left = eval( (window.innerWidth/2)-(document.getElementById('choose_type').offsetWidth/2) )+"px";
					
	    } 
		
		if (bName == "Opera") {
			//	document.getElementById('choose_type').style.top = eval(r.y - document.getElementById('choose_type').offsetHeight)+"px";
			document.getElementById('choose_type').style.left = eval( (window.innerWidth/2)-(document.getElementById('choose_type').offsetWidth/2) )+"px";
		}
		
		if (bName == "Microsoft Internet Explorer") {
			document.getElementById('choose_type').style.left = eval( (document.body.clientWidth/2)-(document.getElementById('choose_type').offsetWidth/2) )+"px";
		} 
				
		document.getElementById('choose_type').style.top = eval(r.y-30)+"px";
		
		//фиксим ие6, чтобы селекты не просвечивали
		if ($.browser.version.slice(0,1) == 6) {
			$('#choose_type').prepend('<iframe width="620px" src="" height="100px" frameborder="0" style="filter: alpha(opacity=0);margin: 80px 0 -180px 0; background-color: red;border: 0px none;"></iframe>');
		}
	}	
		
	globalNS.hideSelect = function() {	
		$(".choose_type").hide();	
		if ($.browser.version.slice(0, 1) == 6) {
			$('#choose_type iframe').remove();
		}
	}
	
	globalNS.highlightSelect = function(id) {
		var path = $('#'+id).attr('src');
		var new_path = path.slice(0, -4)+"_active.jpg";
		$('#'+id).attr('src', new_path);
	}
	
	globalNS.unhighlightSelect = function(id) {	
		var path = $('#'+id).attr('src');
		var new_path = path.slice(0, -11)+".jpg";
	   	$('#'+id).attr('src', new_path);
	}
	
	globalNS.initSelects = function() {	
		<!--document.getElementById('').style.left-->
	}
	
	globalNS.initModerations = function() {	
		var i=0;
		$('div.catalog_moderation').each(function(){											   
		    document.getElementById('moderation_for_technics_'+i).style.width = document.getElementById('catalog').offsetWidth+"px";
		    document.getElementById('mark_moderation_'+eval(i)).style.marginTop = "10px";
		    document.getElementById('mark_moderation_'+eval(i)).style.marginLeft = "310px";
		
   		    //alert('mark_moderation_'+i);
		    i++;
		});	
	}
		
	globalNS.initBells();
	globalNS.initModerations();

	// перещелкивание картинок в профиле машины (one.tpl)
	$('.catalog_image_container').click(function(){
	    var old_small = $(this).find('img').attr('src');
	    var new_big = old_small.replace('thumbnails/tn_', 'images/');
	    var new_small = new String($('.catalog_big_photo_container').find('img').attr('src')).replace('images/', 'thumbnails/tn_');
	    if (!old_small.match(/nophotogruz\.gif/) && (new String(window.location)).match(/display/)) {
	        $(this).find('img').attr('src', new_small);
			//show preloader
			$('.catalog_big_photo_container').find('img').attr('src',  baseURL+'/theme/images/common/ajax-loader_big.gif');
	        //create new Image object to load what needed
			var bigImg = new Image();
			bigImg.onload = function () 
			{
				$('.catalog_big_photo_container').find('img').attr('src', new_big);
			}
			bigImg.src = new_big;
	    }
	});
	
	// перещелкивание картинок в аренде площадей (rent.tpl)
	$('.rent_catalog_image_container').click(function(){
	   
		var old_small = $(this).find('img').attr('src');
	    var new_big = old_small.replace('tn_', '');
	    var new_small = new String($('.catalog_big_photo_container').find('img').attr('src')).replace('area/', 'area/tn_');
		$(this).find('img').attr('src', new_small);
		// show preloader		
		$('.catalog_big_photo_container').find('img').attr('src', baseURL+'/theme/images/common/ajax-loader_big.gif');
		//create new Image object to load what needed
		var bigImg = new Image();
		bigImg.onload = function () 
			{
				$('.catalog_big_photo_container').find('img').attr('src', new_big);
			}
		bigImg.src = new_big;
	});
	
	// отправка формы сортировки
	$('.yellow_12_dashed').click(function(){
	    var order_by = $(this).attr('id').substr(5);
	    var current_direction = $('#sorting_order_direction').attr('value');
	    $('#sorting_order_by').attr('value', order_by);
	    $('#sorting_order_direction').attr('value', current_direction=='1'?'0':'1');
	    $('#recordsSorting').submit();
	});
	
	
	// валидация и поведение поля "перейти к ID"
	
	$('#displayById').click(function(){
	    if ($(this).attr('value')=='Перейти к ID') {
            $(this).attr('value', '');
	    }
	});
	
	$('#displayById').keyup(function(){
        if ((new String($(this).attr('value'))).match(/^\d+$/)) {
            $('#displayByIdButton').removeAttr('disabled');
        } else {
            $('#displayByIdButton').attr('disabled', 'true');
        }
    });
	
    $('#displayByIdButton').click(function(){
	   if (!$(this).attr('disabled')) window.location = baseURL + '/catalog/display/' + $('#displayById').attr('value');
	});
	
	
	// валидация формы добавления машины
	
	var validate = function ( field, validator, message, isRequired ) {

	    var fieldValue = $(field).attr('value') || new String();
	    
	    // alert(field + ' - ' + fieldValue);

        if (field=='#mark' && fieldValue=='other') {
                $(field).parent().attr('innerHTML', '<input type="text" id="mark" name="mark" style="width:210px;">');
                $('#mark').attr('value', '');
                $('#mark').keyup(acceptForm); // обновляю хэндлер, потому что он сгинул
                globalNS.acceptForm = false;
                return;
           
        }
	    
        if ( fieldValue.match(new RegExp(validator)) ) {
            $(field+'_validation').attr('innerHTML', '');
        } else {
            if (fieldValue == '') {
                if (isRequired) {
                    $(field+'_validation').attr('innerHTML', 'Поле должно быть заполнено');
                    globalNS.acceptForm = false; 
                }
            } else {
                $(field+'_validation').attr('innerHTML', message);
                globalNS.acceptForm = false;
            }
        }
	    
        
	}
	
	var acceptForm = function() {
	    globalNS.acceptForm = true;
	
   	    validate('#model', /^[^\s]\w+/, 'Укажите модель', true);
   	    validate('#year', /^\d{4}$/, 'Укажите год (ГГГГ)', true);
   	    validate('#price', /^\d+$/, 'Укажите число', true);
   	    validate('#run', /^\d*$/, 'Укажите число', false);
        validate('#mark', /^[1-9a-zA-Z]/, 'Выберите марку из списка или укажите свою', true);

   	    
	    if (globalNS.acceptForm && $('#photo').attr('value')) {
	        $('#formSubmit').removeAttr('disabled');
	    } else {
	        $('#formSubmit').attr('disabled', true);
	    }
	}
	
	acceptForm(); // initializing (required when editing)
	$('#record').find('input').change(acceptForm);
	$('#record').find('input').keyup(acceptForm);

	$('#record').find('select').change(acceptForm);
//	$('#record').blur(acceptForm);	

   //$('body').resize(globalNS.initModerations);
   //не знаю что это было. без него работает
   
	
	//верстка
	
	//задаем всем 'block-level elements' в #catalog_container высоту 101% - хак для нормальной работы jQuery slideToggle в IE
   	$('#catalog_container').children('div','table','td','form').css( "height", "101%" );
	//прозрачные пнгшки в ие6
	if($.browser.msie) {
		$('img[@src$=.png]').ifixpng(); 
	}
	
	//--верстка
	
	//preload preloader
	var preloader_img = new Image();
	preloader_img.src = baseURL+'/theme/images/common/ajax-loader_big.gif';
	
};

// $(document).ready(function(){setTimeout(init, 10)});
$(document).ready(function(){setTimeout(init, 0)});