function open_window(url,width,height){
	window.open(url,'_blank','toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=yes,resizable=yes,width='+width+',height='+height+',top='+(window.screen.height/2 - height/2)+',left='+(window.screen.width/2 - width/2));
	return false;
};
function length_left(maxlength, textlength, objid){
	dispobj=document.getElementById(objid);
	dispobj.innerHTML=maxlength-textlength;
	if(maxlength-textlength >= 0){
		dispobj.style.color="green";
	} else {
		dispobj.style.color="red";
	}
};
function show_group(group_array, active_group){
	for(group_id in group_array) if(document.getElementById(group_id)){
		groupStyle = document.getElementById(group_id).style;
		if(group_id == active_group){
			groupStyle.display = (groupStyle.display == 'none') ? 'inline' : 'none';
		} else {
			groupStyle.display = 'none';
		}
	}
};
function check_subitems(subitems, parent_id, is_parent_event){
	if(is_parent_event){
		isChecked = document.getElementById(parent_id).checked;
		for(subitem_id in subitems){
			document.getElementById(subitem_id).checked = isChecked;
			if(isArray(subitems[subitem_id])) check_subitems(subitems[subitem_id], subitem_id, true);
		}
	} else if (arrayLength(subitems) > 0) {
		isChecked = true;
		for(subitem_id in subitems){
			if(document.getElementById(subitem_id).checked != true) isChecked = false;
		}
		document.getElementById(parent_id).checked = isChecked;
	}
};

function arrayLength(arr){
	arr_length = 0;
	for(void_this in arr) arr_length++;
	return arr_length;
}
function isArray(obj) {
	if (obj.constructor.toString().indexOf("Array") == -1)
		return false;
	else
		return true;
}

function load_my_image(img_id, img_width, img_height, site_url){
	with (parent.document) {
		with (getElementById('image_tag')) {
			src = site_url+'/images/notes/thumb-'+img_id+'.jpg';
			width = img_width;
			height = img_height;
		}
		getElementById('image_file_input').value = '';
		getElementById('image_id_input').value = img_id;
		getElementById('image_place').style.display="";
		getElementById('image_input').style.display="none";
	}
};

function clear_my_image(){
	with (parent.document) {
		with (getElementById('image_tag')) {
			src = '';
			width = 0;
			height = 0;
		}
		getElementById('image_id_input').value = 0;
		getElementById('image_place').style.display="none";
		getElementById('image_input').style.display="";
	}
};

function show_offer(the_event, popup_text){
	show_select_boxes();
	base_scroll_height = document.documentElement.scrollHeight;

	offerbox=document.getElementById("offerlayer");
	offerbox.innerHTML = popup_text;
	offerbox.style.left=document.documentElement.scrollLeft+the_event.clientX+10+'px';
	if(document.documentElement.scrollTop+the_event.clientY-offerbox.offsetHeight-5 >= 0){
		offerbox.style.top=document.documentElement.scrollTop+the_event.clientY-offerbox.offsetHeight-5+'px';
	} else {
		offerbox.style.top = 0+'px';
	}
	if(offerbox.offsetTop < document.documentElement.scrollTop) offerbox.style.top = document.documentElement.scrollTop+'px';

	if(document.documentElement.scrollHeight > base_scroll_height || (offerbox.offsetTop+offerbox.offsetHeight) > document.documentElement.scrollHeight){
		offerbox.style.top=base_scroll_height-offerbox.offsetHeight+'px';
	}
	hide_select_boxes();
	offerbox.style.visibility="visible";
};
function build_offer_popup(offer){

	popup  = '<table cellspacing=\"0\" cellpadding=\"0\" id=\"offerlayer_table\"><tr><td id=\"offerlayer_title\"><b>';

	popup += offer['title'];
	popup += '<\/b><\/td><\/tr><tr><td><table cellspacing=\"0\" cellpadding=\"0\"><tr><td valign=\"top\" width=\"100%\" id=\"offerlayer_text\">'+offer['description'];
	if(offer['price']) popup += '<br><br>'+offer['price'];
	if(offer['phone']) popup += '<br><br>'+offer['phone'];
	if(offer['icq']) popup += '<br><br>'+offer['icq'];
	if(offer['contactOver']) popup += '<br><br>Контактное лицо: '+offer['contactOver'];
	if(offer['ad_end_on']) popup += '<br><br>'+offer['ad_end_on'];
	if(offer['logo']){
		popup += '<\/td><td> <a href=\"#\"><img src=\"'+site_url+'/images/logos/thumb-'+offer['logo']+'.jpg\"  border=\"0\" align=\"right\" hspace=\"10\"><\/a>';
	}
	if(offer['image_width']){
		popup += '<\/td><td><a href=\"#\" onClick=\"javascript:open_window(\''+site_url+'/offer-'+offer['id']+'.htm\',600,600); return false;\"><img src=\"'+site_url+'/images/offers/thumb-'+offer['image_width']+'\"  hspace=\"5\" border=\"0\" align=\"right\" style=\"padding-right:10px\"><\/a>';
	} else {
		//popup += '<\/td><td> <img src=\"'+site_url+'/images/no_photo.gif\" width=\"90\" height=\"60\" border=\"0\" align=\"right\" hspace=\"5\">';
	}
	popup += '<\/td><\/tr><\/table><\/td><\/tr><tr><td id=\"offerlayer_text\" nowrap>';
	if(offer['password']){
		if(offer['is_disabled']) popup += '<a href=\"#\" onClick=\"javascript:open_window(\''+site_url+'/edit.php?id='+offer['id']+'&action[republish]=true\',600,600); return false;\">'+offer['is_disabled']+'<\/a> &nbsp;|&nbsp; ';
		if(offer['ad_balance']) popup += '<a href=\"#\" onClick=\"javascript:open_window(\''+site_url+'/my-ad.php?offer[id]='+offer['id']+'\',600,600); return false;\">'+offer['ad_balance']+'<\/a> &nbsp;|&nbsp; ';
		popup += '<a href=\"#\" onClick=\"javascript:open_window(\''+site_url+'/edit.php?id='+offer['id']+'&password='+offer['password']+'\',600,600); return false;\">'+edit_offer+'<\/a>';
	} else {
		if(offer['catalog']){
		if(offer['email']) popup += '<a href=\"#\" onClick=\"javascript:open_window(\''+site_url+'/offer.php?id='+offer['id']+'&action[contact]=true\',600,600); return false;\">'+offer['email']+'<\/a> &nbsp;|&nbsp; ';
		popup += '<a href=\"#\" onClick=\"javascript:open_window(\''+site_url+'/offer.php?id='+offer['id']+'&action[forward]=true\',600,600); return false;\">'+send_to_friend+'<\/a>';
		}
		else
		{
		if(offer['email']) popup += '<a href=\"#\" onClick=\"javascript:open_window(\''+site_url+'/offer.php?id='+offer['id']+'&action[contact]=true\',600,600); return false;\">'+offer['email']+'<\/a> &nbsp;|&nbsp; ';
		popup += '<a href=\"#\" onClick=\"javascript:open_window(\''+site_url+'/offer.php?id='+offer['id']+'&action[forward]=true\',600,600); return false;\">'+send_to_friend+'<\/a>';
		}
	}
	if(offer['delete_from_notepad'])
		popup+=' &nbsp;|&nbsp; <a href=\"my-notepad.php?action[delete]=true&notess[id]='+offer['note_id']+'\" >'+offer['delete_from_notepad']+'</a>  ';
	if(offer['auth']==1)
		popup+=' &nbsp;|&nbsp;<input type=\"hidden\" id=\"offer_id\" value=\"'+offer['id']+'\"> <a href=\"#\" onclick=\'JavaScript:xmlhttpPost(\"add_note.php?type=0\")\'>'+add_note+'</a>';

	if(offer['added_by'])
		popup+=' &nbsp;|&nbsp; <a href=\"'+site_url+'/user/'+offer['added_by']+'/ \">'+user_profile+'</a> <\/td><\/tr><\/table> ';

	return popup;
};

function build_message_popup(message){
	popup  = '<table cellspacing=\"0\" cellpadding=\"0\" id=\"offerlayer_table\"><tr><td id=\"offerlayer_title\"><b>'+message['subject'];
	popup += '<\/b><\/td><\/tr><tr><td id=\"offerlayer_text\"><table cellspacing=\"0\" cellpadding=\"0\"><tr><td valign=\"top\" width=\"100%\">'+message['text'];
	if(message['phone']) popup += '<br><br>'+message['phone'];
	popup += '<br><br>'+message['email'];
	popup += '</td></tr></table></td></tr></table>';

	return popup;
};
function hide_offer(eventobj){
	offerbox  = document.getElementById("offerlayer");
	eventelem = document.getElementById("offerlayer_table");

	var left   = offerbox.offsetLeft;
	var top    = offerbox.offsetTop;
	var right  = offerbox.offsetLeft+eventelem.offsetWidth;
	var bottom = offerbox.offsetTop+eventelem.offsetHeight;

	eX = eventobj.clientX+document.documentElement.scrollLeft;
	eY = eventobj.clientY+document.documentElement.scrollTop;

	if(document.documentElement.clientLeft) eX -= document.documentElement.clientLeft;
	if(document.documentElement.clientTop) eY -= document.documentElement.clientTop;

	if (eX <= left || eX >= right || eY <= top || eY >= bottom){
		show_select_boxes();
		offerbox.style.visibility="hidden";
	}
};
function show_antibot_img(antibot_src){
	if(document.getElementById("td_antibot_img").innerHTML == ''){
		document.getElementById("td_antibot_img").innerHTML = '<img src="'+antibot_src+'" width="145" height="35" style="border: 1px solid gray">';
		document.getElementById("tr_img").style.display = '';
		document.getElementById("tr_input").style.display = '';
	}
}
function blink_me(objid){
	blinkobj = document.getElementById(objid);
	blinkobj.style.textDecoration = (blinkobj.style.textDecoration == 'underline') ? 'none' : 'underline';
	window.setTimeout("blink_me('"+objid+"')", 500);
}
function hide_select_boxes() {
	if(!document.all) return;

	tag_types = new Array("IFRAME", "SELECT", "OBJECT");
	offerbox  = document.getElementById("offerlayer");
	oX = page_location(offerbox, 'Left');
	oY = page_location(offerbox, 'Top');
	oW = offerbox.offsetWidth;
	oH = offerbox.offsetHeight;

	for (var j=0; j<tag_types.length; j++) {
		selEl = document.all.tags(tag_types[j]);
		for (var i=0; i<selEl.length; i++) {
			select_box = selEl[i];
			sX = page_location(select_box, 'Left');
			sY = page_location(select_box, 'Top');
			sW = select_box.offsetWidth;
			sH = select_box.offsetHeight;
			if((oX+oW) < sX || oX > (sX+sW) || (oY+oH) < sY || oY > (sY+sH)) continue;
			select_box.isHidden = 1;
			select_box.style.visibility = 'hidden';
		}
	}
}
function show_select_boxes() {
	if(!document.all) return;

	tag_types = new Array("IFRAME", "SELECT", "OBJECT");
	for (var j=0; j<tag_types.length; j++) {
		selEl = document.all.tags(tag_types[j]);
		for (var i=0; i<selEl.length; i++) {
			select_box = selEl[i];
			if(typeof select_box.isHidden !=  'undefined' && select_box.isHidden) {
				select_box.isHidden = 0;
				select_box.style.visibility = 'visible';
			}
		}
	}
}
function page_location(o, t){
	x = 0;
	while(o.offsetParent){
		x += o['offset'+t];
		o = o.offsetParent;
	}
	x += o['offset'+t];
	return x
}
function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
    var word = document.getElementById('offer_id').value;
    qstr = 'w=' + escape(word);  // NOTE: no '?' before querystring
    return qstr;
}

function updatepage(str){
    if(window.opener &&  window.opener.document.getElementById("notepad"))
    window.opener.document.getElementById("notepad").innerHTML = str;
    else
        if(document.getElementById("notepad")){
            document.getElementById("notepad").innerHTML = str;
	        expandtab('cabtab', 1);
        }
    else
        if(document.getElementById("notepad1")){
            expandtab('cabtab', 1);
            }
    if(document.getElementById("result")){
        alert('test there');
        document.getElementById("result").innerHTML = str;

    }
}



// from base
var bustcachevar=1
var loadstatustext="<img src='images/loading.gif' align='absmiddle' hspace='3' alt='' /> Получение данных..."
var enabletabpersistence=1

var loadedobjects=""
var defaultcontentarray=new Object()
var bustcacheparameter=""

function ajaxpage(url, containerid, targetobj){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
var ullist=targetobj.parentNode.parentNode.getElementsByTagName("li")
for (var i=0; i<ullist.length; i++)
ullist[i].className=""
targetobj.parentNode.className="selected"
if (url.indexOf("#default")!=-1){ //if simply show default content within container (verus fetch it via ajax)
document.getElementById(containerid).innerHTML=defaultcontentarray[containerid]
return
}
document.getElementById(containerid).innerHTML=loadstatustext
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}

function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}

function loadobjs(revattribute){
if (revattribute!=null && revattribute!=""){
var objectlist=revattribute.split(/\s*,\s*/)
for (var i=0; i<objectlist.length; i++){
var file=objectlist[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" "
}
}
}
}

function expandtab(tabcontentid, tabnumber){
var thetab=document.getElementById(tabcontentid).getElementsByTagName("a")[tabnumber]
if (thetab.getAttribute("rel")){
ajaxpage(thetab.getAttribute("href"), thetab.getAttribute("rel"), thetab)
loadobjs(thetab.getAttribute("rev"))
}
}

function savedefaultcontent(contentid){
if (typeof defaultcontentarray[contentid]=="undefined")
defaultcontentarray[contentid]=document.getElementById(contentid).innerHTML
}

function startajaxtabs(){
for (var i=0; i<arguments.length; i++){
var ulobj=document.getElementById(arguments[i])
var ulist=ulobj.getElementsByTagName("li") //array containing the LI elements within UL
var persisttabindex=(enabletabpersistence==1)? parseInt(getCookie(arguments[i])) : ""
var isvalidpersist=(persisttabindex<ulist.length)? true : false
for (var x=0; x<ulist.length; x++){ //loop through each LI element
var ulistlink=ulist[x].getElementsByTagName("a")[0]
ulistlink.index=x
if (ulistlink.getAttribute("rel")){
var modifiedurl=ulistlink.getAttribute("href").replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+"/")
ulistlink.setAttribute("href", modifiedurl)
savedefaultcontent(ulistlink.getAttribute("rel"))
ulistlink.onclick=function(){
ajaxpage(this.getAttribute("href"), this.getAttribute("rel"), this)
loadobjs(this.getAttribute("rev"))
saveselectedtabindex(this.parentNode.parentNode.id, this.index)
return false
}
if ((enabletabpersistence==1 && persisttabindex<ulist.length && x==persisttabindex) || (enabletabpersistence==0 && ulist[x].className=="selected")){
ajaxpage(ulistlink.getAttribute("href"), ulistlink.getAttribute("rel"), ulistlink)
loadobjs(ulistlink.getAttribute("rev"))
}
}
}
}
}

////////////Persistence related functions//////////////////////////

function saveselectedtabindex(ulid, index){
if (enabletabpersistence==1)
setCookie(ulid, index)
}

function getCookie(Name){
var re=new RegExp(Name+"=[^;]+", "i");
if (document.cookie.match(re))
return document.cookie.match(re)[0].split("=")[1]
return ""
}

function setCookie(name, value){
document.cookie = name+"="+value
};


function dw_scroller(id, w, h, num, axis, bMouse) {
    this.id=id; this.el = document.getElementById? document.getElementById(id): null;
    if (!this.el) return; this.css = this.el.style;
    this.css.left = this.x = 0; this.css.top = this.y = 0;
    this.w=w; this.h=h; this.num=num; this.axis=axis||"v";
    this.ctr=0;
    this.pause=5000; this.speed=60; // defaults
    if (bMouse) dw_scrollers.setMouseEvents(this.el);
    this.lastTime = new Date().getTime(); this.check = 0;
    this.index = dw_scrollers.ar.length;  dw_scrollers.ar[this.index] = this;
    this.active = true;
}

dw_scroller.prototype.setTiming = function(speed, pause) {
    this.speed = speed; this.pause = pause;
}

dw_scroller.prototype.controlScroll = function() {
    if (this.ctr > this.num-1) {
        this.shiftTo(0, 0); this.ctr = 1;
    } else {
        switch (this.axis) {
            case "v" :
                if (this.y > -this.h * this.ctr) {
                    var ny = this.y + -1 * this.elapsed/1000 * this.speed;
                    ny = Math.max(ny, -this.h * this.ctr);
                    this.shiftTo(0, ny);
                } else this.doPause();
                break;
            case "h" :
                if (this.x > -this.w * this.ctr) {
                    var nx = this.x + -1 * this.elapsed/1000 * this.speed;
                    nx = Math.max(nx, -this.w * this.ctr);
                    this.shiftTo(nx, 0);
                } else this.doPause();
            break;
        }
    }
}

dw_scroller.prototype.doPause = function() {
    this.check += this.elapsed;
    if (this.check >= this.pause) { this.ctr++; this.check = 0; }
}

dw_scroller.prototype.shiftTo = function(x, y) {
    this.css.left = (this.x = x) + "px";
    this.css.top = (this.y = y) + "px";
}

////////////////////////////////////////////////////////////////////////////
// common to all scrollers (pausing or continuous, vertical or horizontal)
dw_scrollers = {};
dw_scrollers.ar = []; // global access to all scroller instances

dw_scrollers.setMouseEvents = function(obj) {
    obj.onmouseover = dw_scrollers.halt;
    obj.onmouseout = dw_scrollers.resume;
}

dw_scrollers.halt = function() {
    var curObj;
    for (var i=0; curObj = dw_scrollers.ar[i]; i++)
        if ( curObj.id == this.id ) { curObj.active = false; return; }
}

dw_scrollers.resume = function(e) {
    var curObj;
    for (var i=0; curObj = dw_scrollers.ar[i]; i++) {
        if ( curObj.id == this.id ) {
            e = e? e: window.event;
            var toEl = e.relatedTarget? e.relatedTarget: e.toElement;
            if ( this != toEl && !dw_contained(toEl, this) ) {
                var now = new Date().getTime();
                curObj.elapsed = now - curObj.lastTime;
                curObj.lastTime = now; curObj.active = true; return;
            }
        }
    }
}

// Handle all instances with one timer - idea from youngpup.net
dw_scrollers.timer = window.setInterval("dw_scrollers.control()", 10);
dw_scrollers.control = function() {
    var curObj;
    for (var i=0; curObj = dw_scrollers.ar[i]; i++) {
        if ( curObj.active ) {
            var now = new Date().getTime();
            curObj.elapsed = now - curObj.lastTime;
            curObj.lastTime = now; curObj.controlScroll();
        }
    }
}

// remove layers from table for ns6+/mozilla (needed for scrollers inside tables)
// pass id's of scrollers (i.e., div's that contain content that scrolls, usually wn, or wn1, ...)
dw_scrollers.GeckoTableFix = function() {
    var ua = navigator.userAgent;
    if ( ua.indexOf("Gecko") > -1 && ua.indexOf("Firefox") == -1
        && ua.toLowerCase().indexOf("like gecko") == -1 ) {
        dw_scrollers.hold = []; // holds id's of wndo (i.e., 'the scroller') and its container
        for (var i=0; arguments[i]; i++) {
            var wndo = document.getElementById( arguments[i] );
            var holderId = wndo.parentNode.id;
            var holder = document.getElementById(holderId);
            document.body.appendChild( holder.removeChild(wndo) );
            wndo.style.zIndex = 1000;
            var pos = getPageOffsets(holder);
            wndo.style.left = pos.x + "px"; wndo.style.top = pos.y + "px";
            dw_scrollers.hold[i] = [ arguments[i], holderId ];
        }
        window.addEventListener("resize", dw_scrollers.rePosition, true);
    }
}

// ns6+/mozilla need to reposition layers onresize when scrollers inside tables.
dw_scrollers.rePosition = function() {
    if (dw_scrollers.hold) {
        for (var i=0; dw_scrollers.hold[i]; i++) {
            var wndo = document.getElementById( dw_scrollers.hold[i][0] );
            var holder = document.getElementById( dw_scrollers.hold[i][1] );
            var pos = getPageOffsets(holder);
            wndo.style.left = pos.x + "px"; wndo.style.top = pos.y + "px";
        }
    }
}

function getPageOffsets(el) {
    var left = el.offsetLeft;
    var top = el.offsetTop;
    if ( el.offsetParent && el.offsetParent.clientLeft || el.offsetParent.clientTop ) {
        left += el.offsetParent.clientLeft;
        top += el.offsetParent.clientTop;
    }
    while ( el = el.offsetParent ) {
        left += el.offsetLeft;
        top += el.offsetTop;
    }
    return { x:left, y:top };
}

// returns true if oNode is contained by oCont (container)
function dw_contained(oNode, oCont) {
  if (!oNode) return; // in case alt-tab away while hovering (prevent error)
  while ( oNode = oNode.parentNode ) if ( oNode == oCont ) return true;
  return false;
}

// avoid memory leak in ie
dw_scrollers.unHook = function() {
  var i, curObj;
  for (i=0; curObj = dw_scrollers.ar[i]; i++) {
    if ( curObj.el ) {
      curObj.el.onmouseover = null;
      curObj.el.onmouseout = null;
      curObj.el = null;
    }
  }
}

if ( window.addEventListener ) window.addEventListener( "unload", dw_scrollers.unHook, true);
else if ( window.attachEvent ) window.attachEvent( "onunload", dw_scrollers.unHook );
