var isMSIE = document.attachEvent != null;
var isMSIE6 = false;
var isGecko = !document.attachEvent && document.addEventListener;

function do_init() {
	var si = el('query');
	if (si) si.onkeyup = as_kpress;
	if (window.init_page) window.init_page();

	$(document).ready(function(){
		if (window.autogeo && window.autogeo == 1) {
			var ccity = $("#ccity");
			if (ccity) {
				ccity.css('background-color', '#cfe0f2');
				ccity.animate({'background-color': '#ffffff'}, isMSIE?1000:2000);
			}
		}
	})	
}

function getY(e) {
	if (!e) {
		return 0;
	}
    else {
      	return e.offsetTop + getY(e.offsetParent);
  	}
}

function getX(e) {
        if (!e) {
		return 0;
        }
        else {
        	return e.offsetLeft + getX(e.offsetParent);
        }
}

function el(id) {
	return document.getElementById(id);
}

function submit_on_enter(e) {
	if (window.event) e = window.event;
	if (e.keyCode == 13) f.submit();
	if (e.keyCode == 27) {
		if ((e.srcElement) && (e.srcElement.tagName == 'INPUT')) e.srcElement.value = '';
		if ((e.target) && (e.target.tagName == 'INPUT')) e.target.value = '';
	}
}
function FocusInput(i) {
	if (i.createTextRange) {
		var u = i.createTextRange();
		u.moveStart("character", 0);
		u.moveEnd("character", i.value.length);
		u.select();	
	}
	else if (i.setSelectionRange) {
		i.setSelectionRange(0,i.value.length);
	}
	i.focus();
}		

function checkRadio(id) {
	el(id).checked = true;
}

function toggleCheckbox(id) {
	var cb = el(id);
	cb.checked = !cb.checked;
}

function as_kpress(e){
    if (window.event) 
        e = window.event;
    var i = el('query');
    switch (e.keyCode) {
        case 27:
            i.value = '';
            
        default:
            var query = '' + i.value;
            if (query.search(/^[0-9\s\+]+$/) >= 0) {
                if (query.search(/\+/) >= 0) {
                    query = query.replace(/\+/, ' ');
                    i.value = query;
                }
            }
            break;
    }
}

function clearSearchField(i){
	if (i.value == 'поиск по каталогу') {
		i.value = '';
		i.style.color = 'black';
	}
}

function submitSearch() {
	var f = el('sf');
	var i = el('query');
	if (f && i && (i.value.length > 0) && (i.value != 'поиск по каталогу')) f.submit();
}

function drawPLines() {
	var cnvs = document.getElementsByTagName('CANVAS');
	for (var i=0; i<cnvs.length; i++) {
		switch(cnvs[i].className) {
			case 'dot':
				drawPDot(cnvs[i]);
				break;
			default:
				drawPLine(cnvs[i]);
		}
	}
}

function drawPDot(c) {
	if (c.getContext) {  
		var ctx = c.getContext("2d");  
		var cw = c.clientWidth;
		var dot_r = cw/2;
		ctx.lineWidth = 0.1;
		ctx.strokeStyle = (c.style.color.length > 0)?c.style.color:"#999999";
		ctx.fillStyle = (c.style.color.length > 0)?c.style.color:"#999999";
		ctx.beginPath();		
		ctx.arc(dot_r, dot_r, dot_r, 0, Math.PI*2, true);
		ctx.fill();
		ctx.stroke();
	}
}
		
function drawPLine(c) {
	if (c.getContext) {  
		var ctx = c.getContext("2d");  
		var cw = c.clientWidth;
		var ch = c.clientHeight;
		ctx.lineWidth = 1;
		ctx.lineCap = "round";
		ctx.strokeStyle = (c.style.color.length > 0)?c.style.color:"#999999";
				
		switch (c.className) {
			case "tlbr":
				ctx.moveTo(0, 0);
				ctx.lineTo(cw, ch);   
				break;
			case "tb":
				ctx.moveTo(0.5,0);
				ctx.lineTo(0.5, ch);
				break;
			case "lr":
				ctx.moveTo(0,0.5);
				ctx.lineTo(cw, 0.5);
				break;
			default:	
				ctx.moveTo(0, ch);
				ctx.lineTo(cw, 0);   
		}
		ctx.stroke();
	}  
}

function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}
	return x1 + x2;
}		

function setCartMode(m) {
	el('cart_mode').value = m;
	el('togf').submit();
}

function showCitySelect() {
	var ofs = $("#loc_div").offset();
	$("#city_select").modal({
		opacity: 40,
		overlayCss: {backgroundColor: "#000"},
		position: [ofs.top, ofs.left - 20] 
	});
}

function setCity(i_cityid) {
	el('cityid').value = i_cityid;
	el('togcity').submit();
}

function wmMap(mblock, cx, cy, cs, wmx, wmy) {
	var map = new YMaps.Map(el(mblock));
	map.setCenter(new YMaps.GeoPoint(cx, cy), cs);
	var s = new YMaps.Style();
	s.iconStyle = new YMaps.IconStyle();
	s.iconStyle.href = "/img/wm_pointer.png";
	s.iconStyle.size = new YMaps.Point(16, 44);
	s.iconStyle.offset = new YMaps.Point(-8, -44);
	s.iconStyle.shadow = new YMaps.IconShadowStyle();
	s.iconStyle.shadow.href = "/img/wm_pointer_s.png";
	s.iconStyle.shadow.size = new YMaps.Point(22, 42);
	s.iconStyle.shadow.offset = new YMaps.Point(-4, -42);			
	var placemark = new YMaps.Placemark(new YMaps.GeoPoint(wmx,wmy), {style: s, hasBalloon : false });
	map.addOverlay(placemark); 
}

function SampleBalloonLayout() {
    this.element = YMaps.jQuery(
        "<div class=\"wm-balloon-layout\"><div class=\"content\"></div><div class=\"close\"></div><div class=\"tail\"></div></div>");
 
    this.close = this.element.find(".close");
    this.content = this.element.find(".content");
 
    // Отключает кнопку закрытия балуна
    this.disableClose = function(){
        this.close.unbind("click").css("display", "none");
    };
                
    // Включает кнопку закрытия балуна
    this.enableClose = function(callback){
        this.close.bind("click", callback).css("display", "");
        return false;
    };
 
    // Добавляет макет на страницу
    this.onAddToParent = function (parentNode) {
        YMaps.jQuery(parentNode).append(this.element);
        this.update();
    };
 
    // Удаляет макет со страницы
    this.onRemoveFromParent = function () {
        this.element.remove();
    };
 
    // Устанавливает содержимое балуна
    this.setContent = function (content) {
    	this.content.html("");
        content.onAddToParent(this.content[0]);
    };
                
    // Обновляет балун
    this.update = function() {
        this.element.css("margin-top", "-" + (this.content.height() + 52) + "px");
    };
};

function wmMapArray(mblock, cx, cy, cs, pmks) {
	var map_cont = el(mblock);
	map_cont.marks = [];
	var map = new YMaps.Map(map_cont);
	map.setCenter(new YMaps.GeoPoint(cx, cy), cs);
	
	map.addControl(new YMaps.TypeControl());
	map.addControl(new YMaps.Zoom());
	map.addControl(new YMaps.ScaleLine());
	
	var s = new YMaps.Style();
	s.iconStyle = new YMaps.IconStyle();
	s.iconStyle.href = "/img/wm_pointer.png";
	s.iconStyle.size = new YMaps.Point(16, 44);
	s.iconStyle.offset = new YMaps.Point(-8, -44);
	s.iconStyle.shadow = new YMaps.IconShadowStyle();
	s.iconStyle.shadow.href = "/img/wm_pointer_s.png";
	s.iconStyle.shadow.size = new YMaps.Point(22, 42);
	s.iconStyle.shadow.offset = new YMaps.Point(-4, -42);

	var sampleBalloonTemplate = new YMaps.LayoutTemplate(SampleBalloonLayout);
	s.balloonStyle = {template: sampleBalloonTemplate};
	
	var template = new YMaps.Template('<div><nobr><img src="/img/rali.gif" class="rali" align="bottom" alt=""><a href="/$[metaDataProperty.href]/">$[name]</a></nobr></div>');
	s.balloonContentStyle = new YMaps.BalloonContentStyle(template);
	
	map_cont.mark_style = s;

	var s_l = new YMaps.Style();
	s_l.iconStyle = new YMaps.IconStyle();
	s_l.iconStyle.href = "/img/wm_pointer_lite.png";
	s_l.iconStyle.size = new YMaps.Point(16, 44);
	s_l.iconStyle.offset = new YMaps.Point(-8, -44);
	s_l.iconStyle.shadow = new YMaps.IconShadowStyle();
	s_l.iconStyle.shadow.href = "/img/wm_pointer_s_lite.png";
	s_l.iconStyle.shadow.size = new YMaps.Point(22, 42);
	s_l.iconStyle.shadow.offset = new YMaps.Point(-4, -42);

	s_l.balloonStyle = {template: sampleBalloonTemplate};
	s_l.balloonContentStyle = new YMaps.BalloonContentStyle(template);
	
	map_cont.mark_style_lite = s_l;
	
	
	for (var i=0; i<pmks.length; i++) {
		var c_placemark = new YMaps.Placemark(new YMaps.GeoPoint(pmks[i][0],pmks[i][1]), {style: map_cont.mark_style});
		c_placemark.name = pmks[i][2];
		c_placemark.description = "";
		c_placemark.metaDataProperty.href = pmks[i][3];
		c_placemark.metaDataProperty.branch_type = pmks[i][5];
		c_placemark.metaDataProperty.company_id = pmks[i][4];
		map_cont.marks.push(c_placemark);
		map.addOverlay(c_placemark);
	}
}

function updatePlacemarks(mblock, type_toks, co_toks) {
	var map_cont = el(mblock);
	var has_cond = ((type_toks.length > 0) || (co_toks.length > 0));
	
	for (var i=0; i<map_cont.marks.length; i++) {
		var is_shaded = false;
		
		if (has_cond) {
			var type_satisfy = false;
			var co_satisfy = false;
			
			if (type_toks.length > 0) {
				var j=0;
				while (!type_satisfy && (j<type_toks.length)) {
					type_satisfy = (type_toks[j] == map_cont.marks[i].metaDataProperty.branch_type);
					j++;
				}
			}
			else type_satisfy = true;

			if (co_toks.length > 0) {
				var j=0;
				while (!co_satisfy && (j<co_toks.length)) {
					co_satisfy = (co_toks[j] == map_cont.marks[i].metaDataProperty.company_id);
					j++;
				}
			}
			else co_satisfy = true;
			
			is_shaded = !(type_satisfy && co_satisfy);
		}
		
		map_cont.marks[i].setOptions({style: is_shaded?map_cont.mark_style_lite:map_cont.mark_style});
		map_cont.marks[i].update();
	}
}
