var site_url = 'http://www.promtrest.ru/';

var tDOM = (document.getElementById) ? true:false;
var tIE = (document.all) ? true:false;
var tIE4 = tIE && !tDOM;
var tNS = tDOM && !tIE;
var tNS4 = (document.layers) ? true:false;
var tOPER = (window.opera) ? true:false;

function check_delivery_form ()
{
	var f = document.order_form;

	for(var i = 0; i < f.order_delivery.length; i++)
	{
		if (f.order_delivery[i].checked && f.order_delivery[i].value == '4')
		{
			if (f.delivery_price_4.value == '' || parseInt(f.delivery_price_4.value) <= 0)
			{
				open_win('cpcr', site_url+'cart/cpcr/');
				return false;
			}
		}
	}

	return true;
}

function update_cpcr_price (price, descr)
{
	if (window.opener)
	{
		if (window.opener.document.order_form)
			window.opener.document.order_form.delivery_price_4.value = price;
		write_toobj(
			get_objbyid(window.opener.document, 'delivery_price_4'),
			(price!='') ? (' - '+price + ' руб') : ''
			);
		write_toobj(
			get_objbyid(window.opener.document, 'delivery_price_descr_4'),
			(descr!='') ? ('<p><em>'+descr+'</em></p>') : ''
			);
	}
}

function open_win (name, url, w, h)
{
	var t=0, l=0;
	var mw = screen.availWidth;
	var mh = screen.availHeight;
	if ( ! w) w = 500;
	if ( ! h) h = 400;
	if (mw > 0 && mh > 0)
	{
		l = (mw - w) * .5;
		t = (mh - h) * .5;
	}
	var win = window.open(url ,name, "width="+w+",height="+h+"," +"left="+l+",top="+t+"," + "directories=no,location=yes,menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=yes,titlebar=no");
	if (win)
	{
		win.focus();
		if (win.opener==null) win.opener=window;
	}
}

function get_objbyid (doc, id)
{
	var obj;
	if (!doc) doc = document;
	if (tNS4) obj = doc.layers[id];
	else if (tDOM) obj = doc.getElementById(id);
	else if (tIE) obj = doc.document.all[id];
	return obj;
}

function write_toobj (obj, html)
{
	if (!obj) return;
	if (tNS4) {
		obj.document.open();
		obj.document.open();
		obj.document.write(html);
		obj.document.close();
	}
	else if (tDOM || tIE) obj.innerHTML = html;
	return;
}

function show_block (id)
{
	var obj = get_objbyid(null, id);
	if (obj)
	{
		obj.style.display = (obj.style.display=='block') ? 'none':'block';
	}
}

function add_to_compare (id)
{
	document.compare_form.entry_id.value = id;
	document.compare_form.submit();
}

function del_from_compare (id)
{
	document.del_compare_form.entry_id.value = id;
	document.del_compare_form.submit();
}

function open_compare_win (name, url)
{
	var mw = screen.availWidth - 50;
	var mh = screen.availHeight - 50;

	w = 800;
	h = 600;

	if (w > mw) w = mw;
	if (h > mh) h = mh;

	return open_win (name, url, w, h);
}

function opener_url (url)
{
	if (window.opener)
	{
		window.opener.document.location.href = url;
		window.opener.focus();
		return true;
	}

	return false;
}

function change_more_icon (state)
{
	var obj = get_objbyid(null, 'image_more_icon');
	if (obj)
	{
		obj.src = '/i/' + ( state ? 'lupa2.gif' : 'lupa1.gif' );
	}
}

var Addr_parts = {
	'p1' : ['Улица'],
	'p2' : ['Дом'],
	'p3' : ['Корпус'],
	'p4' : ['Подъезд'],
	'p5' : ['Домофон'],
	'p6' : ['Этаж'],
	'p7' : ['Кв./Офис', '(?:Кв\\.\\/Офис|Квартира|Офис)']
	};

function save_ext_address (id)
{
	if ( ! tDOM) return;

	var elem = document.getElementById(id);
	var f = elem;

	while (f && f.tagName != 'FORM') { f = f.parentNode; }
	if ( ! f) return;

	var res_str = '';

	for(var k in Addr_parts)
	{
		if ( ! f.elements[elem.name + '_' + k])
		{
			return;
		}
		if (/\S/.test(f.elements[elem.name + '_' + k].value))
		{
			if (k != 'p1')
				res_str += Addr_parts[k][0] + ": ";
			res_str += f.elements[elem.name + '_' + k].value + "; ";
		}
	}

	elem.value = res_str;

	return true;
}

function create_ext_address (id)
{
	if ( ! tDOM) return;

	var elem = document.getElementById(id);
	if ( ! elem) return;

	var addr_name = elem.name;
	var addr_value = elem.value;
	var parent = elem.parentNode;

	var newinput = document.createElement("input");
	newinput.setAttribute("id", id);
	newinput.setAttribute("type","hidden");
	newinput.setAttribute("name", addr_name);
	newinput.setAttribute("value", addr_value);
	
	var newdiv = document.createElement("div");

	
	var val = {};

	for(var k in Addr_parts)
	{
		var re = new RegExp(
			(Addr_parts[k][1] ? Addr_parts[k][1] : Addr_parts[k][0]) + "\s*:\s*(.+?)\s*(?:;|$)",
			"im");
		var res = re.exec(addr_value);
		if (res && res.length>0)
		{
			addr_value = addr_value.replace(re, '');
			val[k] = res[1].replace(/(^\s+|\s+$)/, '');
		}
		else val[k] = '';
	}

	addr_value = addr_value.replace(/^[\s;]+/, '');
	addr_value = addr_value.replace(/[\s;]+$/, '');

	if (addr_value != '')
	{
		val['p1'] += ( val['p1'] != '' ? ' ' : '' ) + addr_value;
	}

	newdiv.innerHTML = '<table cellspacing="0" class="tab_address">' +
		'<tr><th>улица:</th><td colspan="5">' +
		'<input type="text" name="' + addr_name + '_p1" value="' + escape_html(val['p1']) + '" size="25" class="input" style="width: 100%;" />' +
		'</td></tr><tr><th>дом:</th><td>' +
		'<input type="text" name="' + addr_name + '_p2" value="' + escape_html(val['p2']) + '" size="4" class="input" style="width: 40px;" />' +
		'</td><th>корпус:</th><td>' +
		'<input type="text" name="' + addr_name + '_p3" value="' + escape_html(val['p3']) + '" size="4" class="input" style="width: 40px;" />' +
		'</td><th>подъезд:</th><td>' +
		'<input type="text" name="' + addr_name + '_p4" value="' + escape_html(val['p4']) + '" size="4" class="input" style="width: 40px;" />' +
		'</td></tr><tr><th>домофон:</th><td>' +
		'<input type="text" name="' + addr_name + '_p5" value="' + escape_html(val['p5']) + '" size="4" class="input" style="width: 40px;" />' +
		'</td><th>этаж:</th><td>' +
		'<input type="text" name="' + addr_name + '_p6" value="' + escape_html(val['p6']) + '" size="4" class="input" style="width: 40px;" />' +
		'</td><th>кв./офис:</th><td>' +
		'<input type="text" name="' + addr_name + '_p7" value="' + escape_html(val['p7']) + '" size="4" class="input" style="width: 40px;" />' +
		'</td></tr></table>';


	parent.removeChild(elem);
	parent.appendChild(newinput);
	parent.appendChild(newdiv);

	return true;
}

function escape_html(str)
{
	str = str.replace(/&/g, '&amp;');
	str = str.replace(/"/g, '&quot;');
	str = str.replace(/>/g, '&gt;');
	str = str.replace(/</g, '&lt;');
	
	return str;
}


/**
 * This array is used to remember mark status of rows in browse mode
 */
var marked_row = new Array;

/**
 * enables highlight and marking of rows in data tables
 *
 */
function markRowsInit() {
    // for every table row ...
    var rows = document.getElementsByTagName('tr');
    for ( var i = 0; i < rows.length; i++ ) {
        // ... with the class 'even' ...
        if ('even' != rows[i].className.substr(0,4) ) {
            continue;
        }
        // ... add event listeners ...
        // ... to highlight the row on mouseover ...
        if ( navigator.appName == 'Microsoft Internet Explorer' ) {
            // but only for IE, other browsers are handled by :hover in css
            rows[i].onmouseover = function() {
                this.className += ' hover';
            }
            rows[i].onmouseout = function() {
                this.className = this.className.replace( ' hover', '' );
            }
        }
        // Do not set click events if not wanted
        if (rows[i].className.search(/noclick/) != -1) {
            continue;
        }
        // ... and to mark the row on click ...
        rows[i].onmousedown = function() {
            var unique_id;
            var checkbox;

            checkbox = this.getElementsByTagName( 'input' )[0];
            if ( checkbox && checkbox.type == 'checkbox' ) {
                unique_id = checkbox.name + checkbox.value;
            } else if ( this.id.length > 0 ) {
                unique_id = this.id;
            } else {
                return;
            }

            if ( typeof(marked_row[unique_id]) == 'undefined' || !marked_row[unique_id] ) {
                marked_row[unique_id] = true;
            } else {
                marked_row[unique_id] = false;
            }

            if ( marked_row[unique_id] ) {
                this.className += ' marked';
            } else {
                this.className = this.className.replace(' marked', '');
            }

            if ( checkbox && checkbox.disabled == false ) {
                checkbox.checked = marked_row[unique_id];
            }
        }

        // ... and disable label ...
        var labeltag = rows[i].getElementsByTagName('label')[0];
        if ( labeltag ) {
            labeltag.onclick = function() {
                return false;
            }
        }
        // .. and checkbox clicks
        var checkbox = rows[i].getElementsByTagName('input')[0];
        if ( checkbox ) {
            checkbox.onclick = function() {
                // opera does not recognize return false;
                this.checked = ! this.checked;
            }
        }
    }
}
window.onload=markRowsInit;

/**
 * marks all rows and selects its first checkbox inside the given element
 * the given element is usaly a table or a div containing the table or tables
 *
 * @param    container    DOM element
 */
function markAllRows( container_id ) {
    var rows = document.getElementById(container_id).getElementsByTagName('tr');
    var unique_id;
    var checkbox;

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

        checkbox = rows[i].getElementsByTagName( 'input' )[0];

        if ( checkbox && checkbox.type == 'checkbox' ) {
            unique_id = checkbox.name + checkbox.value;
            if ( checkbox.disabled == false ) {
                checkbox.checked = true;
                if ( typeof(marked_row[unique_id]) == 'undefined' || !marked_row[unique_id] ) {
                    rows[i].className += ' marked';
                    marked_row[unique_id] = true;
                }
            }
        }
    }

    return true;
}

/**
 * marks all rows and selects its first checkbox inside the given element
 * the given element is usaly a table or a div containing the table or tables
 *
 * @param    container    DOM element
 */
function unMarkAllRows( container_id ) {
    var rows = document.getElementById(container_id).getElementsByTagName('tr');
    var unique_id;
    var checkbox;

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

        checkbox = rows[i].getElementsByTagName( 'input' )[0];

        if ( checkbox && checkbox.type == 'checkbox' ) {
            unique_id = checkbox.name + checkbox.value;
            checkbox.checked = false;
            rows[i].className = rows[i].className.replace(' marked', '');
            marked_row[unique_id] = false;
        }
    }

    return true;
}

