function printOpenBlock(object,wUgol,hUgol) {
document.writeln(
"	<TABLE cellspacing='0' class='"+object+"'>"
+"	<TR>"
+"		<TD><img src='/i/"+object+"_ugol_1.gif' width='"+wUgol+"' height='"+hUgol+"'></TD>"
+"		<TD class='top'></TD>"
+"		<TD><img src='/i/"+object+"_ugol_2.gif' width='"+wUgol+"' height='"+hUgol+"'></TD>"
+"	</TR>"
+"	<TR>"
+"		<TD class='left'></TD>"
+"		<TD class='body'>"
);
}

function printCloseBlock(object,wUgol,hUgol) {
document.writeln(
"		</TD>"
+"		<TD class='right'></TD>"
+"	</TR>"
+"	<TR>"
+"		<TD><img src='/i/"+object+"_ugol_4.gif' width='"+wUgol+"' height='"+hUgol+"'></TD>"
+"		<TD class='bottom'></TD>"
+"		<TD><img src='/i/"+object+"_ugol_3.gif' width='"+wUgol+"' height='"+hUgol+"'></TD>"
+"	</TR>"
+"	</TABLE>"
);
}

function win() {
subscribe=window.open("","subscribe","width=300,height=200,top=0,left=0,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no");
subscribe.document.open();
subscribe.document.write("<html><head><title>SR Subscribe v1.0</title><style> a:link {font-size: 11px; color: #6060B0; font-weight: normal; text-decoration: none} a:visited {font-size: 11px; color: #6060B0; font-weight: normal; text-decoration: none} a:active {font-size: 11px; color: #6060B0; font-weight: normal; text-decoration: none} a:hover {font-size: 11px; color: #000000; font-weight: normal; text-decoration: none}</style></head><body topmargin='0' leftmargin='0' marginwidth='0' marginheight='0'><table width='300' height='200' border='0' cellspacing='0' cellpadding='0'><tr><td height='180' align='center' valign='middle' style='font-family:Verdana;font-size:11px;'>Идет подписка, ждите...</td></tr><tr><td height='20' align='center' valign='middle'><a href='http://www.sad-raven.ru/' target='_blank'><font style='font-family:Verdana;font-size:9px;color:#CCCCCC'>SR Subscribe v1.0 &copy; 2002</font></a></td></tr></table></body></html>");
subscribe.document.close();
document.sr_subscribe.submit();
}

function openWindow(url,width,height) {
win = window.open("","win","width="+(width+22)+", height="+(height+22)+",top=0,left=0, titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes");
win.document.open();
win.document.write("<html><head><title></title></head><body style='margin:0px; padding:10px; background:#D7DAEB;'><img style='border:1px solid white;' src='"+url+"'></body></html>");
win.document.close();
}


function zapis() {
	window.open("/zapis/", "zapis", "width=500, height=410, titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes");
}
function zapis_and_skidka() {
	window.open("/zapis/form_and_skidka.php", "zapis", "width=700, height=410, titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes");
}


function opros() {
	window.open("/opros/", "opros", "width=600, height=500, titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes");
}

function medal() {
	window.open("/medal.html", "medal", "width=360, height=200, titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes");
}

function happy_zub() {
	window.open("/happy_zub/", "happy_zub", "width=500, height=500, titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes");
}


try{
	document.execCommand("BackgroundImageCache", false, true);
} catch(e) {
	
}

/*
 * 
 * Работает только для Png в background
 * Нужно применять также и для IE чтобы анимация прозрачности правильно работала с png прозрачностью
 * (в противном случае будет черная рамочка)
 * 
 */


document.write('<style>');
document.write('.png {-filter: expression(fixPNG(this));}');
document.write('.allie_png {filter: expression(fixPNG(this));}');
document.write('</style>');


/*
 * РљР°Рє РёСЃРїРѕР»СЊР·РѕРІР°С‚СЊ
 * Р’ CSS-С„Р°Р№Р»Рµ РЅР°РїРёСЃР°С‚СЊ С‚Р°РєРѕРµ РїСЂР°РІРёР»Рѕ:
 * .png{
 * 	filter: expression(fixPNG(this));
 * }
 */

var arVersion = navigator.appVersion.split("MSIE");
var ie_version = parseFloat(arVersion[1]);

function fixPNG(element) {
	var src;
	
	if(!ie_version) return true;
	
	//пропускаем png в теге img
	//так как все равно не работает
	if(element.tagName == 'IMG') return true;
	
	if (element.tagName == 'IMG') {
		if (/\.png$/.test(element.src)) {
			src = element.src;
			element.src = "/i_lebed/space.gif";
		}
	} else {
		src = element.currentStyle.backgroundImage
				.match(/url\("(.+\.png)"\)/i)
		if (src) {
			src = src[1];
			element.runtimeStyle.backgroundImage = "none";
		}
	}

	var re_scale_mode = /iesizing\-(\w+)/;
	var m = re_scale_mode.exec(element.className);

	var scale_mode = (m) ? m[1] : 'crop';
	
	if (src)
		element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"
				+ src + "',sizingMethod='" + scale_mode + "')";
}


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


if(!window.Cude) Cude = {};


// ********Определение браузеров 100% работает и пока багов не заметно **************
isMSIE = '\v'=='v';
isMSIE8 = (isMSIE && typeof window.localStorage == 'object') ? true : false;
isFF=/a/[-1]=='a'; 						//Firefox detector 2/3 by DoctorDan
isFF3=(function x(){})[-5]=='x'; 		//Firefox 3
isFF2=(function x(){})[-6]=='x'; 		//Firefox 2
isSafari=/a/.__proto__=='//'; 				//Safari
isChrome=/source/.test((/a/.toString+'')); //Chrome



//создает точку и устанавливает ее в нужной точке экрана
//если точка уже создана, просто перемещает на новое место
Cude.point = function(name, x, y) {
	if($('#'+name.d()).text()) {
		$('#'+name.d()).css({left:x+'px', top:y+'px'});
		return true;
	}
	
	$('body').prepend('<div id="'+name+'" style="position:absolute; background:orange; width:10px; height:10px; ">'+name+'</div>');
	
	$('#'+name.d()).css({left:x+'px', top:y+'px'});
}


Cude.random = function(min,max) {
	var range = max + 1 - min;
	var n = Math.floor(Math.random()*range) + min;
	return n;
}

function explode( delimiter, string ) {   
    // http://kevin.vanzonneveld.net   
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
    // +   improved by: kenneth   
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)   
    // *     example 1: explode(' ', 'Kevin van Zonneveld');   
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}   
    
    var emptyArray = { 0: '' };   
    
    if ( arguments.length != 2   
        || typeof arguments[0] == 'undefined'   
        || typeof arguments[1] == 'undefined' )   
    {   
        return null;   
    }   
    
    if ( delimiter === ''   
        || delimiter === false   
        || delimiter === null )   
    {   
        return false;   
    }   
    
    if ( typeof delimiter == 'function'   
        || typeof delimiter == 'object'   
        || typeof string == 'function'   
        || typeof string == 'object' )   
    {   
        return emptyArray;   
    }   
    
    if ( delimiter === true ) {   
        delimiter = '1';   
    }   
    
    return string.toString().split ( delimiter.toString() );   
}

/*//Работает но например к меню не смогли прикрутить
$(document).ready(function(){
    $('[@ten]').each(function(){
    	var ten_class = $(this).attr('ten'); //берем имя класса тени
		$(this).textDropShadow(ten_class)//далее работает функция, которая в качестве параметра получает название класса тени
    });
});
(function($) {
     $.fn.textDropShadow = function(ShdwClass){//элементы заменяются. Вместо оригинала внутри будет два спана - один содержащий сам текст, а другой тень этого текста.
     $(this).css('position','relative').html('<span class='+ShdwClass+'>'+$(this).html()+'</span><span style="position:relative;">'+$(this).html()+'</span>');
     return $(this);
     }
})(jQuery);
*/




/* оформляет блоки как хочется. Скругленные уголки и прочая фигня */

/*

---------------------- Пример -------------------
<style>
.f_legend .content {color:red; padding:2px 10px 2px 10px;}
.f_legend TABLE {background:none;}
</style>
<div class='f_legend' type='js_block' image_folder='i' block_width='500'>Привет</div>
-------------------------------------------------

Можно использовать как стандартные 8 картиночные блоки так и с меньшим кол-вом. Например когда есть левая сторона, фон и правая сторона

*/

$(document).ready(
	function() {
		while(true) {
			document.obr_block = false;
			//alert('while');
			
			$("DIV[@type='js_block']").each(function() {
				
				/* если за эту итерацию один блок обработали, останьные пропускаем */
				if(document.obr_block == true) {
					//alert('s');
					return true;
				}
				
				/* если блок уже обработан, пропускаем его */
				if($(this).attr('obr') == 'yes') {
					//alert('g');
					return true;
				}
				
				//alert('f');
				
				document.obr_block = true;
				$(this).attr('obr', 'yes');
				
				pref = $(this).attr('class');
				block_width = $(this).attr('block_width');
				image_folder = $(this).attr('image_folder');
				background_color = $(this).attr('background_color');
				path = image_folder+"/"+pref+"_";
				
				str_do = 
				/* обычный вариант (когда 8 картинок). Первый угол может быть большим, чтобы какой то понтов */
				/* сначало идут линии */
				"<div style='background:url("+path+"l1.png) repeat-x left top'>"+
				"<div style='background:url("+path+"l2.png) repeat-y right top'>"+
				"<div style='background:url("+path+"l3.png) repeat-x left bottom'>"+
				"<div style='background:url("+path+"l4.png) repeat-y left top'>"+
				/* углы (они могут быть большого размера, чтобы както эффект замутить) */
				"<div style='background:url("+path+"u1.png) no-repeat left top'>"+
				"<div style='background:url("+path+"u2.png) no-repeat right top'>"+
				"<div style='background:url("+path+"u3.png) no-repeat right bottom'>"+
				"<div style='background:url("+path+"u4.png) no-repeat left bottom'>"+
				/* контейнер (его стиль нужно самому писать)*/
				"<div class='content'>";
				
				str_posle = "</div></div></div></div></div></div></div></div></div>";
				
				content = $(this).html();
				
				/* чтобы блок растягивался а не занимал сразу все пространство помещаем его в таблицу (можно задать ширину) */
				str_do = "<table class='smart_resize' s_tyle='background:"+background_color+"' width='"+block_width+"' cellspacing=0 cellpadding=0><tr><td width='100%'>" + str_do;
				str_posle = str_posle + "</table>";
				
				$(this).html(str_do + content + str_posle);
			});
			
			if(document.obr_block == false) break;
		}
	}
);


jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		guid: 1,
		global: {},
		regex: /^([0-9]+)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			if (!element.$timers) 
				element.$timers = {};
			
			if (!element.$timers[label])
				element.$timers[label] = {};
			
			fn.$timerID = fn.$timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.$timerID = fn.$timerID;
			
			if (!element.$timers[label][fn.$timerID]) 
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
			
			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = element.$timers, ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.$timerID ) {
							window.clearInterval(timers[label][fn.$timerID]);
							delete timers[label][fn.$timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					element.$timers = null;
			}
		}
	}
});

if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		var global = jQuery.timer.global;
		for ( var label in global ) {
			var els = global[label], i = els.length;
			while ( --i )
				jQuery.timer.remove(els[i], label);
		}
	});




//Пример использования: $.preloadImages(['/i/wait16.gif', '/i/wait18.gif']);
$.preloadImages = function(preload){ 
	$(document.createElement('img')).bind('load', function(){ 
		if(preload[0]) this.src = preload.shift(); 
	}).trigger('load'); 
}


//автоматическая загрузка картинок с параметром preload=true
$(document).ready(function() {
	$('img[@preload=true]').each(function() {
		var image_url = $(this).attr('src');
		$.preloadImages([image_url]);
	});
	
});



//ручная загрузка элементов интерфейса
$.preloadImages([
'/i_lebed/close.png'
]);





//экранирует символ точки двойным. ТЕПЕРЬ ЭТО МЕТОД ЛЮБОЙ СТРОКИ! 
String.prototype.d = function() {
	return this.replace(/\./g, '\\.');
}


/*
$(document).ready(function() {
	$('.SuperMenu').find('A').each(function() {
		text_link.replace();
	});
});
*/


if(typeof window.openWindow == 'undefined') {
	function openWindow(url,width,height) {
		
		url = url.replace(/\.$/, '');
		url = url.replace(/\.(gif|jpg)/, '');
		
		win = window.open("","win","width="+(width+22)+", height="+(height+22)+",top=200,left=200, titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes");
		win.document.open();
		win.document.write(
				"<html>" +
				"<head>" +
					"<script type='text/javascript' src='/jquery-1.2.6.min.js'></script>" + 
					"<title></title>" +
				"</head>" +
				"<body style='margin:0px; padding:10px; background:#D7DAEB;'>" +
					"<center><img style='border:1px solid white;' src='"+url+".jpg' onError='$(this).hide()' onLoad='window.resizeTo($(this).width() + 100, $(this).height() + 100)'></center>" +
					"<center><img style='border:1px solid white;' src='"+url+".gif' onError='$(this).hide()' onLoad='window.resizeTo($(this).width() + 100, $(this).height() + 100)'></center>" +
				"</body>" +
				"</html>");
		win.document.close();
	}
}

if(typeof window.zapis == 'undefined') {
	function zapis() {
		window.open("/zapis/", "zapis", "width=500, height=410, titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=yes");
	}
}




$(document).ready(function() {
	
	/*
	//если человек еще не щелкал по ссылке музыки делаем ее более яркой
	if(!$.cookie('is_first_click_music_button')) {
		$('#music_nota').find('A').text('Включить легкую музыку?');
		
		$('#music_nota').find('A').css({
			'color':'orange',
			'font':'bold 15px Verdana',
			'border-bottom': '1px dashed #E3884A'
		});
		
		$('#music_nota').css({
			'background-image':'url(/i/music_nota.gif)'
		});
	}*/
	
	//обрабатываем нажатие на ссылку
	$('#music_nota').find('A').click(function() {
		$.cookie('is_open_window_music', 1);
		
		$('#mju').html(''); //закрываем плеер на основной странице
		
		music_window = window.open("/music/player.html","music_window","width=170,height=110,top=0,left=0,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no");
		music_window.focus();
		
		/*
		$('#music_nota').find('A').text('Показать проигрыватель');
		$('#music_nota').find('A').css({
			'color':'#999',
			'font':'bold 12px Verdana',
			'border-bottom': '1px dashed silver;'
		});
		$('#music_nota').css({
			'background-image':'url(/i/music_nota_fade.gif)'
		});*/
	});
	
	
	
	/*
	отключили потому что нам не надо чтобы плеер постоянно вылезал
	//При переходе на другую страницу, открываем и запускаем плеер, если он не открыт (данных храняться в куках)
	$('a').click(function() {
		//если окно открыто, ничего не делаем
		if($.cookie('is_open_window_music')) return true;
		
		//окна нет, открываем его
		$('#mju').html(''); //закрываем плеер на основной странице
		
		//ставим куку что плеер открыт
		$.cookie('is_open_window_music', 1);
		
		//открываем плеер в отдельном окне
		music_window = window.open("/music/player.html","music_window","width=170,height=110,top=0,left=0,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no");
	});*/
});





var opera = Boolean(window["opera"]);
var ie = (navigator.appName.indexOf("Microsoft") != -1) && !opera;

function mju_play_track(num) {
	if (num <= 0) return false;
	var mc = ie ? window.mju : window.document.mju;
	mc.SetVariable("play_track",num);
}

function mju_play_file(chars) {
	if (!chars.length) return false;
	var mc = ie ? window.mju : window.document.mju;
	mc.SetVariable("play_file",chars);
}

function mju_do(cmd) {
	if (!cmd.length) return false;
	var mc = ie ? window.mju : window.document.mju;
	mc.SetVariable("do_"+cmd," ");
}



za4 = {
	'ten':false,
	'current_block': false,
	'height': 430,
	'block_width':600,
	'block_height':380
};


//устанавливанием размеры блоков (они фиксированные)
$(document).ready(function() {
	$('.za4_ten').css({'height':za4.height + 'px'});
	$('.za4_block').css({'width':za4.block_width + 'px', 'height':za4.block_height + 'px'});
	
	//РАСКРАШИВАЕМ ТАБЛИЦЫ СРАВНИТЕЛЬНЫХ ЦЕН
	//зелененьким нас
	$('.za4_price').find('tr').find('td:nth-child(2)').each(function() {
		var content = $(this).html();
		content = content.replace(/(\d+)/g, '<span style="color:green">$1</span>');
		$(this).html(content);
	});
	//красненьким конкурентов
	$('.za4_price').find('tr').find('td:nth-child(3)').each(function() {
		var content = $(this).html();
		content = content.replace(/(\d+)/g, '<span style="color:red">$1</span>');
		$(this).html(content);
	});
	
	
	//НАГРАДЫ
	$('.za4_nagrady').find('img').each(function() {
		var text = $(this).attr('alt');
		var image_url = $(this).attr('src');
		image_url = image_url.replace('small', 'big');
		image_url = image_url.replace(/gif$|jpg$/, '');
		$(this).after('<div class="za4_nagrady_podpis"><a href="javascript:void(0);"  onClick="openWindow(\''+image_url+'\',600,600);" style="color:#555;  text-decoration:none;">'+text+'</a></div>');
	});
});


za4.show = function(block_name) {
	//показать тень если нет
	if(!this.ten) {
		$('#za4_ten').fadeIn(300);
		this.ten = true;
	}
	
	//если открыт этот же блок, ничего не делаем (по хорошему надо подсвечивать ссылку)
	if(this.current_block == block_name) return true;
	
	//скрыть текущий блок (если есть)
	if(this.current_block) {
		$('#' + this.current_block)
			.attr({'name':this.current_block})
			.hide();
			//.fadeOut(300);
			/*.animate({left: "-=300"}, 300,
				function(){
					$(this).css({display:'none'})		
				}
			);*/
	}
	
	var x_center = $(window).width() / 2 - za4.block_width/2;  
	
	//выбрать блок, запустить анимацию
	$('#' + block_name)
		.css({display:'block', left:(x_center+300) + 'px', top:($('#za4_ten').position()['top']+10)+'px'/*, opacity:0*/})
		.animate({/*opacity: "50", */left: "-=300"}, 500)
		//.show();
	
	this.current_block = block_name;
}

za4.close = function() {
	//скрыть текущий блок (если есть)
	$('#' + this.current_block)
		.attr({'name':this.current_block})
		.hide();
		/*.animate({opacity: "0", left: "-=300"}, 300,
			function(){
				$(this).css({display:'none'})		
			}
		);*/
	
	$('#za4_ten').fadeOut(300);
	
	this.current_block = '';
	this.ten = false;
}








// --------------- ПАЦИЕНТЫ ---------------

patients = {
	'min': 1,
	'max': 19,
	'num_onpage': 2,
	'shag_top': 110,
	loading_foto_now:[] //массив, пока не используем!
	
	// определяем когда документ загружен
	// 'start_left': 700, 
	// 'start_top': 200
};


$(document).ready(function() {
	
	//определяем, есть ли на этой странице фотки пациентов
	if(!$('#patsienty_start_point').length) return false;
	
	//координаты стартовой точки для пациентов
	patients.start_left = $('#patsienty_start_point').position().left;
	patients.start_top = $('#patsienty_start_point').position().top;
	
	//запускаем первый раз
	patients.show();
});


//перемещаем
$(window).bind('resize', function() {
	
	//координаты стартовой точки для пациентов
	patients.start_left = $('#patsienty_start_point').position().left;
	patients.start_top = $('#patsienty_start_point').position().top;
	
	for(var nomer in patients.patient_nomer_mas) {
		$('#patient_' + nomer).css({'left': patients.start_left + Cude.random(-5,5) + 'px'});
	}
	
	
	
	//запускаем первый раз
	//patients.show();
});


patients.show = function() {
	//выбираем произвольные фотки
	this.patient_nomer_mas = [];
	var i = 0;
	while(i < this.num_onpage) {
		var random_nomer = Cude.random(this.min, this.max);
		if(this.patient_nomer_mas[random_nomer]) continue; //если уже есть такой номер
		
		this.patient_nomer_mas[random_nomer] = 1;
		i ++;
	}
	
	//alert(patients.start_left + ' ' + patients.start_top);
	
	//скрываем предыдущие если есть
	//if(this.is_view) {
		$('[@id^=patient_]').each(function() {
			//переименовываем блок чтобы не было колизий
			$(this).attr('id', 'for_del' + Cude.random(1000,10000));
			
			
			/*$(this).animate({top: '-='+patients.shag_top+'px', opacity:0}, 300, function() {
				//console.log('Удаляем' + this);
				$(this).remove(); //удаляем, самое оптимальное
				//$(this).css({display:'none', left:-1000, top: -1000});
			});*/
			
			$(this).hide().remove();
			
			
		});
	//}
	
	var isIe = navigator.appVersion.split("MSIE");
	var ie_version = parseFloat(arVersion[1]);
	
	var i = 0;
	this.new_top = this.start_top; //изменять будем new_top
	//показываем новые
	for(var nomer in this.patient_nomer_mas) {
		i ++;
		//создаем фотографию
		
		var filename = "/patients/foto/"+nomer+".png";
		var style= "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\""+filename+"\", sizingMethod=\"crop\")";
		if(ie_version == 6) {
			$('body').append("<div id='patient_"+nomer+"' style='display:block; position:absolute;'><img src='/i_lebed/space.gif' style='"+style+"' width='180' height='150'></div>");	
		}
		else {
			$('body').append("<div id='patient_"+nomer+"' style='display:block; position:absolute;'><img src='"+filename+"' width='180' height='150'></div>");
		}
		
		
		//Cude.point('patient_' + nomer, this.start_left, this.start_top);
		
		//устанавливаем координаты куда она должна в итоге оказаться
		$('#patient_' + nomer).attr({'start_left': this.start_left + Cude.random(-5,5), 'start_top': this.new_top});
		this.new_top = this.start_top + this.shag_top*i + Cude.random(0, 7);
		
		//console.log("this.start_top : " + this.new_top);
		
		//вешаем событие на загрузку фотографии, чтобы анимация сработала когда фотка реально загрузится
		$('#patient_' + nomer).find('img').attr('nomer', nomer).bind('load', function() {
			console.log('Фото загрузилось');
			
			var nomer = $(this).attr('nomer');
			var start_left = parseInt($('#patient_' + nomer).attr('start_left'));
			var start_top = parseInt($('#patient_' + nomer).attr('start_top'));
			
			start_top += patients.shag_top; //делаем смещение для анимации
			
			//console.log(start_top);
			
			//ставим на позицию, запускаем анимацию показа
			$('#patient_' + nomer)
				//.css({'-moz-opacity':0, 'filter':'alpha(opacity=0)', 'opacity':0})
				.css({display:'block'})
				.css({left:start_left+'px', top:start_top+'px'});
				
			$('#patient_' + nomer).animate({'top': '-=' + patients.shag_top + 'px', o_pacity:100}, 300, function(){});	
		});
		
	}
	
}


function random(min,max) {
	var range = max - min;
	var n = Math.floor(Math.random()*range) + min;
	return n;
}

compactGallery = {};
compactGallery.count = 0;

compactGallery.coords_mas = {top:0,left:0};

//создает надписи в нужном месте или перемещает если уже созданы
compactGallery.create_and_move_label = function() {
	$('.compact_gallery').each(function() {
		
		//размеры превьюшек берем из тега обрамляющего галерею, атрибут preview_size='..x..'
		var temp = explode('x', $(this).attr('preview_size'));
		compactGallery.preview_width = temp[0];
		compactGallery.preview_height = temp[1];
		
		$(this).find('img').each(function() {
			//нумеруем тег img или берем его номер если есть
			if(compactGallery.isCreateLabel) {
				var nomer = $(this).attr('nomer');
			}
			else {
				//нумеруем тег, чтобы знать номер его текста и дымки
				$(this).attr('nomer', compactGallery.count);
				var nomer = compactGallery.count;
				compactGallery.count ++;
			}
			
			
			var text = $(this).attr('alt');
			var image_url = $(this).attr('src');
			
			var temp = explode('/', text);
			text_small = temp[0];
			
			image_url = image_url.replace('small', 'big');
			image_url += '?'+random(1000,90000); //чтобы заново загружал а не из кеша брал
			
			var width = compactGallery.preview_width;
			var height = compactGallery.preview_height;
			var left = $(this).offset().left;
			var top = $(this).offset().top;
			
			//в ie почему-то координаты ошибочны на 2 px, исправляем
			if(isMSIE && !isMSIE8) {
				left -=2;
				top -= 2;
			}
			
			//устанавливаем размер картинок в сам тег img
			//$(this).css({width:width+'px', height:height+'px'});
			
			/* ВЕРСИЯ С ПОЛНОЙ ДЫМКОЙ
			$(this).after(
				'<div class="cg_dymka" style="width:'+width+'px; height:'+height+'px; left:'+left+'px; top:'+top+'px; "></div>'+
				'<div class="cg_text" style="width:'+width+'px; height:'+height+'px; left:'+left+'px; top:'+top+'px; ">'+
					'<table cellpadding="0" cellspacing="0" style="width:100%;height:100%">'+
					'<tr valign="bottom"><td>'+text+
					'</table>'+
				'</div>'
				);
			*/
			
			/*width -= 2;
			left += 1;
			top +=1;*/
			
			//ВЕРСИЯ С ДЫМКОЙ ТОЛЬКО ПОД ТЕКСТОМ
			//создаем дымку если не создана
			if(!compactGallery.isCreateLabel) {
				$(this).after(
					'<div class="cg_dymka" id=cg_dymka_'+nomer+' style="width:'+width+'px; height:'+height+'; left:'+left+'px; top:'+top+'px; -moz-opacity:0.8; filter:alpha(opacity=80); opacity:0.8;"></div>'+
					'<div class="cg_text"  id=cg_text_'+nomer+' style="width:'+width+'px; left:'+left+'px; top:'+top+'px; ">'+
						'<table cellpadding="0" cellspacing="0" width="100%" height="100%">'+
						'<tr valign="middle"><td>'+text_small+'<div class="zoom"><u>увеличить</u></div>'+
						'</table>'+
					'</div>'+
					'<a class="cg_link" id=cg_link_'+nomer+' href="'+image_url+'" target="_blank" preview=1 style="width:'+width+'px; height:'+height+'; left:'+left+'px; top:'+top+'px; "><img src="/i/space.gif" class="cj_space" width='+width+' height='+height+'></a>'
					);
				
				//растягиваем дымку чтобы она полностью покрывала пространство под текстом
				/*text_height = $('#cg_text_'+nomer).height();
				$('#cg_dymka_'+nomer).css({height:text_height+'px'});
				*/
				
				//события для появления и пропадания текста
				$('#cg_link_'+nomer).bind('mouseover', {count:nomer}, function(e) {
					$('#cg_dymka_'+e.data.count).fadeIn(150);
					$('#cg_text_'+e.data.count).fadeIn(150);
				});
				$('#cg_link_'+nomer).bind('mouseout', {count:nomer}, function(e) {
					$('#cg_dymka_'+e.data.count).fadeOut(150);
					$('#cg_text_'+e.data.count).fadeOut(150);
				});
			}
			//если дымка существует, просто передвигаем ее и надпись
			else {
				//console.log(nomer);
				
				$('#cg_dymka_'+nomer).css({left:left, top:top});
				$('#cg_text_'+nomer).css({left:left, top:top});
				$('#cg_link_'+nomer).css({left:left, top:top});
			}
		});
	});
	
	compactGallery.isCreateLabel = true;
}


//формируем надписи на картинках
$(document).ready(function() {	compactGallery.coords_mas = $('.compact_gallery').position();	compactGallery.create_and_move_label();
});

/*
//перемещаем надписи если изменился размер экрана
$(window).bind('resize', function() {
	compactGallery.coords_mas = $('.compact_gallery').position();
	compactGallery.create_and_move_label();
});*/

//Отслеживает, не сместились ли фотографии в результате загрузки другого контента и если сместились, перемещает надписи
//Ограничение! Нельзя использовать несколько блоков картинок.
setInterval('compactGallery_check_position()', 1000);
compactGallery_check_position = function() {
	var new_coords = $('.compact_gallery').position();
	if(compactGallery.coords_mas['top'] != new_coords['top'] || 
		compactGallery.coords_mas['left'] != new_coords['left']
	) {
		console.log(new_coords);
		compactGallery.coords_mas = new_coords;
		compactGallery.create_and_move_label();
	}
}


/*
 * В идеале при клике по ссылке для большой фотографии, нужно стараться поместить фото над ссылкой
 * чтобы не загораживать соседние ссылки (верхние правда полюбому будут скрыты)
 * 
 * Несколько интесных вариантов:
 * №1. фотку помещаем сверху. Когда мышка наезжает на фотку и под ней что нибудь есть -> фотка исчезает. При двойном клике по ссылке(это надо как то обозначить), фотка намертво встает там
 * №2. фотку помещаем сверху. Когда мышка попадает на фотку, она убегает вверх.
 * 
 * Пожалуй №2 на данный момент лучшие вариант 
 * */

preview = {
	'add_to_width':65
};
preview.open =  function(e, obj, url) {
	//$('#preview_window').remove();
	
	if(!preview.create_window) {
		//создаем окошко
		$('body').append('<div id="preview_window" style="position:absolute; display:none"><div style="text-align:left; font-size:12px; margin-bottom:5px;color:#eee"><a href="javascript:void(0)" onClick="preview.close()" style="color:white;"><b>Закрыть</b></a> (не обязательно)</div><div id="for_image"></div></div>');
		$('#preview_window').css({margin:'0px', padding:'5px 7px 7px 7px', background:'#263d60', display:'block'});
		preview.create_window = true;
	}
	
	preview.obj_to_click = obj;
	
	$('#preview_window').find('#for_image').html();
	
	resize.start_control($('#preview_window'));
	
	$('#preview_window').bind('change_size', function() {
		preview.move();
		$('#preview_window').unbind('change_size');
	});
	
	resize.stop_check_obj = obj;
	
	param = "$('#preview_window')";
	
	//запускаем загрузку картинки
	$('#preview_window').find('#for_image').html('<img style="color:yellow" src="'+url+'" alt="Загрузка...">');
	
	preview.move();
}

preview.move = function() {
	var obj = preview.obj_to_click;
	
	 //var e = e || window.event;
	 //var x = e.clientX + $(window).scrollLeft();
	 //var y = e.clientY + $(window).scrollTop() + 30;
	
	 var x = $(obj).position().left;
	 var y = $(obj).position().top + this.add_to_width;
	 
	 //ширина картинки
	 var width = $('#preview_window').width();
	 //width += this.add_to_width;
	 
	 //центрируем окно
	 x = x - width/2 + $(obj).width()/2;
	 
	 //смещаем если вышло за пределы браузера (создало горизонтальную прокрутку)
	 ugol_right = x + width;
	 ugol_left = x;
	 
	 //если вышло за правую сторону
	 //даже прокрутку учитываем!!!
	 if(ugol_right > $(window).width() + $(window).scrollLeft()) {
	 	//console.log()
	 	
	 	x = x - (ugol_right - ($(window).width() + $(window).scrollLeft())) - 30;
	 	//console.log('вышло за правую сторону', x);
	 }
	 else if(ugol_left < 0) {
	 	x += ugol_left*(-1);
	 	//console.log('вышло за левую сторону');
	 }
	 
	 //запускаем анимацию
	 $('#preview_window').animate({left:x, top:y}, 400);
	 
	 //$('#preview_window').css({left: x + 'px', top: y+'px'});
}

preview.close = function() {
	preview.create_window = false;
	$('#preview_window').remove();
}

resize = {};
//начало слежение за объектом
resize.start_control = function(jobj) {
	var width = jobj.width();
	var height = jobj.height();
	
	jobj.attr({resize_do_width:width, resize_do_height:height});
	
	jobj.everyTime(10, function() {
		resize.check_change($(this));
	});
}

//проверяет, изменился ли размер
resize.check_change = function(jobj) {
	
	//если изменился
	if(jobj.attr('resize_do_width') != jobj.width() || jobj.attr('resize_do_height') != jobj.height()) {
		
		//проверяем чтобы размер был большим, долго объяснять почему :)
		if(jobj.width() < 110) return false;
		
		resize.stop_check(jobj);
	}
}

resize.stop_check = function(jobj) {
	jobj.stopTime();
	jobj.trigger('change_size');
	console.log('Останавливаем проверку размера');
}


$(document).ready(function() {
	if(window.nizhe_ie7) return true;
	
	$('A[@preview=1]').each(function() {
		
		var href = $(this).attr('href');
		var href_old = href;
		href = href.replace(/(\d)$/, '$1b.jpg');
		
		$(this).attr('href', 'javascript:void(0)');
		$(this).attr('url', href);
		$(this).attr('target', '');
		
		$(this).bind('click', function(e) {
			preview.open(e, this, $(this).attr('url'));
		});
		
	});
	//onClick='preview.open(event, \"/i/buket/7b.jpg\")' 
});


function random(min,max) {
	var range = max - min;
	var n = Math.floor(Math.random()*range) + min;
	return n;
}


/**
 * SWFObject v1.4.1: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, useExpressInstall, quality, xiRedirectUrl, redirectUrl, detectKey){
if (!document.createElement || !document.getElementById) { return; }
this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params = new Object();
this.variables = new Object();
this.attributes = new Array();
if(swf) { this.setAttribute('swf', swf); }
if(id) { this.setAttribute('id', id); }
if(w) { this.setAttribute('width', w); }
if(h) { this.setAttribute('height', h); }
if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion(this.getAttribute('version'), useExpressInstall);
if(c) { this.addParam('bgcolor', c); }
var q = quality ? quality : 'high';
this.addParam('quality', q);
this.setAttribute('useExpressInstall', useExpressInstall);
this.setAttribute('doExpressInstall', false);
var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
this.setAttribute('xiRedirectUrl', xir);
this.setAttribute('redirectUrl', '');
if(redirectUrl) { this.setAttribute('redirectUrl', redirectUrl); }
}
deconcept.SWFObject.prototype = {
setAttribute: function(name, value){
this.attributes[name] = value;
},
getAttribute: function(name){
return this.attributes[name];
},
addParam: function(name, value){
this.params[name] = value;
},
getParams: function(){
return this.params;
},
addVariable: function(name, value){
this.variables[name] = value;
},
getVariable: function(name){
return this.variables[name];
},
getVariables: function(){
return this.variables;
},
getVariablePairs: function(){
var variablePairs = new Array();
var key;
var variables = this.getVariables();
for(key in variables){
variablePairs.push(key +"="+ variables[key]);
}
return variablePairs;
},
getSWFHTML: function() {
var swfNode = "";
if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
if (this.getAttribute("doExpressInstall")) this.addVariable("MMplayerType", "PlugIn");
swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'"';
swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
var params = this.getParams();
 for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
var pairs = this.getVariablePairs().join("&");
 if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
swfNode += '/>';
} else { // PC IE
if (this.getAttribute("doExpressInstall")) this.addVariable("MMplayerType", "ActiveX");
swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'">';
swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
var params = this.getParams();
for(var key in params) {
 swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
}
var pairs = this.getVariablePairs().join("&");
if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
swfNode += "</object>";
}
return swfNode;
},
write: function(elementId){
if(this.getAttribute('useExpressInstall')) {
// check to see if we need to do an express install
var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
this.setAttribute('doExpressInstall', true);
this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
document.title = document.title.slice(0, 47) + " - Flash Player Installation";
this.addVariable("MMdoctitle", document.title);
}
}
if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
n.innerHTML = this.getSWFHTML();
return true;
}else{
if(this.getAttribute('redirectUrl') != "") {
document.location.replace(this.getAttribute('redirectUrl'));
}
}
return false;
}
}

/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(reqVer, xiInstall){
var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins && navigator.mimeTypes.length){
var x = navigator.plugins["Shockwave Flash"];
if(x && x.description) {
PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-z]|[A-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
}
}else{
try{
var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
for (var i=3; axo!=null; i++) {
axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+i);
PlayerVersion = new deconcept.PlayerVersion([i,0,0]);
}
}catch(e){}
if (reqVer && PlayerVersion.major > reqVer.major) return PlayerVersion; // version is ok, skip minor detection
// this only does the minor rev lookup if the user's major version 
// is not 6 or we are checking for a specific minor or revision number
// see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
if (!reqVer || ((reqVer.minor != 0 || reqVer.rev != 0) && PlayerVersion.major == reqVer.major) || PlayerVersion.major != 6 || xiInstall) {
try{
PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
}catch(e){}
}
}
return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
this.major = parseInt(arrVersion[0]) != null ? parseInt(arrVersion[0]) : 0;
this.minor = parseInt(arrVersion[1]) || 0;
this.rev = parseInt(arrVersion[2]) || 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
if(this.major < fv.major) return false;
if(this.major > fv.major) return true;
if(this.minor < fv.minor) return false;
if(this.minor > fv.minor) return true;
if(this.rev < fv.rev) return false;
return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
getRequestParameter: function(param){
var q = document.location.search || document.location.hash;
if(q){
var startIndex = q.indexOf(param +"=");
var endIndex = (q.indexOf("&", startIndex) > -1) ? q.indexOf("&", startIndex) : q.length;
if (q.length > 1 && startIndex > -1) {
return q.substring(q.indexOf("=", startIndex)+1, endIndex);
}
}
return "";
}
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
var objects = document.getElementsByTagName("OBJECT");
for (var i=0; i < objects.length; i++) {
for (var x in objects[i]) {
if (typeof objects[i][x] == 'function') {
objects[i][x] = null;
}
}
}
}
if (typeof window.onunload == 'function') {
var oldunload = window.onunload;
window.onunload = function() {
deconcept.SWFObjectUtil.cleanupSWFs();
oldunload();
}
} else {
window.onunload = deconcept.SWFObjectUtil.cleanupSWFs;
}
/* add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;


/**
 * 
 * Ищет внутри контейнера ссылки и если ее адрес схож с текущим адресом, выделяет пункт 
 * 
 */ 

 
Podsvetka_menu = {};



$(document).ready(function() {
	Podsvetka_menu.light();
});



Podsvetka_menu.light = function() {
	this.is_nashli_link = false;
	
	/* предварительная обработка адреса */
	this.cur_url = document.location.href;
	this.cur_url = this.cur_url.replace(/^http:\/\/.+?\//i, '/')
							   .replace(/index\..+$/i, '/')
							   .replace(/[\/]+/g, '/')
							   .replace('#','');						   
	
	/* сначало ищем вариант с учетом знака вопроса
	 * второй раз уже без него
	 */
	 
	
	 
	for(this.variant_url = 1; this.variant_url<=2; this.variant_url++) {
		
		//если без знака вопроса
		if(this.variant_url == 2) {
			this.cur_url = this.cur_url.replace(/\?.*/, '');
		}
		
		console.log("Текущий адрес: " + this.cur_url);
		
		//alert("Текущий адрес: " + this.cur_url);
		
		/* TODO сделать продвинутую обработку с учетом ? и # */
		
		/* ищем линку */
		$("div[@podsvetka_menu=1]").find('a').each(function(){
				if(Podsvetka_menu.is_nashli_link) return true; //если ссылка уже найдена
			
				var href = $(this).attr('href').replace(/^http:\/\/.+?\//i, '/')
							   					.replace(/index\..+$/i, '/')
							   					.replace(/[\/]+/g, '/');
				
				console.log(href);
				
				/* если нашли ссылку с данным урлом */
				if(href == Podsvetka_menu.cur_url) {
					if(Podsvetka_menu.is_nashli_link);
					/* оформляем ссылку */
					
					console.log("оформляем ссылку");
					
					//если ссылка в стиле список
					if($(this).find('span').length) {
						$('span', this).addClass('ms_select_style_list');
						$('span', this).css({border:0});
					}
					//в стиле тег
					else {
						$(this).addClass('ms_select_style_tag');
					}
				}
			}
		);
		
		if(Podsvetka_menu.is_nashli_link) break;
	}
}

 
 


