dom = (document.getElementById)? true : false;
nn4 = (document.layers)? true : false;
ie = (document.all)? true : false;
ie4 = (!dom && ie)? true : false;
var activeElem = null;

var doc;
var mc;

function preloadImages()
{
    doc = document;
    if( doc.images )
        {
        if( !doc.preloadImgs )
            doc.preloadImgs = new Array();
        var i, j = doc.preloadImgs.length;
        var a = preloadImages.arguments;
        for(i=0; i<a.length; i++)
            {
            doc.preloadImgs[j] = new Image;
            doc.preloadImgs[j++].src = a[i];
            }
        }
}

function findObject( id, doc )
{
    var i;

    if( doc == null )
        doc = document;

    if( dom )
        return doc.getElementById( id );
    else
        {
        if( ie4 )
        return doc.all[ id ];
        }

    for( i=0; i<doc.forms.length; i++ )
        for( j=0; j<doc.forms[i].elements.length; j++ )
        if( id == doc.forms[i].elements[j].name )
            return doc.forms[i].elements[j];

    for( i=0; i<doc.images.length; i++ )
        if( id == doc.images[i].name )
        return doc.images[i];

    if( doc.layers == null )
        return null;

    for( i=0; i<doc.layers.length; i++ )
        {
        if( id == doc.layers[i].name )
        return doc.layers[i];
        var x = findObject( id, doc.layers[i].document );
        if( x != null )
        return x;
        }
    return null;
}

function showElem(elemId)
{
    if (dom)
        document.getElementById(elemId).style.visibility = "visible";
    else
        if (ie4)
        document.all[elemId].style.visibility = "visible";
        else
        if (nn4)
            document.layers[elemId].visibility = "show";
}

function hideElem(elemId)
{
    if (dom)
         document.getElementById(elemId).style.visibility = "hidden";
    else
        if (ie4)
        document.all[elemId].style.visibility = "hidden";
        else
        if (nn4) document.layers[elemId].visibility = "hide";
}

function turnElementOff( elemId )
{
    var elem = getElement( elemId );
    if( elem == null )
        return true;
    if( dom || ie4 )
        elem.style.display = "none";
    else
        {
        if( nn4 )
            elem.display = "none";
        }
}

function toggleElement( elemId )
{
    var elem = getElement( elemId );
    if( elem == null )
        return true;
    if( dom || ie4 )
        (elem.style.display == "none")?elem.style.display="":elem.style.display="none";
    else
        {
        if( nn4 )
            (elem.display == "none")?elem.display="":elem.display="none";
        }
    return false;
}

function getElement( elemId )
{
    if (dom)
        return document.getElementById(elemId);
    else
        if (ie4)
            return document.all[elemId];
        else
            if (nn4)
                return document.layers[elemId];
    return null;
}


// This function writes HTML code into a layer
function Writelayer(layer,code,doc)
{
    if( doc == null )
        doc = "document";
    if (nn4)
        {
        layer.document.open();
        layer.document.write( code );
        layer.document.close();
        }
    else
        if (ie4)
            {
        layer.innerHTML = code;
        }
        else
            if (dom)
                {
            layer.innerHTML = code;
            }
}

function anchorPosX(anchorPtr)
{
    if (document.layers)
        return anchorPtr.x;
    else if (document.getElementById || document.all)
        {
        var pos = anchorPtr.offsetLeft;
        while (anchorPtr.offsetParent != null)
            {
            anchorPtr = anchorPtr.offsetParent;
            pos += anchorPtr.offsetLeft;
            }
        return pos;
        }
}

function anchorPosY(anchorPtr)
{
    if (document.layers)
        return anchorPtr.y;
    else if (document.getElementById || document.all)
        {
        var pos = anchorPtr.offsetTop;
        while (anchorPtr.offsetParent != null)
            {
            anchorPtr = anchorPtr.offsetParent;
            pos += anchorPtr.offsetTop;
            }
        return pos;
        }
}


function offer( largePhoto, smallPhoto, logoImage, model, price, gallery, content, url_path )
{
    this.largePhoto = largePhoto;
    this.smallPhoto = smallPhoto;
    this.logoImage = logoImage;
    this.model = model;
    this.price = price;
    this.gallery = gallery;
    this.content = content;
    this.url = url_path;
}

function setMainOffer()
{
    var obj = findObject( 'mainpic' );
    if( obj )
        obj.src = offers[0].largePhoto;
    obj = findObject( 'mainlogo' );
    if( obj )
        obj.src = offers[0].logoImage;
    obj = findObject( 'mainurl' );
    if( obj )
        obj.href = offers[0].url;
    obj = findObject( 'mainmodel' );
    if( obj )
        obj.innerText = offers[0].model;
    obj = findObject( 'mainprice' );
    if( obj )
        obj.innerHTML = '<p class=price>' + offers[0].price +'<font style="vertical-align: top;" size=1>*</font>';
    obj = findObject( 'tm_1' );
    if( obj )
        {
        col = '';
        if( offers[0].content )
            col = '<p><a href=' + offers[0].url + 'content.html>лПНРМЕЛФБГЙС</a>';
        obj.innerHTML = col + '<p><a href=/conditions/>хУМПЧЙС РПУФБЧЛЙ</a>';
        }
    obj = findObject( 'tm_2' );
    if( obj )
        {
        col = '';
        if( offers[0].gallery )
            col = '<p><a href=' + offers[0].url + 'gallery.html>жПФПЗБМЕТЕС</a>';
        obj.innerHTML = col + '<p><a href=/request.html onclick="return open_request();">ъБЛБЪБФШ ЛПОУХМШФБГЙА</a>';
        }
    obj = findObject( 'tm_3' );
    if( obj )
        obj.innerHTML = '<p><a href=' + offers[0].url +'>фЕИОЙЮЕУЛЙЕ ИБТБЛФЕТЙУФЙЛЙ</a>';
}

function setSmallOffer( num )
{
    var obj = findObject( 'model_' + num );
    if( obj )
        obj.innerText = offers[num].model;
    obj = findObject( 'pic_' + num );
    if( obj )
        obj.src = offers[num].smallPhoto;
}

function changeOffer( num )
{
    var main_obj = offers[0];
    var switching_obj = offers[num];
    offers[0] = switching_obj;
    offers[num] = main_obj;

    setMainOffer();
    setSmallOffer( num );
}

function open_request()
{
    var imageWin = window.open( '/request.html', 'request', 'width=500,height=500,directories=no,toolbar=no,resizable=no,menubar=no,scrollbars=no' );
    if( imageWin.focus )
        imageWin.focus();
    return false;
}

function open_order()
{
    var imageWin = window.open( '/order.html', 'order', 'width=500,height=500,directories=no,toolbar=no,resizable=no,menubar=no,scrollbars=no' );
    if( imageWin.focus )
        imageWin.focus();
    return false;
}

function open_comm(id)
{
    var imageWin = window.open( '/used/addcomment.html?id=' + id, 'order', 'width=385,height=415,directories=no,toolbar=no,resizable=no,menubar=no,scrollbars=no' );
    if( imageWin.focus )
        imageWin.focus();
    return false;
}

function open_usedgallery(id)
{
    var imageWin = window.open( '/used/gallery.html?id=' + id, 'order', 'width=550,height=570,directories=no,toolbar=no,resizable=no,menubar=no,scrollbars=no' );
    if( imageWin.focus )
        imageWin.focus();
    return false;
}

function open_usedservice(id,st)
{
    var imageWin = window.open( '/used/service.html?id=' + id + '&id_st=' + st, 'order', 'width=370,height=410,directories=no,toolbar=no,resizable=no,menubar=no,scrollbars=no' );
    if( imageWin.focus )
        imageWin.focus();
    return false;
}

function initLoginWindow()
{
    var pl = findObject( 'btm' );
    var go = findObject( 'letsgo' );
    var ic = findObject( 'introcont' );
    var mo = findObject( 'lml' );
    if( !pl || !go || !ic || !mo )
        return;
    y = anchorPosY( pl );
    go.style.top = y-220;
    go.style.width = ic.offsetWidth;
    offLeft = Math.floor( (ic.offsetWidth-310)/2+20 );
    mo.style.width = offLeft;
    var i1 = findObject( 'login' );
    var i2 = findObject( 'password' );
    if( i1 && i2 )
        {
        i1.style.width = ic.offsetWidth-offLeft-168;
        i2.style.width = ic.offsetWidth-offLeft-168;
        }
    showElem( 'letsgo' );
}

function processLogin()
{
    var obj = findObject( 'loginFrm' );
    if( obj )
        obj.submit();
}

function turnKeys(what)
{
    var obj = findObject( 'keys' );
    if( obj )
        obj.src = '/img/keys_'+what+'.png';
}

function openTradeInRequest()
{
    var o1 = findObject('tradeinform');
    var o2 = findObject('opentradein');
    if( !o1 || !o2 )
    return false;
    toggleElement( 'opentradein' );
    toggleElement( 'tradeinform' );
    showElem( 'tradeinform' );

    return false;
}

function checkEmpty( fldName )
{
    var o;
    o = findObject( fldName );
    if( !o )
        return false;
    if( o.value == '' || o.value == -1 )
        {
        o.style.backgroundColor = '#e6d7c5';
        o.focus();
        return false;
        }
    o.style.backgroundColor = 'white';
    return true;
}

function correctFloat( fldName )
{
    var o;
    if( !checkEmpty( fldName ) )
        return false;
    o = findObject( fldName );
    if( !o )
        return false;
    var valStr = o.value;
    var res = true;
    for( i=0; i<valStr.length && res; i++ )
        res = (valStr[i] >= '0' && valStr[i] <= '9') || valStr[i]=='.';
    if( !res )
        {
        o.style.backgroundColor = '#e6d7c5';
        o.focus();
        return false;
        }
    o.style.backgroundColor = 'white';
    return true;
}

function correctInt( fldName )
{
    var o;
    if( !checkEmpty( fldName ) )
        return false;
    o = findObject( fldName );
    if( !o )
        return false;
    var valStr = new String( o.value );
    // alert( valStr );
    var res = true;
    for( i=0; i<valStr.length && res; i++ )
        {
        res &= ((valStr[i] >= '0') && (valStr[i] <= '9'));
        alert( valStr[i] );
        }
    if( !res )
        {
        o.style.backgroundColor = '#e6d7c5';
        o.focus();
        return false;
        }
    o.style.backgroundColor = 'white';
    return true;
}

function checkTradeInForm()
{
    var res = true;
    res = res & checkEmpty( 'price' ); // correctInt( 'price' );
    res = res & checkEmpty( 'capacity' ); // correctFloat( 'capacity' );
    res = res & checkEmpty( 'mileage' ); // correctInt( 'mileage' );
    res = res & checkEmpty( 'gear' );
    res = res & checkEmpty( 'engine' );
    res = res & checkEmpty( 'year' );
    res = res & checkEmpty( 'bodytype' );
    res = res & checkEmpty( 'wdtype' );
    res = res & checkEmpty( 'color' );
    res = res & checkEmpty( 'model' );
    res = res & checkEmpty( 'brand' );
    res = res & checkEmpty( 'cphone' );
    res = res & checkEmpty( 'cname' );

    if( res )
        {
        var o = findObject( 'tradeinf' );
        if( o )
            o.submit();
        }
    return true;
}

var prevMenu = null;
var smTimer = null;
function hism( smid )
{
    if( prevMenu )
        {
        hideElem( prevMenu );
        if( smTimer )
            clearTimeout( smTimer );
        prevMenu = null;
        }
    var obj = findObject( 'a_'+smid );
    if( !obj )
        return false;
    var x = anchorPosX( obj );
    var smb_obj = findObject( 'smb_'+smid );
    if( !smb_obj )
        return false;
    smb_obj.style.left = (x-20)+'px';
    smb_obj.style.top = '115px';
    showElem( 'smb_'+smid );
    prevMenu = 'smb_'+smid;
    return false;
}

function hideSubmenu()
{
    if( smTimer )
        {
        clearTimeout( smTimer );
        smTimer = null;
        }
    if( prevMenu )
        {
        hideElem( prevMenu );
        prevMenu = null;
        }
}

function losm( smid )
{
    var obj = findObject( 'sm_'+smid );
    if( !obj )
        return false;
//  hideElem( 'smb_'+smid );
    smTimer = setTimeout( 'hideSubmenu();', 500 );
    return false;
}

function rect( x, y, width, height )
{
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
}

function setLeftInPercent( divName, divTop, divLeft )
{
    var l = Math.round( divLeft*mc.offsetWidth/100 );
    var res = setLeft( divName, divTop, l );
    return res;
}

function setLeftvsWidthInPercent( divName, divTop, divLeft, divWidth )
{
    var l = Math.round( divLeft*mc.offsetWidth/100 );
    var w = Math.round( divWidth*mc.offsetWidth/100 );
    if( divLeft + divWidth == 100 )
        w = mc.offsetWidth - l;
    var dobj = findObject( divName );
    if( dobj )
        dobj.style.width = w+'px';
    var res = setLeft( divName, divTop, l );
    return res;
}

function setLeft( divName, divTop, divLeft )
{
    var dobj = findObject( divName );
    if( !dobj )
        return;

    var res = new rect( mc.offsetLeft+divLeft, mc.offsetTop+divTop-mc.offsetTop,
        mc.offsetWidth, mc.offsetHeight );

    dobj.style.left = res.x + 'px';
    dobj.style.top = res.y + 'px';
    showElem( divName );
    return res;
}

function init()
{
    mc = findObject( 'mc' );
	var thc = findObject( 'thc' );
    if( !mc || !thc )
        return;

	thc.style.top = mc.offsetTop+'px';
	thc.style.left = mc.offsetLeft+'px';
	thc.style.width = mc.offsetWidth+'px';
	showElem( 'thc' );

    setLeft( 'mm_h1', 0, 0 );
    var bx = setLeftvsWidthInPercent( 'mm_bbg', 0, 37, 60 );
    setLeft( 'mm_lp', 0, bx.x-125 );
    setLeftInPercent( 'mm_r', 0, 36 );
    setLeft( 'mm_about', 67, bx.x-74 );

    var mx = setLeftInPercent( 'mm_man', 75, 44 );
    setLeft( 'mm_accessories', 120, mx.x+80 );

	var ox = setLeftInPercent( 'mm_oil', 0, 60 );
	setLeft( 'mm_onboard', 50, ox.x-67 );
	setLeft( 'mm_byrequest', 15, ox.x+160 );
	setLeft( 'mm_conditions', 65, ox.x+170 );

	var ax = setLeftInPercent( 'mm_abg', 105, 75 );
	setLeft( 'mm_autos', 110, ax.x+10 );

	var sx = setLeftInPercent( 'mm_speed', 0, 90 );
	setLeft( 'mm_news', 40, sx.x-50 );
}

function makeResize()
{
    init();
}



 function dynamicSelect(id1, id2) {

// Сперва необходимо проверить поддержку W3C DOM в браузере

 if (document.getElementById && document.getElementsByTagName) {

// Определение переменных, ссылающихся на списки

  //var sel1 = document.getElementById(id1);
  //var sel2 = document.getElementById(id2);
  var sel1 = document.MyForm.Region;
  var sel2 = document.MyForm.City;


// Клонирование динамического списка

  var clone = sel2.cloneNode(true);

// Определение переменных для клонированных элементов списка

  var clonedOptions = clone.getElementsByTagName("option");

// Вызов функции собирающей вызываемый список

  refreshDynamicSelectOptions(sel1, sel2, clonedOptions);

// При изменении выбранного элемента в первом списке: // вызов функции пересобирающей вызываемый список

  sel1.onchange = function() {
  refreshDynamicSelectOptions(sel1, sel2, clonedOptions);
  }
 }
}

// Функция для сборки динамического списка

function refreshDynamicSelectOptions(sel1, sel2, clonedOptions) {

// Удаление всех элементов динамического списка

 while (sel2.options.length) {
  sel2.remove(0);
 }
 var pattern1 = /( |^)(select)( |$)/;
 var pattern2 = new RegExp("( |^)(" + sel1.options[sel1.selectedIndex].value + ")( |$)");

// Перебор клонированных элементов списка

 for (var i = 0; i < clonedOptions.length; i++) {

// Если название класса клонированного option эквивалентно "select" // либо эквивалентно значению option первого списка

  if (clonedOptions[i].className.match(pattern1) ||
  clonedOptions[i].className.match(pattern2)) {

// его нужно клонировать в динамически создаваемый список

   sel2.appendChild(clonedOptions[i].cloneNode(true));
  }
 }
}

// -------------------------------------------------------------------
// Switch Content Script- By Dynamic Drive, available at: http://www.dynamicdrive.com
// Created: Jan 5th, 2007
// April 5th, 07: Added ability to persist content states by x days versus just session only
// March 27th, 08': Added ability for certain headers to get its contents remotely from an external file via Ajax (2 variables below to customize)
// -------------------------------------------------------------------

var switchcontent_ajax_msg='<em>Loading Ajax content...</em>' //Customize message to show while fetching Ajax content (if applicable)
var switchcontent_ajax_bustcache=true //Bust cache and refresh fetched Ajax contents when page is reloaded/ viewed again?

function switchcontent(className, filtertag){
	this.className=className
	this.collapsePrev=false //Default: Collapse previous content each time
	this.persistType="none" //Default: Disable persistence
	//Limit type of element to scan for on page for switch contents if 2nd function parameter is defined, for efficiency sake (ie: "div")
	this.filter_content_tag=(typeof filtertag!="undefined")? filtertag.toLowerCase() : ""
	this.ajaxheaders={} //object to hold path to ajax content for corresponding header (ie: ajaxheaders["header1"]='external.htm')
}

switchcontent.prototype.setStatus=function(openHTML, closeHTML){ //PUBLIC: Set open/ closing HTML indicator. Optional
	this.statusOpen=openHTML
	this.statusClosed=closeHTML
}

switchcontent.prototype.setColor=function(openColor, closeColor){ //PUBLIC: Set open/ closing color of switch header. Optional
	this.colorOpen=openColor
	this.colorClosed=closeColor
}

switchcontent.prototype.setPersist=function(bool, days){ //PUBLIC: Enable/ disable persistence. Default is false.
	if (bool==true){ //if enable persistence
		if (typeof days=="undefined") //if session only
			this.persistType="session"
		else{ //else if non session persistent
			this.persistType="days"
			this.persistDays=parseInt(days)
		}
	}
	else
		this.persistType="none"
}

switchcontent.prototype.collapsePrevious=function(bool){ //PUBLIC: Enable/ disable collapse previous content. Default is false.
	this.collapsePrev=bool
}

switchcontent.prototype.setContent=function(index, filepath){ //PUBLIC: Set path to ajax content for corresponding header based on header index
	this.ajaxheaders["header"+index]=filepath
}

switchcontent.prototype.sweepToggle=function(setting){ //PUBLIC: Expand/ contract all contents method. (Values: "contract"|"expand")
	if (typeof this.headers!="undefined" && this.headers.length>0){ //if there are switch contents defined on the page
		for (var i=0; i<this.headers.length; i++){
			if (setting=="expand")
				this.expandcontent(this.headers[i]) //expand each content
			else if (setting=="contract")
				this.contractcontent(this.headers[i]) //contract each content
		}
	}
}


switchcontent.prototype.defaultExpanded=function(){ //PUBLIC: Set contents that should be expanded by default when the page loads (ie: defaultExpanded(0,2,3)). Persistence if enabled overrides this setting.
	var expandedindices=[] //Array to hold indices (position) of content to be expanded by default
	//Loop through function arguments, and store each one within array
	//Two test conditions: 1) End of Arguments array, or 2) If "collapsePrev" is enabled, only the first entered index (as only 1 content can be expanded at any time)
	for (var i=0; (!this.collapsePrev && i<arguments.length) || (this.collapsePrev && i==0); i++)
		expandedindices[expandedindices.length]=arguments[i]
	this.expandedindices=expandedindices.join(",") //convert array into a string of the format: "0,2,3" for later parsing by script
}


//PRIVATE: Sets color of switch header.

switchcontent.prototype.togglecolor=function(header, status){
	if (typeof this.colorOpen!="undefined")
		header.style.color=status
}


//PRIVATE: Sets status indicator HTML of switch header.

switchcontent.prototype.togglestatus=function(header, status){
	if (typeof this.statusOpen!="undefined")
		header.firstChild.innerHTML=status
}


//PRIVATE: Contracts a content based on its corresponding header entered

switchcontent.prototype.contractcontent=function(header){
	var innercontent=document.getElementById(header.id.replace("-title", "")) //Reference content container for this header
	innercontent.style.display="none"
	this.togglestatus(header, this.statusClosed)
	this.togglecolor(header, this.colorClosed)
}


//PRIVATE: Expands a content based on its corresponding header entered

switchcontent.prototype.expandcontent=function(header){
	var innercontent=document.getElementById(header.id.replace("-title", ""))
	if (header.ajaxstatus=="waiting"){//if this is an Ajax header AND remote content hasn't already been fetched
		switchcontent.connect(header.ajaxfile, header)
	}
	innercontent.style.display="block"
	this.togglestatus(header, this.statusOpen)
	this.togglecolor(header, this.colorOpen)
}

// -------------------------------------------------------------------
// PRIVATE: toggledisplay(header)- Toggles between a content being expanded or contracted
// If "Collapse Previous" is enabled, contracts previous open content before expanding current
// -------------------------------------------------------------------

switchcontent.prototype.toggledisplay=function(header){
	var innercontent=document.getElementById(header.id.replace("-title", "")) //Reference content container for this header
	if (innercontent.style.display=="block")
		this.contractcontent(header)
	else{
		this.expandcontent(header)
		if (this.collapsePrev && typeof this.prevHeader!="undefined" && this.prevHeader.id!=header.id) // If "Collapse Previous" is enabled and there's a previous open content
			this.contractcontent(this.prevHeader) //Contract that content first
	}
	if (this.collapsePrev)
		this.prevHeader=header //Set current expanded content as the next "Previous Content"
}


// -------------------------------------------------------------------
// PRIVATE: collectElementbyClass()- Searches and stores all switch contents (based on shared class name) and their headers in two arrays
// Each content should carry an unique ID, and for its header, an ID equal to "CONTENTID-TITLE"
// -------------------------------------------------------------------

switchcontent.prototype.collectElementbyClass=function(classname){ //Returns an array containing DIVs with specified classname
	var classnameRE=new RegExp("(^|\\s+)"+classname+"($|\\s+)", "i") //regular expression to screen for classname within element
	this.headers=[], this.innercontents=[]
	if (this.filter_content_tag!="") //If user defined limit type of element to scan for to a certain element (ie: "div" only)
		var allelements=document.getElementsByTagName(this.filter_content_tag)
	else //else, scan all elements on the page!
		var allelements=document.all? document.all : document.getElementsByTagName("*")
	for (var i=0; i<allelements.length; i++){
		if (typeof allelements[i].className=="string" && allelements[i].className.search(classnameRE)!=-1){
			if (document.getElementById(allelements[i].id+"-title")!=null){ //if header exists for this inner content
				this.headers[this.headers.length]=document.getElementById(allelements[i].id+"-title") //store reference to header intended for this inner content
				this.innercontents[this.innercontents.length]=allelements[i] //store reference to this inner content
			}
		}
	}
}


//PRIVATE: init()- Initializes Switch Content function (collapse contents by default unless exception is found)

switchcontent.prototype.init=function(){
	var instanceOf=this
	this.collectElementbyClass(this.className) //Get all headers and its corresponding content based on shared class name of contents
	if (this.headers.length==0) //If no headers are present (no contents to switch), just exit
		return
	//If admin has changed number of days to persist from current cookie records, reset persistence by deleting cookie
	if (this.persistType=="days" && (parseInt(switchcontent.getCookie(this.className+"_dtrack"))!=this.persistDays))
		switchcontent.setCookie(this.className+"_d", "", -1) //delete cookie
	// Get ids of open contents below. Four possible scenerios:
	// 1) Session only persistence is enabled AND corresponding cookie contains a non blank ("") string
	// 2) Regular (in days) persistence is enabled AND corresponding cookie contains a non blank ("") string
	// 3) If there are contents that should be enabled by default (even if persistence is enabled and this IS the first page load)
	// 4) Default to no contents should be expanded on page load ("" value)
	var opencontents_ids=(this.persistType=="session" && switchcontent.getCookie(this.className)!="")? ','+switchcontent.getCookie(this.className)+',' : (this.persistType=="days" && switchcontent.getCookie(this.className+"_d")!="")? ','+switchcontent.getCookie(this.className+"_d")+',' : (this.expandedindices)? ','+this.expandedindices+',' : ""
	for (var i=0; i<this.headers.length; i++){ //BEGIN FOR LOOP
		if (typeof this.ajaxheaders["header"+i]!="undefined"){ //if this is an Ajax header
			this.headers[i].ajaxstatus='waiting' //two possible statuses: "waiting" and "loaded"
			this.headers[i].ajaxfile=this.ajaxheaders["header"+i]
		}
		if (typeof this.statusOpen!="undefined") //If open/ closing HTML indicator is enabled/ set
			this.headers[i].innerHTML='<span class="status"></span>'+this.headers[i].innerHTML //Add a span element to original HTML to store indicator
		if (opencontents_ids.indexOf(','+i+',')!=-1){ //if index "i" exists within cookie string or default-enabled string (i=position of the content to expand)
			this.expandcontent(this.headers[i]) //Expand each content per stored indices (if ""Collapse Previous" is set, only one content)
			if (this.collapsePrev) //If "Collapse Previous" set
			this.prevHeader=this.headers[i]  //Indicate the expanded content's corresponding header as the last clicked on header (for logic purpose)
		}
		else //else if no indices found in stored string
			this.contractcontent(this.headers[i]) //Contract each content by default
		this.headers[i].onclick=function(){instanceOf.toggledisplay(this)}
	} //END FOR LOOP
	switchcontent.dotask(window, function(){instanceOf.rememberpluscleanup()}, "unload") //Call persistence method onunload
}


// -------------------------------------------------------------------
// PRIVATE: rememberpluscleanup()- Stores the indices of content that are expanded inside session only cookie
// If "Collapse Previous" is enabled, only 1st expanded content index is stored
// -------------------------------------------------------------------

//Function to store index of opened ULs relative to other ULs in Tree into cookie:
switchcontent.prototype.rememberpluscleanup=function(){
	//Define array to hold ids of open content that should be persisted
	//Default to just "none" to account for the case where no contents are open when user leaves the page (and persist that):
	var opencontents=new Array("none")
	for (var i=0; i<this.innercontents.length; i++){
		//If persistence enabled, content in question is expanded, and either "Collapse Previous" is disabled, or if enabled, this is the first expanded content
		if (this.persistType!="none" && this.innercontents[i].style.display=="block" && (!this.collapsePrev || (this.collapsePrev && opencontents.length<2)))
			opencontents[opencontents.length]=i //save the index of the opened UL (relative to the entire list of ULs) as an array element
		this.headers[i].onclick=null //Cleanup code
	}
	if (opencontents.length>1) //If there exists open content to be persisted
		opencontents.shift() //Boot the "none" value from the array, so all it contains are the ids of the open contents
	if (typeof this.statusOpen!="undefined")
		this.statusOpen=this.statusClosed=null //Cleanup code
	if (this.persistType=="session") //if session only cookie set
		switchcontent.setCookie(this.className, opencontents.join(",")) //populate cookie with indices of open contents: classname=1,2,3,etc
	else if (this.persistType=="days" && typeof this.persistDays=="number"){ //if persistent cookie set instead
		switchcontent.setCookie(this.className+"_d", opencontents.join(","), this.persistDays) //populate cookie with indices of open contents
		switchcontent.setCookie(this.className+"_dtrack", this.persistDays, this.persistDays) //also remember number of days to persist (int)
	}
}


// -------------------------------------------------------------------
// A few utility functions below:
// -------------------------------------------------------------------


switchcontent.dotask=function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
	var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
	if (target.addEventListener)
		target.addEventListener(tasktype, functionref, false)
	else if (target.attachEvent)
		target.attachEvent(tasktype, functionref)
}

switchcontent.connect=function(pageurl, header){
	var page_request = false
	var bustcacheparameter=""
	if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
		try {
		page_request = new ActiveXObject("Msxml2.XMLHTTP")
		}
		catch (e){
			try{
			page_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}
	else if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest()
	else
		return false
	page_request.onreadystatechange=function(){switchcontent.loadpage(page_request, header)}
	if (switchcontent_ajax_bustcache) //if bust caching of external page
		bustcacheparameter=(pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', pageurl+bustcacheparameter, true)
	page_request.send(null)
}

switchcontent.loadpage=function(page_request, header){
	var innercontent=document.getElementById(header.id.replace("-title", "")) //Reference content container for this header
	innercontent.innerHTML=switchcontent_ajax_msg //Display "fetching page message"
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
		innercontent.innerHTML=page_request.responseText
		header.ajaxstatus="loaded"
	}
}

switchcontent.getCookie=function(Name){
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

switchcontent.setCookie=function(name, value, days){
	if (typeof days!="undefined"){ //if set persistent cookie
		var expireDate = new Date()
		var expstring=expireDate.setDate(expireDate.getDate()+days)
		document.cookie = name+"="+value+"; expires="+expireDate.toGMTString()
	}
	else //else if this is a session only cookie
		document.cookie = name+"="+value
}


/***********************************************
* Cool DHTML tooltip script II- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
Начало!!!
***********************************************/

var offsetfromcursorX=12 //Customize x offset of tooltip
var offsetfromcursorY=10 //Customize y offset of tooltip

var offsetdivfrompointerX=10 //Customize x offset of tooltip DIV relative to pointer image
var offsetdivfrompointerY=14 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1).

document.write('<div id="dhtmltooltip"></div>') //write out tooltip DIV
document.write('<img id="dhtmlpointer" src="/img/arrow2.gif">') //write out pointer image

var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
if (ie||ns6)
var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""

var pointerobj=document.all? document.all["dhtmlpointer"] : document.getElementById? document.getElementById("dhtmlpointer") : ""

function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ddrivetip(thetext, thewidth, thecolor){
if (ns6||ie){
if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
tipobj.innerHTML=thetext
enabletip=true
return false
}
}

function positiontip(e){
if (enabletip){
var nondefaultpos=false
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20
var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20

var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX
var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY

var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000

//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth){
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=curX-tipobj.offsetWidth+"px"
nondefaultpos=true
}
else if (curX<leftedge)
tipobj.style.left="5px"
else{
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetfromcursorX-offsetdivfrompointerX+"px"
pointerobj.style.left=curX+offsetfromcursorX+"px"
}

//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight){
tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px"
nondefaultpos=true
}
else{
tipobj.style.top=curY+offsetfromcursorY+offsetdivfrompointerY+"px"
pointerobj.style.top=curY+offsetfromcursorY+"px"
}
tipobj.style.visibility="visible"
if (!nondefaultpos)
pointerobj.style.visibility="visible"
else
pointerobj.style.visibility="hidden"
}
}

function hideddrivetip(){
if (ns6||ie){
enabletip=false
tipobj.style.visibility="hidden"
pointerobj.style.visibility="hidden"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}

document.onmousemove=positiontip
/***********************************************
* Cool DHTML tooltip script II- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
Конец!!!!
***********************************************/