function openw(url, title, options) {
	var newwin = window.open(url, title, options);
	newwin.focus();
}

function reloadCaptcha() {
	var img = document.getElementById('cappic');
	img.src = '/lib/frmcaptcha.php?rld=' + Math.random();
	return false;
}

function vbaneri2(section, htmlstart, htmlend) {
	if (!banners[section]) return false;
	if (showban1==1) {
		document.write(htmlstart);
		vbaneri(section);
		document.write(htmlend);
	}
}

function prodredir(t){
	window.location.href=t.options[t.selectedIndex].value;
} 

var JSemote = {
	'/i/icons/face-angel.png':'0:-)',
	'/i/icons/face-crying.png':':\'(',
	'/i/icons/face-devil-grin.png':':devil:',
	'/i/icons/face-glasses.png':'B-)',
	'/i/icons/face-kiss.png':':-*',
	'/i/icons/face-monkey.png':':(|)',
	'/i/icons/face-plain.png':':-|',
	'/i/icons/face-sad.png':':(',
	'/i/icons/face-smile.png':':)',
	'/i/icons/face-smile-big.png':':D',
	'/i/icons/face-surprise.png':':-0',
	'/i/icons/face-wink.png':';)'
};

function QuoteForum(tid, aid, sid) {
	var frm = document.forms['addcomment'];
	
	var author = document.getElementById(aid).innerHTML;
	author = author.replace(/<[^>]+>/gmi, '');
	author = author.replace(/\s\(.*\)/gmi, '');
	
	var msgtxt = document.getElementById(tid).innerHTML;
	msgtxt = msgtxt.replace(/<img\s+src="([^"]*)"[^>]+>/gmi, '*^*$1*^*');
	var msgarr = msgtxt.split('*^*');
	
	
	
	for (var i = 0; i < msgarr.length; i ++) {
		if (JSemote[msgarr[i]]) {
			msgarr[i] = JSemote[msgarr[i]];
		}
	}
	
	msgtxt = msgarr.join('');
	msgtxt = msgtxt.replace(/<fieldset class="quotetation"><legend>([^<]*)<\/legend>/gmi, '[quote="$1"]');
	msgtxt = msgtxt.replace(/<\/fieldset>/gmi, '[/quote]');
	
	var quotation = '[quote="' + author + '"]';
	quotation += msgtxt;
	quotation += '[/quote]';
	
	frm.msg.value = quotation;
	window.location.hash = 'addcomment';
}

var allglobalopts = new Object();

function rld(targelname, targel, filtername, filterval, frm) {
	var msel = 0;
	if (!targel) {
		if (!frm) return;
		targel = document.forms[frm].elements[targelname + "[]"];
		msel = 1;
	}
	
	if (!allglobalopts[targelname]) {
		allglobalopts[targelname] = targel.cloneNode(true).options;
		for(i = 0; i < allglobalopts[targelname].length; i++) {
			allglobalopts[targelname][i].selected = targel[i].selected;
		}
	}
	var allopt = allglobalopts[targelname];
	
	targel.options.length = 0;
	targel.selectedIndex = -1;
	for(i = 0; i < allopt.length; i++) {
		if (allopt[i].getAttribute(filtername) == filterval || allopt[i].value == "") {
			neweli = targel.options.length;
			targel.options[neweli] = new Option(allopt[i].text, allopt[i].value, false, allopt[i].selected);
			for(var n = 0; n < allopt[i].attributes.length; n ++) {
				if (
					allopt[i].attributes[n].nodeName != 'selected' && 
					allopt[i].attributes[n].nodeName != 'name' && 
					allopt[i].attributes[n].nodeName != 'id' && 
					allopt[i].attributes[n].nodeName != 'value' && 
					allopt[i].attributes[n].nodeName != 'type'
				) {
					targel.options[neweli].setAttribute(allopt[i].attributes[n].nodeName, allopt[i].attributes[n].nodeValue);
				}
			}
		}
	}
	if(targel.onchange) targel.onchange();
}

function rldContent(t, txt) {
	if (t.value == txt) {
		t.value = '';
	}
}

function rldContent2(t, txt) {
	if (t.value == '') {
		t.value = txt;
	}
}

function CheckLoginForm(frm, uname, upass) {
	if (frm.uname.value == uname) {
		frm.uname.value = '';
	}
	
	if (frm.upass.value == upass) {
		frm.upass.value = '';
	}

	return true;

}

function getTooltipEl() {
	d = document.getElementById("tooltipel");
	if (d) return d;

	di = document.createElement("IFRAME");
	di.id = "ttiframe";
	di.frameborder = 0;
	di.scrolling = "no";
	di.style.width = '250px';
	di.style.position = "absolute";
	di.style.border = "0px";
	di.style.zIndex = 90;
	document.body.appendChild(di);

	d = document.createElement("DIV");
	d.id = "tooltipel";
	d.className = 'infobox';
	d.style.zIndex = 100;
	document.body.appendChild(d);		
	return d;
}


function DisplayInfobox(t, ibox) {
	var box = document.getElementById(ibox);
	d = getTooltipEl();
	di = document.getElementById("ttiframe");
	d.innerHTML = box.innerHTML;
	d.style.left = getOffset(t, "Left") + "px";
	d.style.top = getOffset(t, "Top") + "px";
	
	objLeft   = t.offsetLeft;
	objTop    = t.offsetTop;		
	objParent = t.offsetParent;

	while( objParent.tagName.toUpperCase() != "BODY" ) {
		objLeft  += objParent.offsetLeft;
		objTop   += objParent.offsetTop;
		objParent = objParent.offsetParent;
	}
	
	d.style.display = "block";
	di.style.display = "block";
	
	if (document.body.clientWidth < (objLeft + t.offsetWidth + d.offsetWidth)) {
		d.style.left = getOffset(t, "Left") - (d.offsetWidth - t.offsetWidth) + "px";
	}
	
	di.style.left = d.style.left;
	di.style.top = d.style.top;
	
	di.style.width = d.offsetWidth + 'px';
	di.style.height = d.offsetHeight + 'px';
}

function HideInfobox(ibox) {
	d = getTooltipEl();
	di = document.getElementById("ttiframe");
	d.style.display = '';
	di.style.display = '';
}


function getOffset(el, which) {
	var amount = el["offset" + which];
	if (which=="Top")
		amount += el.offsetHeight;
	el = el.offsetParent;
	while (el != null) {
		amount += el["offset" + which];
		el = el.offsetParent;
	}
	return amount;
}

var _CAL_IS_IE = (navigator.userAgent.toLowerCase().indexOf("msie") > -1) ? true : false;

var jscalcallerfrm = "";
var jscalcallerel = "";
var jscalalignment = "";

function jscalbuild(yy, mm) {
	d = new Date(yy, mm, 1);
	s = "";
	
	oldmonth = d.getMonth();
	oldyear = d.getRealYear();
	
	firstweekcnt = 0;
	firstweek = false;
	
	i = 1;
	
	while(oldmonth == d.getMonth()) {
		if (!firstweek) firstweekcnt++;
		
		if (d.getDay() == 1 && i > 1) {
			s += "</tr><tr>";
			firstweek = true;
		}
		
		if (d.getDay() == 0 || d.getDay() == 6) {
			bgtag = "style=\"background-color: #f8f8f0;\" ";
		} else {
			bgtag = "";
		}
		s += "<td " + bgtag + "align=\"center\" onMouseUp=\"jscalcellclick(this)\"><a href=\"#\" onClick=\"return jscalsetdate('" + (d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getRealYear()) + "')\">" + d.getDate() + "</a></td>";
		d.setDate(++i);
	}
	
	if (firstweekcnt == 8) firstweekcnt = 0;
	
	if (firstweekcnt > 1) {
		for (i = 0; i <  8 - firstweekcnt; i++) {
			s = "<td></td>" + s;
		}
	}
	
	nextmonth = d.getMonth();
	nextyear = d.getRealYear();
	d.setYear(oldyear);
	d.setMonth(oldmonth - 1);
	prevmonth = d.getMonth();
	prevyear = d.getRealYear();
	
	s = "<table class=\"cal\" width=\"100%\" cellspacing=\"1\" cellpadding=\"1\" border=\"0\"><tr><th>Mn</th><th>Tu</th><th>Wn</th><th>Th</th><th>Fr</th><th>Sa</th><th>Su</th></tr><tr>" + s + "</tr></table>";
	t = "<table border=\"0\" cellspacing=\"0\" cellpadding=\"1\" width=\"100%\" class=\"cal\"><tr>";
	if (jscalalignment=='right')
		t += "<td valign=\"top\" width=\"10\"><a href=\"#\" onClick=\"return jscalhide()\"><img src=\"/i/calico.gif\" border=\"0\"/></a></td>";
	t += "<td>&nbsp;<a title=\"Month Back\" style=\"text-decoration: none;\" onMouseUp=\"return jscalrecalc(" + prevyear + ", " + prevmonth + ")\">&#9668;</a>&nbsp;</td>";
	t += "<td width=\"100%\" align=\"center\">" + (mm + 1) + "&nbsp;/&nbsp;" + yy + "</td>";
	t += "<td align=\"right\"><a title=\"Month Forward\" style=\"text-decoration: none;\"  onMouseUp=\"return jscalrecalc(" + nextyear + ", " + nextmonth + ")\">&#9658;</a></td>";
	if (jscalalignment=='left')
		t += "<td valign=\"top\" width=\"10\"><a href=\"#\" onClick=\"return jscalhide()\"><img src=\"/i/calico.gif\" border=\"0\"/></a></td>";
	t += "</tr></table>";
	
	return t + s;
}

function jscalsetdate(dt) {
	document.forms[callerfrm].elements[callerel].value = dt;
	jscalhide();
	return false;
}

function jscalcellclick(a) {
	a.firstChild.onclick();
	return false;
}

var callerfrm = '';
var callerel = '';

function jscalshow(w, targetfrm, targetel) {
	if (!w) w = event.srcElement;
	
	callerfrm = targetfrm;
	callerel = targetel;
	
	var tmpelwidth = w.offsetWidth;
	
	for ( var posl = 0, post = 0; w.style.position != 'absolute' && w.style.position != 'relative' && w.offsetParent; w = w.offsetParent ) {
		posl += w.offsetLeft; post += w.offsetTop;
	}
	
	post -= 3;
	posl -= 3;

	w = document.body.clientWidth;
	
	jscalalignment = "right";
	
	if (w - posl < 151) {
		jscalalignment = "left";
		posl -= 150 - tmpelwidth - 5;
	}

	var c = document.getElementById("calid");

	var ddd = new Date();
	c.innerHTML = jscalbuild(ddd.getRealYear(), ddd.getMonth());

	c.style.top = (post - 2) + 'px';
	c.style.left = (posl - 2) + 'px';
	c.style.display = "block";
	
	if (_CAL_IS_IE) {
		var fm = document.getElementById("calidfrm");
		fm.style.top = (post - 2) + 'px';
		fm.style.left = (posl - 2) + 'px';
		fm.style.width = c.offsetWidth;
		fm.style.height = c.offsetHeight;
		fm.style.display = "block";
	}
	
	
	
	return false;
}

function jscalhide() {
	c = document.getElementById("calid");
	c.style.display = "none";
	if (_CAL_IS_IE) {
		fm = document.getElementById("calidfrm");
		fm.style.display = "none";
	}
	
	return false;
}

function jscalrecalc(yy, mm) {
	c = document.getElementById("calid");
	c.innerHTML = jscalbuild(yy, mm);
	
	if (_CAL_IS_IE) {
		fm = document.getElementById("calidfrm");
		fm.style.height = c.offsetHeight;
	}
	
	return false;
}

// window.onload = jscalcreateparentel;

// tva e za da se create-va dinamichno - za momenta ne go izpolzvame
function jscalcreateparentel() {
	// div: z-index: 2; display: none; position: absolute; width: 150px; height: auto; background-color: White;
	// iframe: z-index: 1; display: none; position: absolute; left: 0px; top: 0px;
	if (_CAL_IS_IE) {
		var oFrm=document.createElement("IFRAME");
		document.body.appendChild(oFrm);
		oFrm.id = "calidfrm";
		oFrm.src = "about:blank";
		oFrm.border = 0;
		oFrm.frameBorder = 0;
		oFrm.style.position = "absolute";
		oFrm.style.zIndex = 1;
		oFrm.style.display = "none";
		oFrm.style.width = "150px";
		oFrm.style.height = "auto";
		oFrm.style.backgroundColor = "White";
		oFrm.style.left = "0px";
		oFrm.style.top = "0px";
	}
	
	var oDiv=document.createElement("DIV");
	document.body.appendChild(oDiv);
	oDiv.id = "calid";
	oDiv.style.position = "absolute";
	oDiv.style.zIndex = 2;
	oDiv.style.display = "none";
	oDiv.style.width = "150px";
	oDiv.style.height = "auto";
	oDiv.style.backgroundColor = "White";
}

// tva e shoto getYear pod vsichki browseri vrushta razlichni neshta
Date.prototype.getRealYear = function() {
	var lyear = this.getYear();
	if (lyear < 1500) lyear += 1900; // deba i skapanite browseri
	return lyear;
}

// Menuta
function DisplaySubmenu(t, menuId, mmid, toppos) {
	HideAllSm(menuId, mmid);
	d = document.getElementById(menuId);
	if (!d) return;
	
	di = getSubmenuIframe(mmid);
	d.style.position = 'absolute';
	d.style.left = t.offsetLeft + "px";
	d.style.top = toppos;
	di.style.left = t.offsetLeft + "px";
	di.style.top = toppos;
	
	d.style.display = "block";
	di.style.display = "block";
	di.style.width = d.offsetWidth + 'px';
	di.style.height = (d.offsetHeight - 12) + 'px';
}

function HideSubmenu(menuId, event, mmid){
	var from=event.fromElement || event.target;
	var to=event.toElement || event.relatedTarget;
	
	var e=to;
	while(e && e.className!='submenu'){
		e=e.parentNode;
	}
	if(e) return;
	
	//~ console.log('grr closing');
	d = document.getElementById(menuId);
	if (!d) return;
	di = getSubmenuIframe(mmid);
	d.style.display = 'none';
	di.style.display = 'none';	
}

function HideAllSm(menuId, mmid) {
	var smh = document.getElementById(mmid);
	var divs = smh.getElementsByTagName('div');
	di = getSubmenuIframe(mmid);
	
	for (var i = 0; i < divs.length; i ++) {
		if (divs[i].id.match(/^menu(\d+)/)) {
			if (divs[i].id != menuId) {
				divs[i].style.display = 'none';
			}
		}
	}
	di.style.display = 'none';
}

function getSubmenuIframe(mmid) {
	di = document.getElementById('menu_IFRAME');
	if (di) return di;
	di = document.createElement("IFRAME");
	di.id = "menu_IFRAME";
	di.frameborder = 0;
	di.scrolling = "no";
	di.style.display = 'none';
	di.style.position = "absolute";
	di.style.border = "0px";
	di.style.zIndex = 98;
	
	var mm = document.getElementById(mmid);
	mm.appendChild(di);		
	return di;
}

var FirstCheckedCat;

function CompareCboxChecked(t) {
	var tab = document.getElementById('ProductListTable');
	if (!tab) return;
	
	if (!FirstCheckedCat) {
		FirstCheckedCat = t.getAttribute('cat_id');
	}
	var boxes = tab.getElementsByTagName('input');
	var cnt = 0;
	
	for (var i = 0; i < boxes.length; i ++) {
		if (boxes[i].getAttribute('compare_cbox') == 'true') {
			if (boxes[i].checked) cnt ++;
		}
	}
	
	for (var i = 0; i < boxes.length; i ++) {
		if (boxes[i].getAttribute('compare_cbox') == 'true') {
			if (boxes[i].getAttribute('cat_id') != FirstCheckedCat) {
				boxes[i].disabled = true;
				boxes[i].className = 'disabled_cbox';
			}
			if (cnt >= 4) {
				if (!boxes[i].checked) {
					boxes[i].disabled = true;
					boxes[i].className = 'disabled_cbox';
				}
			} else {
				if (cnt == 0) FirstCheckedCat = 0;
				if (cnt == 0 || boxes[i].getAttribute('cat_id') == FirstCheckedCat) {
					boxes[i].disabled = false;
					boxes[i].className = '';
				}
			}
		}
	}
	
	t.blur();
	if (cnt > 4) {
		t.disabled = true;
		return false;
	}
	return true;
}

function CompareSendData(calctype) {
	var tab = document.getElementById('ProductListTable');
	if (!tab) return;
	var cat_id;
	var prods = [];
	var boxes = tab.getElementsByTagName('input');
	
	for (var i = 0; i < boxes.length; i ++) {
		if (boxes[i].getAttribute('compare_cbox') == 'true') {
			if (!cat_id) cat_id = boxes[i].getAttribute('cat_id');
			if (boxes[i].checked) {
				prods.push(boxes[i].value);
			}
		}
	}
	if (cat_id && prods.length) {
		var url = '/compare.php?calctype=' + calctype + '&cat_id=' + cat_id;
		for (var i = 0; i < prods.length; i ++) {
			url += '&product_' + (i + 1) + '=' + prods[i];
		}
		window.location.href = url;
	}
}

function ShowHideCalcRes(t) {
	var d = document;
	if (!t) return;
	var hdiv = d.getElementById('calcres_info');
	if (hdiv.style.display == 'none') {
		hdiv.style.display = '';
		t.innerHTML = 'Скрий погасителния план';
	} else {
		hdiv.style.display = 'none';
		t.innerHTML = 'Виж погасителния план';
	}
	window.location.hash = 'calcbottom';
	t.blur();
}

function ShowHideCalc(t, showcalc) {
	var d = document;
	if (!t) return;
	var hdiv = d.getElementById('showhide_calc');
	if (hdiv.style.display == 'none' || showcalc == 1) {
		hdiv.style.display = '';
		t.innerHTML = 'Скрий калкулатора';
	} else {
		hdiv.style.display = 'none';
		t.innerHTML = 'Вноски по кредита';
	}
	t.blur();
}

var fontSizesArr = new Array('9px', '10px', '11px', '12px', '13px', '14px', '15px');
var activeFontSize = 3;
var tmpfontsize = readCookie('fincityFontSize');
if (tmpfontsize) activeFontSize = parseInt(tmpfontsize);
var cookiesDayLimit = 100;

function defFontSize() {
	activeFontSize = 3;
	setFontSize();
}

function increaseFontSize() {
	if (parseInt(activeFontSize) + 1 >= fontSizesArr.length) return false;
	activeFontSize ++;
	setFontSize();
}

function decreaseFontSize() {
	if (parseInt(activeFontSize) - 1 < 0) return false;
	activeFontSize --;
	setFontSize();
}

function setFontSize() {
	if (document.styleSheets[0].rules) {
		var css = document.styleSheets[0].rules;
	} else {
		var css = document.styleSheets[0].cssRules;
	}
	
	for (var i = 0; i < 3; i++) {
		if (css[i].selectorText.toLowerCase() == 'body') {
			if (document.all) {
				css[i].style.fontSize = fontSizesArr[activeFontSize];
			} else {
				css[i].style.setProperty('font-size', fontSizesArr[activeFontSize], null);
			}
			createCookie('fincityFontSize', activeFontSize, cookiesDayLimit);
		}
	}
}

function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	} else 
		var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	var ca = document.cookie.split(';');
	var nameEQ = name + "=";
	for(var i=0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1, c.length); //delete spaces
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name, "", -1);
}

// correctly handle PNG transparency in Win IE 5.5 & 6.
function correctPNG() {
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);
	if ((version >= 5.5) && (document.body.filters)) {
		for(var i=0; i<document.images.length; i++) {
			var img = document.images[i];
			var imgName = img.src.toUpperCase();
			if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
				var imgID = (img.id) ? "id='" + img.id + "' " : "";
				var imgClass = (img.className) ? "class='" + img.className + "' " : "";
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
				var imgStyle = "display:inline-block;" + img.style.cssText;
				if (img.align == "left") imgStyle = "float:left;" + imgStyle;
				if (img.align == "right") imgStyle = "float:right;" + imgStyle;
				if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
					+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
					+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
					+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" ;
				img.outerHTML = strNewHTML;
				i = i-1;
			}
		}
	}    
}

if (window.addEventListener){ 
	// ...
} else if (window.attachEvent){ 
	window.attachEvent("onload", correctPNG);
}

function HemTakaHemInache(t) {
	if (t.options[t.selectedIndex].value == 38) {
		window.location.href = '/prod.php?cat=38';
	}
}

function doAjax(url, params, target, prod){
	req = GetXmlHttpObject();
	
	req.onreadystatechange = function(){
			
		if (req.readyState == 4) {
			if (req.status == 200) {
				var text = req.responseText;	
				proccess(target, text, prod);
			} else {
				alert("Problem: " + req.statusText);
			}
		}
	}
	req.open('POST', url, true);
	req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	req.setRequestHeader("Content-length", params.length);
	req.setRequestHeader("Connection", "close");
	req.send(params);	
	
}

function GetXmlHttpObject(){ 
	var xmlHttp;
  try
    {
    // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      try
        {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
        alert("Your browser does not support AJAX!");
        return false;
        }
      }
    }
	return xmlHttp;
}

function proccess(target, text, prod){	
	document.getElementById(target).innerHTML = text;
	if (prod != '') {
		document.getElementById(target).firstChild.value = prod;
	}
}

function changeProdukts (form, prod) {
	var bankid = form['bank'].value;
	var valid = form['valuta'].value;
	var catid = form['cat_id'].value;
	var params = '';
	if (bankid != "" && catid !="" && valid != "") {
		params = 'bankid='+bankid+'&catid='+catid+'&val='+valid;
		var url = 'ajax_acept.php';
		doAjax(url, params, 'products', prod);
	} 
}

function stateChanged(el, processing, denied, finished) {
	var pipeline = document.getElementsByName('in_pipeline')[0];
	if (typeof pipeline != 'undefined') {
		if ((el.value == processing) || (el.value == finished)) {
			pipeline.value = 2;
		} else {
			pipeline.value = 1;
		}
	}
}
