var  isIE6CSS = (document.compatMode && document.compatMode.indexOf("CSS1") >= 0) ? true : false;



function ConfirmDelete() {
	return (window.confirm("Действительно удалить?"));

}
function clSelfrelOp(){

	self.close();
	self.opener.location.reload();
}
function delPopup(url){

	var del;
	del = ConfirmDelete();
	if (del != false){

		PopupWindow(url);

	}

}
var newWindow;
function PopupWindow(URL,w,h) {
	self.name="smmain"
	var topPos=0;
	var leftPos=(screen.width-340)>>1;
	if (!h)
	{
		var winHeight=screen.availHeight-50;
	} else {
		var winHeight = h;
	}
	var left = parseInt((screen.availWidth/2) - (w/2));
	var top = parseInt((screen.availHeight/2) - (winHeight/2));
	var windowFeatures = "width=" + w + ",height=" + winHeight +
	",dependent=yes,status,resizable=no, scrollbars=yes,left=" + left + ",top=" + top +
	",screenX=" + left + ",screenY=" + top;


	if (!newWindow || newWindow.closed) {
		newWindow = window.open(URL, "details",windowFeatures);
	} else
	{		newWindow.document.location.href = URL;
	newWindow.focus();
	}

}
function delPopup(url){

	var del;
	del = ConfirmDelete();
	if (del != false){

		window.location.href = url;

	}

}

function isinArray(array,find){

	if (array.length>1){
		var cc = 0;
		for (var i = 0; i < array.length; i++) {
			if (array[i] == find){

				cc += 1;}


		}
		if(cc > 0){
			return true;
		} else {
			return false;
		}
	} else {
		if(array == find){
			return true;
		} else {
			return false;
		}
	}
}

function string2Array(string) {
	eval("var result = " + string);
	return result;
}
function getElementWithId(id){
	var obj = null;
	if(document.getElementById){
		/* Prefer the widely supported W3C DOM method, if
		available:-
		*/
		obj = document.getElementById(id);
	}else if(document.all){
		/* Branch to use document.all on document.all only
		browsers. Requires that IDs are unique to the page
		and do not coincide with NAME attributes on other
		elements:-
		*/
		obj = document.all[id];
	}
	/* If no appropriate element retrieval mechanism exists on
	this browser this function always returns null:-
	*/
	return obj;
}
function hasClass(obj) {
	var result = false;
	if (obj.getAttributeNode("class") != null) {
		result = obj.getAttributeNode("class").value;
	}
	return result;
}


function stripe(id) {

	// the flag we'll use to keep track of
	// whether the current row is odd or even
	var even = false;

	// if arguments are provided to specify the colours
	// of the even & odd rows, then use the them;
	// otherwise use the following defaults:
	var evenColor = arguments[1] ? arguments[1] : "#fff";
	var oddColor = arguments[2] ? arguments[2] : "#eee";

	// obtain a reference to the desired table
	// if no such table exists, abort
	var table = document.getElementById(id);
	if (! table) { return; }

	// by definition, tables can have more than one tbody
	// element, so we'll have to get the list of child
	// &lt;tbody&gt;s
	var tbodies = table.getElementsByTagName("tbody");

	// and iterate through them...
	for (var h = 0; h < tbodies.length; h++) {

		// find all the &lt;tr&gt; elements...
		var trs = tbodies[h].getElementsByTagName("tr");

		// ... and iterate through them
		for (var i = 0; i < trs.length; i++) {

			// avoid rows that have a class attribute
			// or backgroundColor style
			if (!hasClass(trs[i]) && ! trs[i].style.backgroundColor) {

				// get all the cells in this row...
				var tds = trs[i].getElementsByTagName("td");

				// and iterate through them...
				for (var j = 0; j < tds.length; j++) {

					var mytd = tds[j];

					// avoid cells that have a class attribute
					// or backgroundColor style
					if (! hasClass(mytd) && ! mytd.style.backgroundColor) {

						mytd.style.backgroundColor = even ? evenColor : oddColor;

					}
				}
			}
			// flip from odd to even, or vice-versa
			even =  ! even;
		}
	}
}

/*function validate(reqs) {

var errors='';
for (var i = 0; i < reqs.length; i++) {

var str = document.getElementById(reqs[i]).value;
//alert(str.length);
if(str == '' || str.length < 9) {
errors +=(reqs[i] +" is empty! \n");
}
}
if (errors != ''){
alert(errors);
return false;
} else {
return true;

}

}*/
function showHide(id,img){
	if (document.getElementById(id).style.display == 'block')
	{
		document.getElementById(id).style.display = 'none';
		document.getElementById(img).src = '/admin/images/folder1.gif'
	}
	else if(document.getElementById(id).style.display == 'none')
	{
		document.getElementById(id).style.display = 'block';
		document.getElementById(img).src = '/admin/images/folder-d.gif'
	}

}
function switchVis(id,evt){

	if (document.getElementById(id).style.display == 'block')
	{
		document.getElementById(id).style.display = 'none';
	} else
	{
		document.getElementById(id).style.display = 'block';
	}


}

function switchVisAndMove(id,evt){

	if (document.getElementById(id).style.display == 'block')
	{
		document.getElementById(id).style.display = 'none';
	} else
	{
		document.getElementById(id).style.display = 'block';
		evt = (evt) ? evt : event;
		var coords = getPageEventCoords(evt);
		document.getElementById(id).style.left = coords.left+'px';
		document.getElementById(id).style.top = (coords.top-5)+'px';

		var windowWidth = getInsideWindowWidth();
		var rightMargin = windowWidth -(coords.left + document.getElementById(id).offsetWidth);
		if (rightMargin < 50)
		{
			//move left

			left = windowWidth-document.getElementById(id).offsetWidth-50;

			document.getElementById(id).style.left = left+'px';
		}

	}





}//


function getInsideWindowHeight() {
	if (window.innerHeight) {
		return window.innerHeight;
	} else if (isIE6CSS) {
		// measure the html element's clientHeight
		return document.body.parentElement.clientHeight;
	} else if (document.body && document.body.clientHeight) {
		return document.body.clientHeight;
	}
	return 0;
}

function getInsideWindowWidth() {
	if (window.innerWidth) {
		return window.innerWidth;
	} else if (isIE6CSS) {

		return document.body.parentElement.clientWidth;
	} else if (document.body && document.body.clientWidth) {
		return document.body.clientWidth;
	}
	return 0;
}


function Hide(id){
	if (document.getElementById(id).style.display == 'block')
	{
		document.getElementById(id).style.display = 'none';

	}
}


function updateCheckboxes() {
	var els = document.getElementsByTagName('input');
	for(var i=0; i<=els.length;i++) {
		if (els[i]) {
			if (els[i].getAttribute('type') == 'checkbox') {
				if (els[i].value && els[i].getAttribute('is_checked')=='1')
				els[i].checked = true;
			}
		}
	}
}


function CommaFormatted(amount,showZero,showDollarSign,decimalPlaces) {
	wholeAmt   = strdecimal(amount);	// strip all but numeric-related characters
	wholeAmt = wholeAmt.toFixxed(decimalPlaces);
	if (isNaN(wholeAmt)) wholeAmt = 0;
	var minus = "";
	if (wholeAmt < 0) {
		wholeAmt = -wholeAmt;
		minus = "-";
	}
	if (wholeAmt == 0 && !showZero) return "";
	integerAmt = parseInt(wholeAmt);
	decimalAmt = Math.round((wholeAmt - integerAmt)*Math.pow(10,decimalPlaces));
	intStr = integerAmt.toString();
	decStr = decimalAmt.toString();
	while (decStr.length < decimalPlaces)
	decStr = '0'+decStr;
	//alert('CF amount: '+amount+'  wholeAmt:'+wholeAmt+'  integerAmt:'+integerAmt+'  intStr:'+intStr+'  decimalAmt:'+decimalAmt+'  decStr:'+decStr);
	intStr = addCommasToInteger(intStr);
	retStr = minus+(showDollarSign ? "$" : "") + intStr
	+ (decimalPlaces > 0 ? "."+decStr : "");
	//alert (minus);
	return retStr;


	// alert(amount);
	var delimiter = ","; // replace comma if desired
	rExp = new RegExp(delimiter,"g");
	amount = amount.replace(rExp,"");	// zap existing delimiters
	rExp = new RegExp("\.","i");
	if (!rExp.test(amount))
	amount += '.00';
	var a = amount.split('.',2)
	if (a[0] == '') a[0] = '0';
	if (a[1] == undefined) a[1] = '00';
	var d = (a[1] == '' ? '00' : a[1]);
	if (d.length == 1) d += '0';
	var i = parseInt(a[0]);
	if(isNaN(i)) return ('');
	var minus = (i < 0 ? '-' : '');
	i = Math.abs(i);
	var n = new String(i);
	var a = [];
	while(n.length > 3) {
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) a.unshift(n);
	n = a.join(delimiter);
	amount = n + '.' + d;
	amount = minus + amount;
	//alert (minus);
	if (showZero == false && parseFloat(amount) == 0) return ('');
	if (showDollarSign) amount = '$' + amount;
	return amount;

} /* CommaFormatted */

function strdecimal (inStr) {
	// strips everything but the numbers, minus sign, and decimal point
	return (parseFloat(inStr.toString().replace(/[^0-9.\-]/g, "")));

} /* strdecimal */
Number.prototype.toFixxed = function(f) {
	f = parseInt(f/1 || 0)
	if (f<0 || f>20) // next line was throw ...
	alert("The number of fractional digits is out of range")
	if (isNaN(this)) return "NaN"
	var s = this<0 ? "-" : "", x = Math.abs(this)
	if (x>Math.pow(10,21)) return s + x.toString()
	var m = Math.round(x*Math.pow(10,f)).toString()
	if (!f) return s + m
	while (m.length<=f) m = "0" + m
	return s + m.substring(0,m.length-f)+"."+m.substring(m.length-f)
}

function addCommasToInteger (intStr) {
	var commaStr = "";
	var charCount = 0;
	for (var i = intStr.length; i >0; i--) {
		var thisChar = intStr.substr(i-1, 1);
		if (charCount %3 == 0 && charCount > 0) {
			commaStr = "," + commaStr;
		}
		commaStr = thisChar + commaStr;
		charCount++;
	}
	return commaStr;
}

function getFieldDecimalValue (fieldID,decimalPlaces) {
	return getDecimalValue (document.getElementById(fieldID).value,decimalPlaces);
}

function getDecimalValue (amount,decimalPlaces) {
	var wholeAmt = strdecimal(amount);	// strip all but numeric-related characters
	wholeAmt = wholeAmt.toFixxed(decimalPlaces);
	if (isNaN(wholeAmt)) wholeAmt = 0;
	return wholeAmt;
}


function setAllVals(value,subname) {

	var els = document.getElementsByTagName('input');
	for(var i=0; i<=els.length;i++) {
		if (els[i]) {
			if (els[i].getAttribute('subname')==subname) {
				els[i].value  = value;
			}
		}
	}
}

function CheckEmail (emailField,emptyOK) {
	var newstr = "";
	var at = false;
	var dot = false;
	var tld = "";
	var checkString = emailField.value;
	var validTLDs = ":com:net:org:edu:aero:biz:coop:info:museum:name:pro:ad:ae:af:ag:ai:" +
	"al:am:an:ao:aq:ar:as:at:au:aw:az:ba:bb:bd:be:bf:bg:bh:bi:bj:bm:bn:" +
	"bo:br:bs:bt:bv:bw:by:bz:ca:cc:cf:cg:ch:ci:ck:cl:cm:cn:co:cr:cs:cu:" +
	"cv:cx:cy:cz:de:dj:dk:dm:do:dz:ec:ee:eg:eh:er:es:et:fi:fj:fk:fm:fo:" +
	"fr:fx:ga:gb:gd:ge:gf:gh:gi:gl:gm:gn:gp:gq:gr:gs:gt:gu:gw:gy:hk:hm:" +
	"hn:hr:ht:hu:id:ie:il:in:io:iq:ir:is:it:jm:jo:jp:ke:kg:kh:ki:km:kn:" +
	"kp:kr:kw:ky:kz:la:lb:lc:li:lk:lr:ls:lt:lu:lv:ly:ma:mc:md:mg:mh:mk:" +
	"ml:mm:mn:mo:mp:mq:mr:ms:mt:mu:mv:mw:mx:my:mz:na:nc:ne:nf:ng:ni:nl:" +
	"no:np:nr:nt:nu:nz:om:pa:pe:pf:pg:ph:pk:pl:pm:pn:pr:pt:pw:py:qa:re:" +
	"ro:ru:rw:sa:sb:sc:sd:se:sg:sh:si:sj:sk:sl:sm:sn:so:sr:st:su:sv:sy:" +
	"sz:tc:td:tf:tg:th:tj:tk:tm:tn:to:tp:tr:tt:tv:tw:tz:ua:ug:uk:um:us:" +
	"uy:uz:va:vc:ve:vg:vi:vn:vu:wf:ws:ye:yt:yu:za:zm:zr:zw:int:mil:arpa:nato:";

	if (emailField.type == 'hidden') return (true);

	if (isEmpty(checkString) && (emptyOK == true)) {
		return (true);
	}

	tld = reverseStr(checkString);
	tld = tld.substr(0,tld.search(/\./));			// find the '.' and copy to it
	tld = ":" + reverseStr(tld).toLowerCase() + ":";	//This becomes the search string
	if (validTLDs.search(tld) == -1) {
		//alert("Неверный формат email");
		// emailField.focus();
		return (false);
	}


	for (var i = 0; i < checkString.length; i++) {
		ch = checkString.substring(i, i + 1)
		if ((ch >= "A" && ch <= "Z") || (ch >= "a" && ch <= "z")
		|| (ch == "@") || (ch == ".") || (ch == "_")
		|| (ch == "-") || (ch >= "0" && ch <= "9")) {
			newstr += ch;
			if (ch == "@") {
				if (at == true) { //only one per address!
					at = false;
					break;
				}
				at=true;
			}
		}
	}
	if (!at) {
		//alert("Неверный формат email");
		//emailField.focus();
		return (false);
	}
	if (newstr.length != checkString.length) {	// invalid characters were not copied
		//alert("Неверный формат email");
		//emailField.focus();
		return (false);
	}

	return (true);
} /* CheckEmail() */


function isEmpty (inStr) {
	var s = trimStr(inStr);
	return ((s.length == 0) || (s == ""));
} /* isEmpty */

function trimStr (inStr) {
	//regex explanation:
	//regex is in forward slashes:  //
	// syntax  string = string.replace(/pattern/, 'replace with this');
	//    ^        = beginning of line
	//    (\s+)?   = one or more characters of whitespace, optional
	//    (.*\S)   = any characters, with the last one not being whitespace
	//    (\s+)?   = one or more characters of whitespace, optional
	//    $        = end of line
	//    $2       = what was in the 2nd set of parenthesis


	return inStr.replace(/^(\s*)?(.*\S*)(\s*)?$/, '$2');
}

function reverseStr (inStr) {
	var outStr;
	for (outStr="", i=inStr.length-1;i>-1;i=i-1) {
		outStr += inStr.charAt(i);
	}
	return (outStr);
} /* reverseStr */


function submitFormAJ(form,target)
{
	var err = false;
	var errmes = "Не заполнены обязательные поля";
	for (var i=0; i<form.length; i++)
	{

		var valid = form[i].getAttribute('valid');
		if (valid)
		{
			switch(valid)
			{
				case 'email':
				if (!CheckEmail(form[i]))
				{
					err = true;
					form[i].className = 'alert';
					errmes +='\n Неверный формат email';
				} else {
					form[i].className = 'form';
				}
				break;

				case 'req':
				if (isEmpty(form[i].value))
				{
					form[i].className = 'alert';
					err = true;
				} else {
					form[i].className = 'form';
				}
				break;

				default:
				if (isEmpty(form[i].value))
				{
					form[i].className = 'alert';
					err = true;
				} else {
					form[i].className = 'form';
				}
				break;


			}

		}
	}
	if (err)
	{
		alert(errmes);
		return false;

	}
	//alert('submit form');
	return !HTML_AJAX.formSubmit(form, target)
}

function validateForm(form,nclass)
{
	var err = false;
	if (!nclass) nclass = 'form';
	var errmes = "Не заполнены обязательные поля";


	for (var i=0; i<form.length; i++)
	{

		var valid = form[i].getAttribute('valid');
		if (valid)
		{
			if (valid.indexOf('choice') != -1) {
				if (isEmpty(form[i].value))
				{
					var chelid = valid.substring(7,100);
					if (isEmpty(document.getElementById(chelid).value))
					{
						err = true;
						form[i].className = 'alert';
					} else
					{
						form[i].className = nclass;
					}
				} else
				{
					form[i].className = nclass;
				}

			} else
			{

				switch(valid)
				{
					case 'radio':
					case 'checkboxes':
					var elname = form[i].name;

					var checked=0;
					var form1 = form;
					for (var j=0; j<form1.length; j++)
					{
						if (form1[j].name && (form1[j].name== elname))
						{

							if (form1[j].checked)
							{
								checked +=1;
							}
						}
					}
					if (checked ==0)
					{
						err = true;
						form[i].className = 'alert';
					} else
					{
						form[i].className = '';
					}

					break;

					case 'email':
					if (!CheckEmail(form[i]))
					{
						err = true;
						form[i].className = 'alert';
						errmes +='\n Неверный формат email';
					} else {
						form[i].className = nclass;
					}
					break;

					case 'req':
					if (isEmpty(form[i].value))
					{
						form[i].className = 'alert';
						err = true;
					} else {
						form[i].className = nclass;
					}
					break;

					case 'passwd_compare':

					if (!isEmpty(form[i].value))
					{


						if (form[i].id.indexOf('_1') == -1)
						{

							if (form[i].value != document.getElementById(form[i].id+'_1').value)
							{
								form[i].className = 'alert';
								document.getElementById(form[i].id+'_1').className = 'alert';
								err = true;
								errmes +='\nВведенные пароли не соответсвуют';

							} else
							{
								form[i].className = nclass;
								document.getElementById(form[i].id+'_1').className = 'alert';
							}

						}
					}

					break;


					case 'int':
					if (isEmpty(form[i].value))
					{
						form[i].className = 'alert';
						err = true;
					} else {
						form[i].value = makeInt(form[i].value);
						form[i].className = nclass;
					}
					break;

					case 'select':

					if (form[i].value==0)
					{
						form[i].className = 'alert';
						form[i].style.color = 'red';
						err = true;
					} else {
						form[i].className = nclass;
						if (form[i].style.color == 'red')
						{
							form[i].style.color = 'black';
						}
					}
					break;

					case 'date':
					//later
					if (form[i].value=='')
					{
						form[i].className = 'alert';
						err = true;
					} else {
						form[i].className = nclass;
					}
					break;

					case 'decimal':
					if (isEmpty(form[i].value))
					{
						form[i].className = 'alert';
						err = true;
					} else {
						form[i].value = makeDecimal(form[i].value);
						form[i].className = nclass;
					}
					break;

					default:
					if (isEmpty(form[i].value))
					{
						form[i].className = 'alert';
						err = true;
					} else {
						form[i].className = nclass;
					}
					break;


				}
			}

		}
	}
	if (err)
	{
		alert(errmes);
		return false;

	}
	//alert('submit form');
	return true;
}//

function makeInt(val)
{
	val = parseInt(val);
	if (isNaN(val))
	{
		return 0;
	} else {
		return val;
	}

}//

function makeDecimal(val)
{
	val = parseFloat(val);
	if (isNaN(val))
	{
		return '0.00';
	} else {
		return val.toFixed(2);
	}

}//

function Dump(d,l) {
	if (l == null) l = 1;
	var s = '';
	if (typeof(d) == "object") {
		s += typeof(d) + " {";
		for (var k in d) {
			for (var i=0; i<l; i++) s += "  ";
			s += k+": " + Dump(d[k],l+1);
		}
		for (var i=0; i<l-1; i++) s += "  ";
		s += "}"
	} else {
		s += "" + d + "\n";
	}
	return s;
}

function getRadioGroupValue(targetID, parentElement)
{
	if (parentElement == null) parentElement = document;
	var children = parentElement.getElementsByTagName("input");
	for (var i=0; i<children.length; i++)
	{
		if (children[i].id == targetID && children[i].getAttribute("type") == "radio" && children[i].checked)
		{
			return children[i].getAttribute("value");
		}
	}
	return false;
}

function setRadioGroupValue(targetID, value, parentElement, chk, rev)
{
	if (parentElement == null) parentElement = document;
	var children = parentElement.getElementsByTagName("input");
	for (var i=0; i<children.length; i++)
	{
		if (children[i].id == targetID && children[i].getAttribute("type") == "radio")
		{
			if (children[i].getAttribute('value') == value)
			{
				children[i].checked = chk;
			}
			else
			{
				if (rev) children[i].checked = false;
			}
		}
	}
	return false;
}

function getPageEventCoords(evt) {
	var coords = {left:0, top:0};
	if (evt.pageX) {
		coords.left = evt.pageX;
		coords.top = evt.pageY;
	} else if (evt.clientX) {
		coords.left =
		evt.clientX + document.body.scrollLeft - document.body.clientLeft;
		coords.top =
		evt.clientY + document.body.scrollTop - document.body.clientTop;
		// include html element space, if applicable
		if (document.body.parentElement && document.body.parentElement.clientLeft) {
			var bodParent = document.body.parentElement;
			coords.left += bodParent.scrollLeft - bodParent.clientLeft;
			coords.top += bodParent.scrollTop - bodParent.clientTop;
		}
	}
	return coords;
}

function validateAllFields(form)
{
	var err = false;

	for (var i=0; i<form.length;i++)
	{
		if(form[i].type == 'text' || form[i].type == 'textarea')
		{
			if (isEmpty(form[i].value))
			{
				form[i].className = 'alert';
				err = true;

			} else
			{
				form[i].className = 'form'
			}

		} else if (form[i].type == 'select-one')
		{
			if (form[i].getAttribute('valid'))
			{
				if (form[i].value == 0)
				{
					//form[i].className = 'alert';
					form[i].style.color = 'red';
					err = true;

				} else
				{
					form[i].style.color = 'black';
					//form[i].className = 'form'
				}
			}

		}
	}
	if (err)
	{
		alert('Все поля должны быть заполнены');
		return false;

	} else
	{
		form.submit();
	}

}

var myWindow;
function openCWin(url,w,h) {
    var width = w;
    var height = h;
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
    var windowFeatures = "width=" + width + ",height=" + height + 
        ",dependent=yes,status=no,resizable=yes,left=" + left + ",top=" + top + 
        ",screenX=" + left + ",screenY=" + top;
     if (!myWindow || myWindow.closed) {
        myWindow = window.open(url, "subWind", windowFeatures);
     } else {
     myWindow.close();
     myWindow = window.open(url, "subWind", windowFeatures);
     }
}

