var layoutIT=true;

//navigator.appName=="Netscape"
var empties=new Array();
function init_layout(){
	if(!layoutIT) return;
//alert(window.navigator.userAgent);
/*
	
	if(navigator.appName=='Netscape') {
		alert('ОЙ-ей ей!!! А вы знаете, что ваш любимый шкаф не хочет работать с символическими ключами в массивах?');
		return false;
	}
*/
	//Настройки
	var marginObj=10;
	//Системные переменные
	//	Индексный массв обьектов
	var obj_order=new Array();
	//	Массив позиций для подстановок
	var places=new Array(), placesCNT=0;
	//		placesCNT нужен для отслеживания РЕАЛЬНОГО 
	//		количества позиций в массиве. чтобы не перебирать их каждый раз, 
	//		т.к. элемент не удаляется а опустошается...БЛЯ!
	var bodyHeight=0;
	//Для отслеживания разницы в высотах блоков
	var tmpmaxH=0,minAllowHDiff=300;
	//Нахожу основной контейнер
	var lbody=document.getElementById('layoutBody');
	

	//Удаляю заглушки (для ресайза, )
	for(var i=0; i<empties.length; i++){
		//document.removeChild(empties[i]);
		if(empties[i].parentNode)
			empties[i].parentNode.removeChild(empties[i]);
	}

	//Выставляю базовыю область для подстановок!
	var bw=(lbody.clientWidth>=500)?lbody.clientWidth:500;
	places.push( new Array(bw,0,0) ); placesCNT++;
	
	//Получаю всех, кого надо построить
	var objs=lbody.childNodes;

	//Фанка для определения, кто больше, а кто меньше
	function jCmp(x, y){
		//if(y==undefined){ alert('here'); return -1;}
		/*
		if (y.obj.attributes.title){
			if(x.obj.attributes.title) {
				if(x.obj.attributes.title.value > y.obj.attributes.title.value) return -1;
				else if(x.obj.attributes.title.value == y.obj.attributes.title.value) return 0;
				return 1;
			}else return 1;
		}else if(x.obj.attributes.title) return -1;

		if (x.width > y.width) return -1;
		else if (x.width == y.width){
			if (x.height > y.height) return -1;
			else if (x.height == y.height) return 0;
		}
		return 1;
		*/
		//Сравниваю по ширине
		if (x.width > y.width) return -1;
		else if (x.width == y.width){
			//СРавнение по высоте только если раздница больше 100 точек
			if( Math.abs(x.height - y.height)>150 ){
				if (x.height > y.height) return -1;
				else if (x.height == y.height) return 0;
			}else return 0;
		}
		return 1;
	}
		
	//фанка для сортировки областей по высоте
	function placeSort(x,y){
		if(x[2]<y[2]) return -1;
		else if(x[2]>y[2]) return 1;
		return 0;
	}
	
	function setEmptie( width, height , left, top, clr){
			var tmp=document.createElement("div");
			tmp.style.position='absolute';
			tmp.style.left=left+'px';
			tmp.style.top=top+'px';
			tmp.style.width=width+'px';
			tmp.style.height=height+'px';
			if(clr) tmp.style.backgroundColor=clr;
			empties.push(tmp);
			lbody.appendChild(tmp);
	}

	function fillEmpties(){
		for( var i=0; i<places.length; i++){
			if(places[i]==undefined || places[i][0]<0 || places[i][0]<95 || places[i][0]>430){ continue;}
			var height=(bodyHeight-places[i][2]);
			if(height<0) continue;
			var left=(places[i][1]+marginObj/2);
			var top=(places[i][2]+marginObj/2);
			var width=(places[i][0]);
			setEmptie( width, height , left, top );
		}
	}
	
	//Формирую индексный массив (состоит из реальной ширины,высоты обьекта и ссылки на сам обьект)
	for(var i=0 ; i<objs.length; i++){
		if(objs[i].nodeType==1 && objs[i].tagName.toLowerCase()=='div') {
			var tmp=new Array();
			tmp['width']=objs[i].offsetWidth;
			tmp['height']=objs[i].offsetHeight;
			tmp['obj']=objs[i];
			//objs[i].style.display='none';
			obj_order.push(tmp);
		}
	}
	//alert(obj_order);
	//Сортирую по убыванию линейных размеров (исходя из придчи о заполнении сoсуда камнями большими и малыми, как жизнь вещами - важными и мелкими)
	obj_order.sort(jCmp);
//for(var i=0, ts='',cnt=obj_order.length; i<cnt; i++)ts+="\n"+obj_order[i]['obj'].attributes['id'].value+') '+obj_order[i].width+'X'+obj_order[i].height; alert(ts);
	//Основной рабочий цикл - позиционирование
	var guard=0; //Предохранитель от зацикливания
	var debug=false;
//for(var j=0, ts=''; j<places.length; j++) ts+="\n"+places[j]; alert(ts);

	while (obj_order.length>0 && guard<100){
		var i=0; guard++; 
		//пропускаю, все обьекты, уже выставленные
		while(i<obj_order.length && obj_order[i].seted ) i++;
		
		if(i>=obj_order.length || obj_order.length<1) break;
		//Перебираю позиции в поисках подходящей по ширине для обьекта
		var found=false;
		for(var j=0; j<places.length && obj_order.length>0; j++){
			if((j==(places.length-1) && found==false)){
				fillEmpties();
				places=new Array();
				places.push( new Array(bw,0,bodyHeight+marginObj) ); placesCNT=1;
				j=0;
			}
			if(places[j]==undefined || places[j][0] < obj_order[i].width) continue;
			//нашел! - выставляю обьект
//alert(j+') left:'+ places[j][1]+' top:'+places[j][2]);
			obj_order[i].obj.style.left=places[j][1]+'px';
			obj_order[i].obj.style.top=places[j][2]+'px';
			obj_order[i].obj.style.position='absolute';
			found=true;
			//Отмечаю, что он уже выставлен
			obj_order[i].seted=true;
			//obj_order[i].obj.style.display='';
			//Отмечаю общую высоту контейнера
			bodyHeight=Math.max(bodyHeight, ( places[j][2]+obj_order[i].height ) );
			//добавляю новые позиции под и справа от обьекта
			if(places[j][0]-obj_order[i].width-marginObj>=100){//справа
				var nplace=new Array(places[j][0]-obj_order[i].width-marginObj, places[j][1]+obj_order[i].width+marginObj , places[j][2]);
				places.push(nplace); placesCNT++;
//setEmptie( nplace[0], 10 , nplace[1], nplace[2], '#f00');
			}
			if(obj_order[i].width>=100){//под
				var nplace=new Array(obj_order[i].width, places[j][1], places[j][2]+obj_order[i].height+marginObj);
				places.push(nplace); placesCNT++;
//setEmptie( nplace[0], 10 , nplace[1], nplace[2], '#f00');
			}
			//Удаляю старую позицию - ее больше нет.
			delete places[j]; placesCNT--;
			places.sort(placeSort);
			//выхожу из цикла - переходим к новому обьекту
			break;
		}
		if(!found){//Позиция для обьекта таки не найдена - он слишком большой
			obj_order[i].seted=true;
			obj_order[i].obj.style.display='none';
		}
	}
	lbody.style.height=bodyHeight+marginObj+'px';
	fillEmpties();
}
