Socket = function(){
    this.Server         = false;
    this.Client         = false;
    this.ClientNotSend  = true;
    // запрос висящий
    this.OnLine         = false;

    this.SetServer = function(ID){
        this.Server = ID.server;
    }

    this.SetClient = function(ID){
        this.Client = ID.client;
    }

    // коннект к синхронизации
	this.Connect = function(){
        if (Socket.ClientNotSend && Socket.Client){
            Socket.Send('client=' + Socket.Client + '&SetClient[client]=' + Socket.Server);
            Socket.ClientNotSend = false;
        }
        
        Socket.OnLine = $.ajax({
                                url:      '/ajax/synchro/Connect.php',
                                type:     'post',
                                dataType: 'json',
                                data:     'server=' + Socket.Server,
                                success:  Socket.Success,
                                complete: Socket.Complete
                              });
        return true;
	}

    // установить полученный идентификатор
	this.Complete = function(xhr){
        /*if (xhr.status == 404) {
            Socket.Disconnect();
        } else*/ if (xhr.status == 200) Socket.Connect();
        else setTimeout(Socket.Connect, 5000);
	}

    /*
     * Эта функция обрабатывает приходящие с сервера действия и выполняет их.
     */
    this.Success = function(data) {
        if (data.error == undefined){
            var i = 0;
            if (typeof data.synchro == 'object') {
                for (i = 0; i < data.synchro.length; i++) {
                    if (typeof Synchronizer[data.synchro[i].action] == 'function') {
                        Synchronizer[data.synchro[i].action](data.synchro[i].params);
                    }
                }
            }
        } else {
            alert(data.error);
            Socket.Disconnect();
        }
    }

    /*
     * Отсоединение от сервера.
     */
    this.Disconnect = function(){
        if (Socket.OnLine && Socket.Server) {
            $.ajax({
                    url: '/ajax/synchro/Connect.php',
                    type: 'post',
                    dataType: 'json',
                    data: 'action=Disconnect&server=' + Socket.Server
                    });
            Socket.OnLine.abort();
        }
    }

    /*
     * Отправка данных на сервер.
     * сюда данные нужна в виде имя функции[]=значение для нее
     */
    this.Send = function(Data){
        if (Socket.Client){
            $.ajax({
                url:        '/ajax/synchro/Connect.php',
                type:       'post',
                dataType:   'json',
                data:       'client=' + Socket.Client + '&' + Data
            });
        }
    }
}

var Socket = new Socket();

// получение координат курсора
Cursorer = function(){
	this.GetCoords = function(e){
		var x = 0, y = 0;
		if (e.pageX || e.pageY){
			x = e.pageX;
			y = e.pageY;
		} else if (e.clientX || e.clientY){
			x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
			y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
		}
		return {"x": x, "y": y};
	}
}

var Cursorer = new Cursorer();

Calcer = function(){
    this.Stop  = false;
	this.Freeq = Array();
	this.Calculate = function(){
        if (this.Stop) return false;
		var iLength	 = parseInt($("#LengthCompany").val());
		var iCars    = parseInt(Router.Monitors);
		var aFreeq	 = Array(), aLengths = Array(), i = 0;
		$('#' + FullRC.TagID.Ads + ' select.freeq').each(function(){ aFreeq.push(parseInt($(this).val())); });
		$('#' + FullRC.TagID.Ads + ' select.length').each(function(){ aLengths.push(parseInt($(this).val())); });
		this.Freeq = aFreeq;
		
		if (iCars > 0 && aFreeq.length > 0){
			this.InsertResult(this.GetMoney(iLength, iCars, aLengths, aFreeq));
			AjaxCalculator.Calculation({ iAllCars: iCars, iCarsWithComplexes: iCars, A: 0, B: 0, C: 0, D: iCars });
		} else Synchronizer.SendDataAfterCalculate();
	}
	
	this.InsertResult = function(oResults){
		var iAverageExposures = 0;
		for (var i = 0; i < this.Freeq.length; i++) iAverageExposures += Math.round(60 / this.Freeq[i] * 13 * 6);
		$("#Money").html(this.FormatMoney(oResults.iMoney) + ' руб.');
		$("#NDS").html(this.FormatMoney(oResults.iNDS) + ' руб.');
		$("#Exposures").html(this.FormatMoney(oResults.iExposures));
		$("#AverageExposures").html(this.FormatMoney(iAverageExposures));
		$("#CPT").html(this.FormatMoney(oResults.iCPT) + ' у. е.');
		$("#GRP").html(this.FormatMoney(oResults.iGRP));
		$("#CPP").html(this.FormatMoney(oResults.iCPP) + ' у. е.');
        Synchronizer.SendDataAfterCalculate();
	}
	
	this.FormatMoney = function(iMoney){
		iMoney 	  += '';
		var sMoney = '';
		for (var i = iMoney.length - 1, j = 1; i >= 0; i--, j++){
			sMoney = iMoney.charAt(i) + sMoney;
			if (iMoney.charAt(i) == '.') j = 0;
			if (j == 3){
				j = 0;
				sMoney = ' ' + sMoney;
			}
		}
		return sMoney;
	}
	
	this.GetMoney = function(iLength, iCars, aLengths, aFreeq){
		var iExposures = 0, iMoney = 0;
		iLength = eval(iLength);
		
		for (iID in aFreeq){
			if(isNaN(iID)){
				continue;
			}
            iID          = parseInt(iID);

			iMoney 		+= Math.round(cost_one_sec * 60 * iCars * aLengths[iID] * iLength / (aFreeq[iID] * block_length) * 10000) / 10000;
			iExposures 	+= Math.round(people_per_day_average * 7 * Duration_of_trip * iLength * iCars / (aFreeq[iID] * block_length));
		}
		
		return {
			  "iMoney": 		(Math.round(iMoney))
			, "iNDS":			(Math.round((iMoney / (100 + 18) * 18 * 100) / 100))
			, "iExposures":		iExposures
			, "iCPT":			(Math.round(iMoney * 1000 / iExposures * 100 / rate_of_exchange) / 100)
			, "iGRP":			(Math.round(iExposures * 100 / people_general_sum * 100) / 100)
			, "iCPP":			(Math.round(iMoney * people_general_sum / iExposures / 100 * 100 / rate_of_exchange) / 100)
		};
	}
}

var Calcer = new Calcer();

Selectors = function(){
    this.List = {};
    
    this.Set = function(sID, sSelctor){
        this.List[sID] = $(sSelctor);
    }

    this.Get = function(sID){
        if (this.List[sID] == undefined) this.Set(sID, '#' + sID);
        return this.List[sID];
    }
}

var Selectors = new Selectors();// подсказщик
Helper = function(){
	// сообщения подсказок
	// вид: { ид тэга куда лепить: { text: текст подсказки, view: true/false показывать/нет } }
	this.Helpers  = {};
	
	// добавить подсказку
	// вход: 	sTagID 	- ид тэга где будет подсказка
	//			sText	- текст подсказки
	this.AddHelper = function(sTagID, sText){
		this.Helpers[sTagID] = { text: sText, view: true };
	}
	
	// показать подсказку
	// вход: 	sTagID 	- ид тэга где будет подсказка
	this.OnHelper = function(oTag){
		if (this.Helpers[oTag.id] == undefined || !this.Helpers[oTag.id].view) return false;
		jQuery('#Helper').html(this.Helpers[oTag.id].text).css('display', 'inline');
	}
	
	// скрыть подсказку
	this.OffHelper = function(){
		jQuery('#Helper').css('display', 'none');
	}
	
	// запретить показ подсказки
	this.Prohibit = function(sTagID){
		if (this.Helpers[sTagID] == undefined) return false;
		this.Helpers[sTagID].view = false;
	}
	
	// разрешить показ подсказки
	this.Resolve = function(sTagID){
		if (this.Helpers[sTagID] == undefined) return false;
		this.Helpers[sTagID].view = true;
	}
	
	// переместить подсказку
	this.MoveHelper = function(event){
		var aCoord = Cursorer.GetCoords(event);
		jQuery('#Helper').css('top', aCoord.y + 30).css('left', aCoord.x + 30);
	}
	
	// загрузка подсказщика
	this.Load = function(){
		jQuery('body').append(this.GetHelperWindow());
		jQuery('.Helper').mouseout(function(){ eval('Helper.OffHelper();'); }).mousemove(function(e){ eval('Helper.MoveHelper(e); '); }).mouseover(function(){ eval('Helper.OnHelper(this);'); });
	}
	
	// получить окно для подсказок
	this.GetHelperWindow = function(){
		return '<div id="Helper" class="HelperTag fs10"></div>';
	}
}

var Helper = new Helper();

// класс - мигалка для кнопок
Blinker = function(){
	// содержит данные о мигалках
	// вид: { ид тэга: { 
	//					  action: true/false 	- включена/выключена мигалка
	//					, thema:  'main'		- цветовая схема мигалки
	//					}
	//		 }
	this.Blinks = {};
	// цветовые решения/темы
	// вид:	main: { 									- название
	//				  background: { 					- цвета фонов
	//								  easy: '#FFFFFF'	- спокойный
	//								, flash: '#000000' 	- вспышка
	//							 }
	//				, color: { 							- цвета шрифта
	//							  easy: '#000000'		- спокойный
	//							, flash: '#FFFFFF' 		- вспышка
	//						  }
	//				, iTime: 500 						- время (милисекунды) вспышек
	//				}
	this.Thems  = { 
					main: { background: { easy: '#FFFFFF', flash: '#000000' }, color: { easy: '#000000', flash: '#FFFFFF' }, time: 500 }
					};
					
	// добавляет тему. заменяет если существует
	// вход: 	sName		- название схемы
	//			sEasyBack	- цвет фона спокойного
	//			sEasyColor	- цвет шрита спокойного
	//			sFlashBack	- цвет фона вспышки
	//			sFlashColor	- цвет шрифта вспышки
	//			iTime		- время вспышек(милисекуны)
	this.AddThema = function(sName, sEasyBack, sEasyColor, sFlashBack, sFlashColor, iTime){
		this.Thems[sName] = { background: { easy: sEasyBack, flash: sFlashBack }, color: { easy: sEasyColor, flash: sFlashColor }, time: iTime };
	}
	
	// остановить мигалку для этого тэга
	this.StopBlink = function(sTag){
		if (this.Blinks[sTag] == undefined) this.AddBlinker(sTag, 'main');
		this.Blinks[sTag].action = false;
		jQuery('#' + sTag).css('background-color', this.Thems[this.Blinks[sTag].thema].background.easy).css('color', this.Thems[this.Blinks[sTag].thema].color.easy);
	}
	
	// добавить мигалку
	this.AddBlinker = function(sTag, sThema){
		this.Blinks[sTag] = { action: false, thema: sThema };
	}
	
	// включить мигалку для этого тэга
	this.Blink = function(sTag){
		if (this.Blinks[sTag] == undefined) this.AddBlinker(sTag, 'main');
		if (this.Blinks[sTag].action) return false;
		this.Blinks[sTag].action = true;
		this.Action(sTag, true);
	}
	
	// сама мигалка
	this.Action = function(sTag, bFlag){
		if (!this.Blinks[sTag].action) return false;
		if (bFlag){
			jQuery('#' + sTag).css('background-color', this.Thems[this.Blinks[sTag].thema].background.flash).css('color', this.Thems[this.Blinks[sTag].thema].color.flash);
		} else {
			jQuery('#' + sTag).css('background-color', this.Thems[this.Blinks[sTag].thema].background.easy).css('color', this.Thems[this.Blinks[sTag].thema].color.easy);
		}
		bFlag = (bFlag) ? false : true;
		setTimeout('Blinker.Action("' + sTag + '", ' + bFlag + ')', this.Thems[this.Blinks[sTag].thema].time);
	}
}

var Blinker = new Blinker();

Maper = function(){
	// объект карты
	this.Map			= null;
	// объект для поиска по адресам
	this.GeoCoder 		= null;
	// количество областей на карте
	this.PolyCount 		= 0;
	// идент тэга для загрузки карты
	this.Tag4Map		= 'map';
	// массив точек
	this.Markers 		= Array();
	// массив зон
	this.PolyZone 		= Array();
	// что то неизведанное... пока
	this.PolyPoints 	= Array();
	// цвет рамки зоны
	this.ZoneBoardColor	= "#3355FF";
	// цвет заливки
	this.ZoneFillColor 	= "#335599";
	// массив линий на карте
	this.LinesOnMap		= Array();
	// вешать функцию на клик по линии
	this.CkickFunction  = true;
	
	// Стиль кнопок на карте
	this.ButtonStyle 	= {
							  Label: function(button){
									button.style.color 			 = "#000000";
									button.style.backgroundColor = "#FFFFFF";
									button.style.font 			 = "small Arial";
									button.style.fontWeight 	 = "bold"
									button.style.fontSize		 = "10px";
									button.style.border			 = "1px solid #000000";
									button.style.padding		 = "1px";
									button.style.marginBottom	 = "3px";
									button.style.textAlign		 = "center";
									button.style.width			 = "112px";
									button.style.height			 = "30px";
								}
							, Button: function(button){
									button.style.color 			 = "#000000";
									button.style.backgroundColor = "#FFFFFF";
									button.style.font 			 = "small Arial";
									button.style.fontWeight 	 = "bold"
									button.style.fontSize		 = "10px";
									button.style.border			 = "1px solid #000000";
									button.style.padding		 = "1px";
									button.style.marginBottom	 = "3px";
									button.style.textAlign		 = "center";
									button.style.width			 = "56px";
									button.style.height			 = "13px";
									button.style.cursor			 = "pointer";
								}
							, Input: function(button){
									button.style.color 			 = "#000000";
									button.style.backgroundColor = "#FFFFFF";
									button.style.font 			 = "small Arial";
									button.style.fontSize		 = "10px";
									button.style.border			 = "1px solid #000000";
									button.style.padding		 = "1px";
									button.style.marginBottom	 = "3px";
									button.style.width			 = "100px";
									button.style.height			 = "13px";
								}
							, DefaultBackgroundColor: '#FFFFFF'
							, HoverBackgroundColor: '#000000'
							};
	
	this.markerslat 	= Array();
	this.markerslng 	= Array();
	this.numvis 		= 0;
	this.numvis2 		= 0;
	this.numvis3 		= 0;
	
	this.polylines 		= Array();
	this.polylines2 	= Array();
	this.polylines3 	= Array();
	// идент выбранного мааршрута
	this.iRoutID		= 0;
	
	// учстановка центра карты
	this.SetCenter = function(){
		this.Map.setCenter(new GLatLng(55.75223581897627, 37.6226806640625), 10);
	}
	
	// загрузка карты
	this.Load = function(){
		// загрузка самой карты
		this.Map = new GMap2(document.getElementById(this.Tag4Map), { draggableCursor: 'auto', draggingCursor: 'move' });
		// центр карты
		this.Map.setCenter(new GLatLng(55.75223581897627, 37.6226806640625), 10);
		// слева маштабирование
		var Hierarchy = new GHierarchicalMapTypeControl();
		Hierarchy.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", true);
		this.Map.addControl(new GSmallMapControl());
		this.Map.disableDoubleClickZoom();
		// загрузка объекта для поиска по адресам
		this.GeoCoder = new GClientGeocoder();
	}
	
	// вешаем на клик функцию
	this.AddClickOnMapFunction = function(sFunc){
		GEvent.addListener(this.Map, "click", sFunc );
	}
	
	// Создание функции лэйбла на карте
	this.CreateLabel = function(oSettings, oObj4Style){
		eval('this.' + oSettings.Name + ' = function(){ }');
		eval('this.' + oSettings.Name + '.prototype = new GControl();');
		eval('this.' + oSettings.Name + '.prototype.initialize = function(map){ var container = document.createElement("div"); container.id  = "' + oSettings.TagID + '"; oObj4Style.Label(container); container.appendChild(document.createTextNode("' + oSettings.Title + '")); map.getContainer().appendChild(container); return container; }');
		eval('this.' + oSettings.Name + '.prototype.getDefaultPosition = function(){ return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(' + oSettings.PosX + ', ' + oSettings.PosY + ')); }');
	}
	
	// Создание функции кнопки на карте
	this.CreateButton = function(oSettings, oObj4Style){
		eval('this.' + oSettings.Name + ' = function(){ }');
		eval('this.' + oSettings.Name + '.prototype = new GControl();');
		eval('this.' + oSettings.Name + '.prototype.initialize = function(map){ var container = document.createElement("div"); container.id  = "' + oSettings.TagID + '"; oObj4Style.Button(container); container.appendChild(document.createTextNode("' + oSettings.Title + '")); GEvent.addDomListener(container, "click", function() { ' + oSettings.ClickFunc + '; }); GEvent.addDomListener(container, "mouseover", function() { this.style.backgroundColor = "' + this.ButtonStyle.Button.HoverBackgroundColor + '"; this.style.color = "' + this.ButtonStyle.Button.DefaultBackgroundColor + '"; }); GEvent.addDomListener(container, "mouseout", function() { this.style.backgroundColor = "' + this.ButtonStyle.Button.DefaultBackgroundColor + '"; this.style.color = "' + this.ButtonStyle.Button.HoverBackgroundColor + '"; }); map.getContainer().appendChild(container); return container; }');
		eval('this.' + oSettings.Name + '.prototype.getDefaultPosition = function(){ return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(' + oSettings.PosX + ', ' + oSettings.PosY + ')); }');
	}
	
	// Создание функции поля ввода
	this.CreateInput = function(oSettings, oObj4Style){
		eval('this.' + oSettings.Name + ' = function(){ }');
		eval('this.' + oSettings.Name + '.prototype = new GControl();');
		eval('this.' + oSettings.Name + '.prototype.initialize = function(map){ var container = document.createElement("input"); container.id  = "' + oSettings.TagID + '"; oObj4Style.Input(container); container.value = "' + oSettings.Title + '"; GEvent.addDomListener(container, "click", function() { ' + oSettings.ClickFunc + '; }); GEvent.addDomListener(container, "mouseover", function() { this.style.backgroundColor = "' + this.ButtonStyle.Input.HoverBackgroundColor + '"; this.style.color = "' + this.ButtonStyle.Input.DefaultBackgroundColor + '"; }); GEvent.addDomListener(container, "mouseout", function() { this.style.backgroundColor = "' + this.ButtonStyle.Input.DefaultBackgroundColor + '"; this.style.color = "' + this.ButtonStyle.Input.HoverBackgroundColor + '"; }); map.getContainer().appendChild(container); return container; }');
		eval('this.' + oSettings.Name + '.prototype.getDefaultPosition = function(){ return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(' + oSettings.PosX + ', ' + oSettings.PosY + ')); }');
	}
	
	// создание точки
	this.AddIcon = function(icon){
		icon.iconSize 		= new GSize(7, 7);
		icon.dragCrossSize  = new GSize(9, 9);
		icon.shadowSize 	= new GSize(0, 0);
		icon.iconAnchor  	= new GPoint(7, 7);
	}
	
	this.AddAddresIcon = function(point){
		var oSquare   = new GIcon();
		oSquare.shadow				= "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		oSquare.image				= "http://labs.google.com/ridefinder/images/mm_20_red.png";
		oSquare.iconSize 			= new GSize(12, 20);
		oSquare.shadowSize 			= new GSize(22, 20);
		oSquare.iconAnchor 			= new GPoint(6, 20);
		oSquare.infoWindowAnchor 	= new GPoint(5, 1);
		var oMarker = new GMarker(point, { icon: oSquare, draggable: false, bouncy: false, dragCrossMove: false});
		this.Map.addOverlay(oMarker);
		eval('GEvent.addListener(oMarker, "click", function(){ Maper.OpenInfoWindow(point, "' + Interface.LastAddress + '"); });');
	}
	
	// добавить точки
	this.AddDot = function(overlay, point){
		if (point){
			// создание точки
			var oSquare   = new GIcon();
			oSquare.image = "pictures/dot_map_blue.png";
			this.AddIcon(oSquare);
			this.AddMarker(point, oSquare);
		}
	}
	
	// поставить маркер
	this.AddMarker = function(point, oSquare){
		var oMarker = new GMarker(point, { icon: oSquare, draggable: true, bouncy: false, dragCrossMove: true});
		this.Markers[this.PolyCount].push(oMarker);
		this.Map.addOverlay(oMarker);
		GEvent.addListener(oMarker, "drag", function() { eval('Maper.DrawZone();'); });
		GEvent.addListener(oMarker, "mouseover", function() { oMarker.setImage("pictures/dot_map_white.png"); });
		GEvent.addListener(oMarker, "mouseout", function() { oMarker.setImage("pictures/dot_map_blue.png"); });
		GEvent.addListener(oMarker, "click", function() { eval('Maper.DropDot(oMarker);'); });
		this.DrawZone();
	}
	
	// удаление точки
	this.DropDot = function(oMarker){
		for (var g = 1; g <= this.PolyCount; g++){
			for (var n = 0; n < this.Markers[g].length; n++) {
				if (this.Markers[g][n] == oMarker){
					this.Map.removeOverlay(this.Markers[g][n]);
					break;
				}
			}
			this.Markers[g].splice(n, 1);
		}
		this.DrawZone();
	}
	
	// заливка зоны
	this.DrawZone = function(){
		for (var g = 1; g <= this.PolyCount; g++){	
			if (this.PolyZone[g]) this.Map.removeOverlay(this.PolyZone[g]);
			this.PolyPoints.length = 0;
			for (i = 0; i < this.Markers[g].length; i++){
				this.PolyPoints.push(this.Markers[g][i].getLatLng());
			}
			this.PolyZone[g] = new GPolygon(this.PolyPoints, this.ZoneBoardColor, 3, .8, this.ZoneFillColor, .3);
			var unit = " km&sup2;"; 
			var area = this.PolyZone[g].getArea() / (1000 * 1000);
			this.Map.addOverlay(this.PolyZone[g]);
		}
	}
	
	// добавить новую зону
	this.AddNewZone = function(){
		this.PolyCount++;
		this.Markers[this.PolyCount] = Array();
	}
	
	// добавить кнопку
	this.AddButton = function(sName, sTagID, sTitle, iPosX, iPosY, sClickFunc){
		this.CreateButton({ Name: sName, TagID: sTagID, Title: sTitle, PosX: iPosX, PosY: iPosY, ClickFunc: sClickFunc }, this.ButtonStyle);
		this.Map.addControl(eval('new this.' + sName + '()'));
	}
	
	// добавить поле ввода
	this.AddInput = function(sName, sTagID, sTitle, iPosX, iPosY, sClickFunc){
		this.CreateInput({ Name: sName, TagID: sTagID, Title: sTitle, PosX: iPosX, PosY: iPosY, ClickFunc: sClickFunc }, this.ButtonStyle);
		this.Map.addControl(eval('new this.' + sName + '()'));
	}
	
	// добавить лэйбл
	this.AddLable = function(sName, sTagID, sTitle, iPosX, iPosY){
		this.CreateLabel({ Name: sName, TagID: sTagID, Title: sTitle, PosX: iPosX, PosY: iPosY }, this.ButtonStyle);
		this.Map.addControl(eval('new this.' + sName + '()'));
	}
	
	// получить выделенные на каре зоны
	this.GetZone = function(){
		var oLatLng, iLat, iLng, aCoordZone = Array();
		
		for (var g = 1; g <= this.PolyCount; g++){
			aCoordZone[(g - 1)] = Array();
			for(i = 0; i < this.Markers[g].length; i++) {
				oLatLng 				  = this.Markers[g][i].getLatLng();
				aCoordZone[(g - 1)][i] 	  = Array();
				iLat 					  = oLatLng.lat();
				iLng 					  = oLatLng.lng();
				aCoordZone[(g - 1)][i][0] = eval(iLat);
				aCoordZone[(g - 1)][i][1] = eval(iLng);
			}
		}
		return aCoordZone;
	}
	
	// удаление линий с карты
	// sParam - параметр указывающий на массив
	// 		'finded' - найденные маршруты
	// 		'selected' - выбраные маршруты
	this.DropLineOnMap = function(aRouts, sTarget){
		for (iNum in aRouts){
			iNum = parseInt(iNum);
			if (aRouts[iNum] == undefined || !aRouts[iNum][sTarget]) continue;
			if (this.LinesOnMap[aRouts[iNum]['iID']] != undefined){
				this.Map.removeOverlay(this.LinesOnMap[aRouts[iNum]['iID']]);
				delete this.LinesOnMap[aRouts[iNum]['iID']];
			}
		}
	}
	
	// рисование линии на карте
	// вход:	iID				- ид маршрута
	//			aCoord			- координаты
	//			sColor			- цвет линии
	//			sFuncClick		- функция на клик
	//			sFoncMouseOver	- функция на вход мыши
	//			sFuncMouseOut	- функция на выход мыши
	this.AddLineOnMap = function(iID, aCoord, sColor, sFuncClick, sFoncMouseOver, sFuncMouseOut){
		var aPoints		= Array();
		var oLatlng		= null;
		
		for(i = 0; i < aCoord.length; i++){
			aPoints[i] = new GLatLng(aCoord[i][0], aCoord[i][1]);
		}
		
		this.LinesOnMap[iID] = new GPolyline(aPoints, sColor, 2, 1);
		this.Map.addOverlay(this.LinesOnMap[iID]);
		GEvent.addListener(this.LinesOnMap[iID], "mouseover", function(){ eval(sFoncMouseOver + '(iID); '); });
		GEvent.addListener(this.LinesOnMap[iID], "mouseout", function() { eval(sFuncMouseOut + '(iID); '); });
		if (this.CkickFunction) GEvent.addListener(this.LinesOnMap[iID], "click", function() { eval(sFuncClick + '(iID); '); });
	}
	
	// установка цвета линии
	this.SetLineColor = function(iID, sColor){
		this.LinesOnMap[iID].setStrokeStyle({color: sColor, weight: 2, opacity: 1 });
	}
	
	// открыть окно с информацией
	this.OpenInfoWindow = function(oLatlng, myHtml){
		this.Map.openInfoWindowHtml(oLatlng, myHtml);
	}
	
	// закрыть окно с информацией
	this.CloseInfoWindow = function(){
		this.Map.closeInfoWindow();
	}
	
	// получить точку на карте
	this.GetPoint = function(x, y){
		return new GLatLng(x, y);
	}
	
	// удаляются все зоны и точки на карте
	this.DropZonesOnMap = function(){
		for (var g = 1; g <= this.PolyCount; g++){
			for (var n = 0; n < this.Markers[g].length; n++) {
				this.Map.removeOverlay(this.Markers[g][n]);
			}
			if (this.PolyZone[g]) this.Map.removeOverlay(this.PolyZone[g]);
		}
		this.PolyPoints	= Array();
		this.Markers 	= Array();
		this.PolyZone 	= Array();
		this.PolyCount	= 0;
	}
	
	// установка цвета линии
	this.SetLineMouseOut = function(iID, sFunc){
		GEvent.addListener(this.LinesOnMap[iID], "mouseout", function() { eval(sFunc); });
	}
	
	// показать область вокруг найденной точки
	this.ShowAreaRoundDot = function(oPoint){
			this.Map.setCenter(oPoint, 12);
			var oMarker = new GMarker(oPoint);
			this.Map.addOverlay(oMarker);
			this.Markers[this.PolyCount].push(oMarker);
			this.AddNewZone();
			this.DrawCircle(oPoint.y, oPoint.x);
	}
	
	// нарисовать какое то подобие круга
	this.DrawCircle = function(lat, lon){
		var latOffset = 0.04;
		var lonOffset = 0.04;
		var oPoint;
		
		var oSquare   = new GIcon();
		oSquare.image = "pictures/dot_map_blue.png";
		this.AddIcon(oSquare);
		
		oPoint = new GLatLng(lat, lon - lonOffset);
		this.AddMarker(oPoint, oSquare);
		
		oPoint = new GLatLng(lat + (lonOffset / 1.5), lon - (latOffset / 2.5));
		this.AddMarker(oPoint, oSquare);
		oPoint = new GLatLng(lat + (lonOffset / 1.5), lon + (latOffset / 2.5));
		this.AddMarker(oPoint, oSquare);
		oPoint = new GLatLng(lat, lon + lonOffset);
		this.AddMarker(oPoint, oSquare);
		oPoint = new GLatLng(lat - (lonOffset / 1.5), lon + (latOffset / 2.5));
		this.AddMarker(oPoint, oSquare);
		oPoint = new GLatLng(lat - (lonOffset / 1.5), lon - (latOffset / 2.5));
		this.AddMarker(oPoint, oSquare);
		
		this.DrawZone();
		
		this.AddNewZone();
	}
	
	// найти адрес
	this.SearchOnAddress = function(address, sFunc) {
		if (this.GeoCoder) {
			this.GeoCoder.getLatLng(address, function(point){ eval('Interface.' + sFunc + '(point, "' + address + '");'); });
		} else alert('Не загружен объект для поиска по карте');
	}
}

var Maper = new Maper();

// выполняет расчет стоимости
Calculator = function(){
    this.Stop               = false;
	// идет/нет процесс вычисления
	this.CalculationProcess = false;
	// необходимо еще раз пересчитать
	this.NeedCalculation 	= false;
	// ид тэгов формы
	this.Tags				= {
								  Money: 'Money'
								, NDS: 'NDS'
								, CountContacts: 'CountContacts'
								, Coverage: 'Coverage'
								, LengthCompany: 'LengthCompany'
								};
	
	// установка значений формы отражающий данные расчета
	this.SetData = function(aData, bClear){
		if (!bClear) jQuery('.LoadRaschet').css('display', 'none');
		
		if (aData.Money4 === ''){
			jQuery('#Money4').html('');
			jQuery('#Money12').html('');
			jQuery('#Money26').html('');
			jQuery('#NDS4').html('');
			jQuery('#NDS12').html('');
			jQuery('#NDS26').html('');
			jQuery('#CountContacts4').html('');
			jQuery('#CountContacts12').html('');
			jQuery('#CountContacts26').html('');
			jQuery('#Coverage4').html('');
			jQuery('#Coverage12').html('');
			jQuery('#Coverage26').html('');
			if (bClear){
				jQuery('.LoadRaschet').css('display', 'inline');
			} else {
				this.CalculationProcess = false;
				eval('Interface.MoreCalculation();');
			}
			return false;
		}
		
		jQuery('#Money4').html(this.NumerFormat(aData.Money4) + ' руб.');
		jQuery('#Money12').html(this.NumerFormat(aData.Money12) + ' руб.');
		jQuery('#Money26').html(this.NumerFormat(aData.Money26) + ' руб.');
		jQuery('#NDS4').html(this.NumerFormat(aData.NDS4) + ' руб.');
		jQuery('#NDS12').html(this.NumerFormat(aData.NDS12) + ' руб.');
		jQuery('#NDS26').html(this.NumerFormat(aData.NDS26) + ' руб.');
		jQuery('#CountContacts4').html(this.NumerFormat(aData.CountContacts4));
		jQuery('#CountContacts12').html(this.NumerFormat(aData.CountContacts12));
		jQuery('#CountContacts26').html(this.NumerFormat(aData.CountContacts26));
		jQuery('#Coverage4').html(this.NumerFormat(aData.Coverage4));
		jQuery('#Coverage12').html(this.NumerFormat(aData.Coverage12));
		jQuery('#Coverage26').html(this.NumerFormat(aData.Coverage26));
		
		if (bClear){
			jQuery('.LoadRaschet').css('display', 'inline');
		} else {
			this.CalculationProcess = false;
			eval('Interface.MoreCalculation();');
		}
	}
	
	this.NumerFormat = function(sNumer){
		var sStr = '', sChar = '';
		sNumer  += sStr;
		for (var i = sNumer.length - 1, j = 0; i >= 0; i--, j++){
			sChar = sNumer.charAt(i);
			if (j >= 3 && sChar != '.'){
				sStr = ' ' + sStr;
				j = 0;
			}
			sStr = sChar + sStr;
		}
		return sStr;
	}
	
	// получение данных
	this.GetData = function(aCars){
		return 'iLengthCompany=' + jQuery('#' + this.Tags.LengthCompany).val() + '&iAllCars=' + aCars.iAllCars + '&iCarsWithComplexes=' + aCars.iCarsWithComplexes + '&aGroup[1]=' + aCars.A + '&aGroup[2]=' + aCars.B + '&aGroup[3]=' + aCars.C + '&aGroup[4]=' + aCars.D + '&iSelectedRubrics=' + ((jQuery('#TypeClip4').attr('checked')) ? 4 : 1);
	}
	
	// вычисление
	this.Calculation = function(aCars){
        if (this.Stop) return false;
		this.CalculationProcess = true;
		var aMoney 	 			= Array();
		aMoney.push({ group: 'i', cost: 1 });
		aMoney.push({ group: 'A', cost: 2000 });
		aMoney.push({ group: 'B', cost: 5000 });
		aMoney.push({ group: 'C', cost: 8000 });
		var iFrequency  		= 7;
		var iClipLength 		= 15; 
		var iMoney				= Math.round((cost_one_sec * 60 * aCars.D * iClipLength / (iFrequency * 2) * 10000) / 10000);
		var iExposures			= Math.round(people_per_day_average * 7 * Duration_of_trip * aCars.iCarsWithComplexes / (iFrequency * block_length)) * 2;
		iMoney		 			= Math.round(iMoney);
		
		for (var i = 1; i <= 3; i++) if (aCars[aMoney[i].group] > 0) iMoney += aCars[aMoney[i].group] * aMoney[i].cost;
		iMoney = Math.round(iMoney);
		
		this.SetData({ Money4: iMoney * 4, NDS4: '', CountContacts4: iExposures * 4, Coverage4: '', Money12: iMoney * 12, NDS12: '', CountContacts12: iExposures * 12, Coverage12: '', Money26: iMoney * 26, NDS26: '', CountContacts26: iExposures * 26, Coverage26: '' }, false);
		return true;
	}
}

var Calculator = new Calculator();

// класс предзагрузщиков
PreLoader = function(){
	// показать заставку
	this.ShowPreload = function(sVal){
		jQuery('#' + sVal).css('display', 'inline');
	}
	// скрыть заставку
	this.HidePreload = function(sVal){
		jQuery('#' + sVal).css('display', 'none');
	}
	// показать заставки
	this.ShowPreloads = function(sVal){
		jQuery('.' + sVal).css('display', 'inline');
	}
	// скрыть заставки
	this.HidePreloads = function(sVal){
		jQuery('.' + sVal).css('display', 'none');
	}
}

var PreLoader = new PreLoader();

// класс маршрутов и фильтра на странице
Router = function(){
	// массивы маршрутов
	this.Routs				 = {  // найденных
								  Finded: Array()
								  // выбранных
								, Selected: Array()
								};
	// массив информации о маршрутах
	this.aRoutsInfo		   	 = Array();
	// количество маршрутов отображаемых на странице
	this.ScrollValues		 = {
								  // количество маршрутов на странице
								  iCountScrollRout: 4
								  // начало отсчета для скролинга
								, iBegin: { Finded: 0, Selected: 0 }
								};
	// цвет маршрутов на странице
	this.sColorRiuteOnPage 	 = '#0000FF';
	// имена классов
	this.Classes			 = {  // для найденных маршрутов
								  Finded: 'finded'
								  // для выбранных маршрутов
								, Selected: 'selected'
								  // для списков маршрутов
								, RoutsList: 'SRout'
								  // кнопки фильтра
								, RouteFiltrButton: 'RouteFiltr'
								};
	// имена тэгов
	this.Tags				 = {  // для найденных маршрутов
								  Finded: 'SearchRout'
								  // для выбранных маршрутов
								, Selected: 'SelectedRout'
								  // с количеством найденных маршрутов
								, FindedRoutsNum: 'FindedRoutsNum'
								  // с количеством выбранных маршрутов
								, SelectedRoutsNum: 'SelectedRoutsNum'
								  // спискафильтров
								, FilrtList: 'RoutsFiltrsList'
								};
	// состояние списка маршрутов true/false - развернут/свернут
	this.IsViewRoutsList	 = false;
	// состояние фильтров true/false - развернут/свернут
	this.ViewFiltrsList		 = false;
	// количества маршрутов
	//this.CountRouts			 = { Find: 0, Select: 0 };
	// значение фильтра
	this.FilrtValue			 = 'All';
	// количество мониторов
	this.Monitors			 = 0;
	// выполнять ли изменения размеров списка маршрутов
	this.CangeSizeRoutsList	 = true;
	// вешать ли функцию на клик по маршруту
	this.RouteMouseClick	 = true;
	
	// заполняет массивы найденных маршрутов
	this.UpdateRouts = function(aRoutes){
		for (var i = 0; i < aRoutes.length; i++){
			this.InsertRoutInfo(aRoutes[i]);
		}
	}
	
	// добавить найденный маршрут в массив с информацией о маршрутах
	this.InsertRoutInfo = function(aRoute){
		var iFinded = true, iSelected = false;
		if (this.aRoutsInfo[aRoute['iID']] != undefined){
			iFinded   = this.aRoutsInfo[aRoute['iID']]['Finded'];
			iSelected = this.aRoutsInfo[aRoute['iID']]['Selected'];
		}
		
		this.aRoutsInfo[aRoute['iID']] 					= Array();
		this.aRoutsInfo[aRoute['iID']]['iID']			= aRoute['iID'];
		this.aRoutsInfo[aRoute['iID']]['sRout'] 		= aRoute['sRout'];
		this.aRoutsInfo[aRoute['iID']]['sKP1'] 			= aRoute['sKP1'];
		this.aRoutsInfo[aRoute['iID']]['sKP2'] 			= aRoute['sKP2'];
		this.aRoutsInfo[aRoute['iID']]['iCarsTotal']	= aRoute['iCarsTotal'];
		this.aRoutsInfo[aRoute['iID']]['iCars'] 		= aRoute['iCars'];
		this.aRoutsInfo[aRoute['iID']]['sGosNumers'] 	= aRoute['sGosNumers'];
		this.aRoutsInfo[aRoute['iID']]['sCategory'] 	= aRoute['sCategory'];
		this.aRoutsInfo[aRoute['iID']]['Finded'] 		= iFinded;
		this.aRoutsInfo[aRoute['iID']]['Selected'] 		= iSelected;
	}
	
	// отфильтровать маршруты
	this.SkipRoutsThroughFilter = function(){
		this.Routs.Finded 	= Array();
		this.Routs.Selected = Array();
		for (var iKey in this.aRoutsInfo){
			iKey = parseInt(iKey);
			if (this.aRoutsInfo[iKey] == undefined) continue;
			if (this.FilrtValue == 'All' || this.FilrtValue == this.aRoutsInfo[iKey]['sCategory']){
				if (this.aRoutsInfo[iKey]['Finded']) this.Routs.Finded.push(this.aRoutsInfo[iKey]['iID']);
				if (this.aRoutsInfo[iKey]['Selected']) this.Routs.Selected.push(this.aRoutsInfo[iKey]['iID']);
			}
		}
	}
	
	// нанести маршруты и данные о них на страницу 
	this.PutRoutsDataOnPage = function(){
		jQuery('.' + this.Classes.Finded).remove();
		jQuery('.' + this.Classes.Selected).remove();
		
		this.PutRoutsOnPage('Finded');
		this.PutRoutsOnPage('Selected');
		this.SetCountRoutsValueOnPage();
	}
	
	// установить значения количеств маршрутов
	this.SetCountRoutsValueOnPage = function(){
		jQuery('#' + this.Tags.FindedRoutsNum).html('' + this.Routs.Finded.length);
		jQuery('#' + this.Tags.SelectedRoutsNum).html('' + this.Routs.Selected.length);
		jQuery('#Monitors').html('' + Calcer.FormatMoney(this.Monitors));
		jQuery('#AverageMonitorsPerWeek').html('' + Calcer.FormatMoney(this.Monitors * 390 * 6));
	}
	
	// очистить найденные маршруты
	this.ClearRouts = function(sTarget){
		jQuery('.' + this.Classes[sTarget]).remove();
		for (iKey in this.aRoutsInfo){
			iKey = parseInt(iKey);
			if (this.aRoutsInfo[iKey] == undefined) continue;
			if (this.aRoutsInfo[iKey][sTarget]) delete this.aRoutsInfo[iKey];
		}
		this.Routs[sTarget] = Array();
	}
	
	// добавляет маршрут на страницу
	// вход:	aRout	 - массив с данными о маршруте
	//			sTarget	 - цель найденные/выбранные Finded/Selected
	//			bDisplay - видимость маршрута
	this.AddRouteOnPage = function(aRoute, sTarget, bDisplay){
		jQuery('#' + this.Tags[sTarget]).append(this.GetRoutStr(aRoute, sTarget, bDisplay));
	}
	
	// генерирует строку для вставки маршрута
	// вход: 	aRout 	- массивс данными о маршруте
	//			sTarget	- цель найденные/выбранные Finded/Selected
	//			Display - отображать/скрыть
	this.GetRoutStr = function(aRoute, sTarget, Display){
		Display = (Display) ? '' : 'display: none;';
		return '<div class="rout ' + this.Classes[sTarget] + '" id="' + sTarget + aRoute['iID'] + '" onmouseover="' + 'Interface.RouteOnMapMouseOver(' + aRoute['iID'] + '); Helper.OnHelper({ id: \'' + ((this.aRoutsInfo[aRoute['iID']]['Selected'] != undefined && this.aRoutsInfo[aRoute['iID']]['Selected']) ? 'DelRout' : 'SelRout') + '\' });" onmouseout="' + 'Interface.RouteOnMapMouseOut(' + aRoute['iID'] + '); Helper.OffHelper({ id: \'' + ((this.aRoutsInfo[aRoute['iID']]['Selected'] != undefined && this.aRoutsInfo[aRoute['iID']]['Selected']) ? 'DelRout' : 'SelRout') + '\' });" ' + (this.RouteMouseClick ? 'onclick="' + 'Interface.RouteMouseClick(' + aRoute['iID'] + ');"' : '') + ' onmousemove="Helper.MoveHelper(event);" style="color: ' + this.sColorRiuteOnPage + '; ' + Display + '">' + aRoute['sRout'] + '</div>';
	}
	
	// нанести маршруты на страницу скрытые
	this.PutRoutsOnPage = function(sTarget){
		for (var i = 0; i < this.Routs[sTarget].length; i++){
			this.AddRouteOnPage(this.aRoutsInfo[this.Routs[sTarget][i]], sTarget, false);
		}
		this.ActionViewRouteList();
	}
	
	// выполняет действие
	this.ActionViewRouteList = function(){
		if (this.CangeSizeRoutsList){
			var iHeight = 0;
			this.ScrollValues.iCountScrollRout = (this.Routs.Finded.length > this.Routs.Selected.length) ? this.Routs.Finded.length : this.Routs.Selected.length;
			this.ScrollValues.iCountScrollRout = (this.IsViewRoutsList) ? (this.ScrollValues.iCountScrollRout > 38 ? 38 : this.ScrollValues.iCountScrollRout) : 4;
			iHeight 					 	   = (this.IsViewRoutsList && this.ScrollValues.iCountScrollRout > 4) ? ((this.ScrollValues.iCountScrollRout > 38 ? 38 : this.ScrollValues.iCountScrollRout) * 14) + 5 + 'px' : ((this.ViewFiltrsList) ? '60px' : '80px');
			jQuery('.' + this.Classes.RoutsList).css('height', iHeight);
		}
		this.ReDriveAllScrollRouts();
	}
	
	// перерисовывает поля с маршрутами
	this.ReDriveAllScrollRouts = function(){
		this.ReDriveScrollRouts('Finded');
		this.ReDriveScrollRouts('Selected');
	}
	
	// перерисовывает отдельный столбец
	// вход:	sTarget - f/s - найденных/выбранных
	this.ReDriveScrollRouts = function(sTarget){
		this.CheckScrollBegin(sTarget);
		var i = 1, iBegin = this.ScrollValues.iBegin[sTarget], iCount = this.ScrollValues.iCountScrollRout;
		
		jQuery("#" + this.Tags[sTarget] + ' div.' + this.Classes[sTarget]).each(function () {
			if ((i < iBegin) || (i > (iCount + iBegin))) this.style.display = 'none';
			else this.style.display = 'block';
			i++;
		});
	}
	
	// проверка выхождения скролинга за пределы
	this.CheckScrollBegin = function(sTarget){
		if (this.ScrollValues.iBegin[sTarget] < 1) this.ScrollValues.iBegin[sTarget] = 1;
		if ((this.ScrollValues.iBegin[sTarget] + this.ScrollValues.iCountScrollRout) > this.Routs[sTarget].length) this.ScrollValues.iBegin[sTarget] = this.Routs[sTarget].length - this.ScrollValues.iCountScrollRout;
	}
	
	// получить информацию о маршруте
	this.GetRouteInfo = function(iID){
		if (this.aRoutsInfo[iID] == undefined) return Array();
		else return this.aRoutsInfo[iID];
	}
	
	// установка точки для информации
	this.SetPoint = function(iID, oPoint){
		this.aRoutsInfo[iID]['oPoint'] = oPoint;
	}
	
	// раскрывает список маршрутов
	this.ViewRoutList = function(bView){
		if (this.IsViewRoutsList == bView) return false;
		this.IsViewRoutsList = (this.IsViewRoutsList) ? false : true;
		this.ActionViewRouteList();
	}
	
	// включение/отключение фильтров
	this.ViewFiltrs = function(){
		if (this.ViewFiltrsList){
			jQuery('#' + this.Tags.FilrtList).css('display', 'none');
			this.ViewFiltrsList = false;
		} else {
			jQuery('#' + this.Tags.FilrtList).css('display', 'inline');
			this.ViewFiltrsList = true;
		}
	}
	
	// клик по фильтру
	this.ClickOnFiltr = function(oTag){
		this.FilrtValue = oTag.id;
		this.SkipRoutsThroughFilter();
		this.PutRoutsDataOnPage();
		this.ViewFilterButton(oTag.id);
	}
	
	// выделение кнопки активного фильтра
	this.ViewFilterButton = function(sTagID){
		jQuery('#' + this.Tags.FilrtList + ' .' + this.Classes.RouteFiltrButton).css('background-color', '').css('color', '#000000');
		jQuery('#' + this.Tags.FilrtList + ' #' + sTagID).css('background-color', '#000000').css('color', '#FFFFFF');
	}
	
	// выбор маршрута (перерисовка его из одного столбца в другой и перемещение в другой массив)
	this.SelectRoute = function(iID){
		jQuery('#Finded' + iID).remove();
		this.aRoutsInfo[iID]['Finded'] 	 = false;
		this.aRoutsInfo[iID]['Selected'] = true;
		this.SkipRoutsThroughFilter();
		jQuery('#' + this.Tags.Selected).append(this.GetRoutStr(this.aRoutsInfo[iID], "Selected", false));
		this.ReDriveAllScrollRouts();
		this.Monitors += this.aRoutsInfo[iID]['iCars'];
	}
	
	// отмена выбора маршрута (перерисовка его из одного столбца в другой и перемещение в другой массив)
	this.UnSelectRoute = function(iID){
		jQuery('#Selected' + iID).remove();
		this.aRoutsInfo[iID]['Selected'] = false;
		this.aRoutsInfo[iID]['Finded'] 	 = true;
		this.SkipRoutsThroughFilter();
		jQuery('#' + this.Tags.Finded).append(this.GetRoutStr(this.aRoutsInfo[iID], "Finded", false));
		this.ReDriveAllScrollRouts();
		this.Monitors -= this.aRoutsInfo[iID]['iCars'];
	}
	
	// прокрутка скролинга
	this.Scroll = function(sTarget, iCount){
		if (this.ScrollValues.iCountScrollRout >= this.Routs[sTarget].length) return false;
		this.ScrollValues.iBegin[sTarget] += iCount;
		this.ActionViewRouteList();
	}
	
	// ограничение выбора маршрутов
	this.LimitationRouts = function(iCount){
		jQuery('#' + this.Tags.Selected + ' div:gt(' + (iCount - 1) + ')').click();
	}
	
	// выдача данных по маршрутам
	// возвращает объект такого вида
	// вход:	sTarget - Finded/Selected - информацию о каких маршрутах нужно выдать
	// { iAllCars: всего машин, iCarsWithComplexes: машин оборудованных, A: , B: , C: , D: количество машин по категориям, sRoutsNumStr: строка с номерами маршрутов }
	this.GetRoutsData = function(sTarget){
		var aData = { iAllCars: 0, iCarsWithComplexes: 0, A: 0, B: 0, C: 0, D: 0, sRoutsNumStr: '', ids: Array() };
		for (iKey in this.aRoutsInfo){
			iKey = parseInt(iKey);
			if (this.aRoutsInfo[iKey] == undefined) continue;
			if (this.aRoutsInfo[iKey][sTarget]){
				aData.iAllCars	 		  += this.aRoutsInfo[iKey]['iCarsTotal'];
				aData.iCarsWithComplexes  += this.aRoutsInfo[iKey]['iCars'];
				if (this.aRoutsInfo[iKey]['sCategory'] == 'D') aData.D += this.aRoutsInfo[iKey]['iCars'];
				else aData[this.aRoutsInfo[iKey]['sCategory']]++;
				if (aData.sRoutsNumStr.length > 0) aData.sRoutsNumStr += ', ';
				aData.sRoutsNumStr += this.aRoutsInfo[iKey]['sRout'];
				aData.ids.push(iKey);
			}
		}
		return aData;
	}
}

var Router = new Router();

// класс работы с формой
Former = function(){
	this.Tags		= {
						Form: 'SaveForm'
						};
	// данные для проверик формы
	// вид:	{ тип формы: Array(0 => { sTagName: имя тэга с обязательным значением, sTagType: тип поля, sError: текст ошибки }), ... }
	// 			sType: 'checkbox' - чекбокс; 'text' - текст; 'posnum' - число больше нуля.
	this.Check 		= {};
	
	// добавить тип формы
	this.AddFormType = function(sFormType, sTagName, sTagType, sError){
		if (this.Check[sFormType] == undefined) this.Check[sFormType] = Array();
		this.Check[sFormType].push({ 'sTagName': sTagName, 'sTagType': sTagType, 'sError': sError });
	}
	
	// проверка введенных данных
	this.CheckForm = function(sFormType){
		var IsNotOK = false;
		if (this.Check[sFormType] == undefined) return true;
		for (var i = 0; i < this.Check[sFormType].length; i++){
			IsNotOK = false;
			switch(this.Check[sFormType][i].sTagType){
				case 'checkbox':
					IsNotOK = (jQuery('#' + this.Tags.Form + ' #' + this.Check[sFormType][i].sTagName).attr('checked')) ? false : true;
					break;
				case 'text':
					IsNotOK = ((jQuery('#' + this.Tags.Form + ' #' + this.Check[sFormType][i].sTagName).val()).length > 0) ? true : false;
					break;
				case 'posnum':
					IsNotOK = (jQuery('#' + this.Tags.Form + ' #' + this.Check[sFormType][i].sTagName).val().length > 0) ? true : false;
					break;
			}
			if (IsNotOK){
				alert(this.Check[sFormType][i].sError);
				return false;
			}
		}
		return true;
	}
	
	// сохранение заявки
	this.Save = function(sFormType){
		if (!this.CheckForm(sFormType)) return false;
		BaseObject.SimpleAjaxQuest('campaign/Create.php', jQuery('#' + this.Tags.Form).serialize(), 'eval(msg); ' + 'Interface.AfretFormSave(aResult);', "jQuery('#IsForm').css('display', 'none'); jQuery('#preload').css('display', 'inline');", "alert('Ошибка при сохранении формы!'); jQuery('#preload').css('display', 'none'); jQuery('#IsForm').css('display', 'inline');");
	}
	
	// действие после сохранения
	this.AfretSave = function(aResult){
		if (aResult.sError != undefined && aResult.sError.length > 0) {
			alert(aResult.sError);
			jQuery('#preload').css('display', 'none');
			jQuery('#IsForm').css('display', 'inline');
		} else {
			jQuery('#preload').css('display', 'none');
			alert("Вашей заявке присвоен номер " + aResult.iNum + ".\nВ ближайшее время с Вами свяжется менеджер канала.\nТак же Вы можете уточнить состояние заявки и обсудить\nдетали размещения по телефону 775-3600.");
			jQuery('.IsForm').css('display', 'none');
		}
	}
}

var Former = new Former();

// обработка шагов продвижения по странице
Steper = function(){
	// строки для линии помощи
	// видa Array[номер шага] = строка помощи
	this.HeplLine 	 = Array();
	// контроль шагов
	// вида Array[номер шага] = выполнен/нет true/false
	this.StepControl = Array();
	
	// вставить строку для помощи
	this.InsertHelpLine = function(iStep, sHelp){
		this.HeplLine[iStep] 	= sHelp;
		this.StepControl[iStep] = false;
	}
	
	// шаг выполнен
	this.AcceptStep = function(iStep){
		this.StepControl[iStep] = true;
	}
	
	// шаг не выполнен
	this.UnAcceptStep = function(iStep){
		this.StepControl[iStep] = false;
	}
	
	// шаги выполнения на карте
	this.Step = function(){
		var iStep = this.GetNextStep();
		jQuery('.Steps').removeClass('cred');
		jQuery('#Step' + iStep).addClass('cred');
		jQuery('#HelpLenta').html(this.HeplLine[iStep]);
	}
	
	// получить номер следующего шага
	this.GetNextStep = function(){
		var i = 0;
		for (i; i < this.StepControl.length; i++){
			if (this.StepControl[i] != undefined && this.StepControl[i] == false) break;
		}
		return i;
	}
	
	this.GetCountSteps = function(){
		var j = 0;
		for (var i = 0; i < this.StepControl.length; i++){
			if (this.StepControl[i] != undefined) j++;
		}
		return j;
	}
}

var Steper = new Steper();

// вычисление даты окончания
function SetEndDate(sStartTag, sLengthTag, sEndTag){
	var sStartDate = jQuery("#" + sStartTag).val();
	var dStartDate = new Date(eval(sStartDate.charAt(6) + sStartDate.charAt(7) + sStartDate.charAt(8) + sStartDate.charAt(9)), (eval(sStartDate.charAt(3) + sStartDate.charAt(4)) - 1), (eval(sStartDate.charAt(0) + sStartDate.charAt(1)) + (jQuery("#" + sLengthTag).val() * 7) - 1), 15, 0, 0);
	jQuery("#" + sEndTag).html(((dStartDate.getDate() < 10) ? '0' + dStartDate.getDate() : dStartDate.getDate()) + "." + (((dStartDate.getMonth() + 1) < 10) ? '0' + (dStartDate.getMonth() + 1) : (dStartDate.getMonth() + 1)) + "." + dStartDate.getFullYear());
}

BaseObject = function(){
	this.prototype = {};
	// простой аякс запрос
	// вход:	sScript - путь до скрипта
	//			sValue	- значения передаваемые скрипту
	//			sFunc	- имя функции выполяемой после завершения запроса. ей передается объект oResult содержащий все необходимое
	this.SimpleAjaxQuest = function(sScript, sValue, sFunc, sFuncBeforeSend, sFuncError){
		jQuery.ajax({
			type: 	 	"POST",
			url:  	 	"ajax/" + sScript,
			data: 	 	sValue,
			timeout:	30000,
			beforeSend: function(){
							eval(sFuncBeforeSend);
						},
			error:		function (XMLHttpRequest, textStatus, errorThrown) {
							eval(sFuncError);
						},
			success: 	function(msg){
							eval(sFunc);
						}
		});
	}
	
	this.EditForm = function(sTag, bView){
		sView = (bView) ? 'inline' : 'none';
		jQuery('#' + sTag).css('display', sView);
		jQuery('#preload').css('display', sView);
	}
	
	// установка конечной датты (вычисляется исходя из недель)
	this.SetEndDate = function(sStartTag, sLengthTag, sEndTag){
		var sStartDate  = jQuery("#" + sStartTag).val();
		var iLength 	= parseInt(jQuery("#" + sLengthTag).val());
		if (sStartDate == undefined || iLength == undefined || iLength <= 0 || sStartDate.length <= 0){
			jQuery("#" + sEndTag).empty();
			return false;
		}
		var dStartDate  = new Date(eval(sStartDate.charAt(6) + sStartDate.charAt(7) + sStartDate.charAt(8) + sStartDate.charAt(9)), (eval(sStartDate.charAt(3) + sStartDate.charAt(4)) - 1), (eval(sStartDate.charAt(0) + sStartDate.charAt(1)) + (jQuery("#" + sLengthTag).val() * 7) - 1), 15, 0, 0);
		jQuery("#" + sEndTag).html(((dStartDate.getDate() < 10) ? '0' + dStartDate.getDate() : dStartDate.getDate()) + "." + (((dStartDate.getMonth() + 1) < 10) ? '0' + (dStartDate.getMonth() + 1) : (dStartDate.getMonth() + 1)) + "." + dStartDate.getFullYear());
	}
	
	this.AJAXLoadFile = function(sFileName){
		if (navigator.appName == 'Microsoft Internet Explorer'){
			jQuery('#NewFile').css('display', 'none');
			jQuery('#FileLoaderImage').css('display', 'inline');
			var req = new JsHttpRequest();
			req.onreadystatechange = function(){
				if (req.readyState == 4){
					if (req.responseJS.error == 'error'){
						alert('Ошибка!');
					} else {
						jQuery('#FileNames').append(req.responseJS.file + ' ');
					}
					
					jQuery('#FileLoaderImage').css('display', 'none');
					jQuery('#NewFile').css('display', 'inline');
				}
		   }
		   req.open('POST', "ajax/LoadFile.php", true);
		   req.send( { NewFile: sFileName } );
		} else {
			jQuery.ajaxFileUpload({
				dataType: 		"post",
				url:  	 		"ajax/LoadFile.php",
				fileElementId:  'NewFile',
				secureuri:		false,
				beforeSend: 	function(){
									jQuery('#NewFile').css('display', 'none');
									jQuery('#FileLoaderImage').css('display', 'inline');
								},
				error:			function (XMLHttpRequest, textStatus, errorThrown) {
									alert('Ошибка!');
									jQuery('#FileLoaderImage').css('display', 'none');
									jQuery('#NewFile').css('display', 'inline');
								},
				success: 		function(msg){
									if (msg == 'error'){
										alert('Ошибка!');
									} else {
										jQuery('#FileNames').append(msg + ' ');
									}
									jQuery('#FileLoaderImage').css('display', 'none');
									jQuery('#NewFile').css('display', 'inline');
								}
			});
		}
	}
	
	this.AJAXLoadSomthingFile = function(sFileName, sTag){
		if (navigator.appName == 'Microsoft Internet Explorer'){
			jQuery('#' + sTag + 'File').css('display', 'none');
			jQuery('#' + sTag + 'LoaderImage').css('display', 'inline');
			var req = new JsHttpRequest();
			req.onreadystatechange = function(){
				if (req.readyState == 4){
					if (req.responseJS.error == 'error'){
						alert('Ошибка!');
						jQuery('#' + sTag + 'LoaderImage').css('display', 'none');
						jQuery('#' + sTag + 'File').css('display', 'inline');
					} else {
						jQuery('#' + sTag + 'File').remove();
						jQuery('#' + sTag + 'FileOK').html('OK');
						jQuery('#' + sTag + 'LoaderImage').css('display', 'none');
					}
				}
		   }
		   req.open('POST', "ajax/LoadFile.php", true);
		   req.send( { NewFile: sFileName } );
		   
		} else {
			jQuery.ajaxFileUpload({
				dataType: 		"post",
				url:  	 		"ajax/LoadFile.php",
				fileElementId:  sTag + 'File',
				secureuri:		false,
				beforeSend: 	function(){
									jQuery('#' + sTag + 'File').css('display', 'none');
									jQuery('#' + sTag + 'LoaderImage').css('display', 'inline');
								},
				error:			function (XMLHttpRequest, textStatus, errorThrown) {
									alert('Ошибка!');
									jQuery('#' + sTag + 'LoaderImage').css('display', 'none');
									jQuery('#' + sTag + 'File').css('display', 'inline');
									//this;
								},
				success: 		function(msg){
					
									if (msg == 'error'){
										alert('Ошибка!');
										jQuery('#' + sTag + 'LoaderImage').css('display', 'none');
										jQuery('#' + sTag + 'File').css('display', 'inline');
									} else {
										jQuery('#' + sTag + 'File').remove();
										jQuery('#' + sTag + 'FileOK').html('OK');
										jQuery('#' + sTag + 'LoaderImage').css('display', 'none');
									}
								}
			});
		}
	}
	
	this.Preloader = {
		  View: function(sID){
					var sDisp = (jQuery('#' + sID).css('display') = 'none') ? 'inline' : 'none';
					jQuery('#' + sID).css('display', sDisp);
		  		}
		, Show: function(sID){ jQuery('#' + sID).css('display', 'inline'); }
		, Hide: function(sID){ jQuery('#' + sID).css('display', 'none'); }
		// загрузка заставки для прелоада 
		// sColor - цвет фона. доступны black|white
		, Load: function(sID, sColor){ jQuery('body').append("<div class='preload-" + sColor + "' id='" + sID + "' align='center' style='display: none;' ></div>"); }
		, Icon: function(sTag, bView){ 
					jQuery('#PreloadIcon_' + sTag).css('display', (bView ? 'inline' : 'none')); 
					jQuery('#PreloadLink_' + sTag).css('display', (bView ? 'none' : 'inline')); 
				}
		, ShowIcon: function(sTag){ this.Icon(sTag, true); }
		, HideIcon: function(sTag){ this.Icon(sTag, false); }
	};
}

Filter = function(){
	this.Tags = { 	button: 'filter_submit'
				  , field: 'filter_field'
				  , order: 'filter_order'
				  , label_in_filter: 'label_4_'
				  , filter_content: 'filter_content'};
	
	this.SetFilter = function(sField, sOrder){
		jQuery('#' + this.Tags.field).val(sField);
		jQuery('#' + this.Tags.order).val(sOrder);
		jQuery('#' + this.Tags.button).click();
	}
	
	this.View = function(){
		var sIsNow = jQuery('#' + this.Tags.filter_content).css('display');
		var sView  = (sIsNow == 'none') ? 'block' : 'none';
		jQuery('#' + this.Tags.filter_content).css('display', sView);
		jQuery('.filter .view').removeClass(sView);
		jQuery('.filter .view').addClass(sIsNow);
	}
}

var Filter 		= new Filter();
var BaseObject  = new BaseObject();

// класс работы с рубриками
Headinger = function(){
	// формы для рубрик
	this.Forms			= {
							  Activ: -1
							, sName: ''
							, Content: {}
							};
	this.Classes 		= {
							  TypeClips: 'TypeClips'
							, HolidayOff : 'holidayoff'
							, HolidayOn: 'holidayon'
							};
	this.Tags			= {
							  TplClip: 'TplClip'
							, SaveFormRe: 'SaveFormStepRe'
							, SaveForm: 'SaveForm'
							, Form: 'IsForm'
							};
	// содержимое плеера соотнесенное с рубрикой
	// массив вида Array[номер рубрики] = контент плеера
	this.HeadingContent = {};
	// соотнесение тэга для вставки и контента формы с типом ролика
	// вида:	{ тип: { Forms: Array( 0 => { sTagID: ид тэга куда вставить форму, sName: имя формы }, Frequency: частота показа, Hrono: хронометраж }, ... ) }
	this.Typs			= {};
	
	// скрытие/показ праздников
	this.SetHoliday = function(bView){
		var sClassOn  = (bView) ? this.Classes.HolidayOn  : this.Classes.HolidayOff;
		var sClassOff = (bView) ? this.Classes.HolidayOff : this.Classes.HolidayOn;
		jQuery('.' + sClassOff).css('display', 'none');
		jQuery('.' + sClassOn).css('display', 'block');
	}
	
	// показать скрыть форму для заполения заявки
	this.ViewSaveForm = function(bViev){
		var sDisplay = (bViev) ? 'block' : 'none';
		jQuery('#' + this.Tags.Form).css('display', sDisplay);
	}
	
	// загрузка формы для сохранения
	this.LoadForm = function(sType, i){
		BaseObject.SimpleAjaxQuest('campaign/Forms.php', 'form=' + this.Typs[sType].Forms[i].sName, 'Interface.Headinger.AddForm(msg, "' + this.Typs[sType].Forms[i].sName + '"); ' + 'Interface.Headinger.InsertFormOnPage("' + sType + '", ' + i + ');', '', "alert('Ошибка загрузки формы!');");
	}
	
	// сохранение формы для сохранения
	this.AddForm = function(Content, sName){
		this.Forms.Content[sName] = Content;
	}
	
	// загрузка контента
	this.LoadClip = function(sType, sContent){
		this.HeadingContent[sType] = sContent;
	}
	
	// вставка клипа на страницу
	this.AddClipOnPage = function(sType){
		jQuery('#' + this.Tags.TplClip).html(this.HeadingContent[sType]);
	}
	
	// загрузка типов
	this.LoadFormsType = function(sType, Frequency, Hrono){
		if (this.Typs[sType] == undefined) this.Typs[sType] = { Forms: Array(), 'Frequency': 0, 'Hrono': 0 };
		this.Typs[sType].Frequency 	= Frequency;
		this.Typs[sType].Hrono 		= Hrono;
	}
	
	// установка данных для ролика
	this.SetData4Clip = function(sType){
		if (this.Typs[sType] == undefined) return false;
		jQuery('#Frequency').val(this.Typs[sType].Frequency);
		jQuery('#Hrono').val(this.Typs[sType].Hrono);
	}
	
	// загрузка формы для типа
	this.LoadForm4Type = function(sType, sTagID, sFormName){
		if (this.Typs[sType].Forms == undefined){
			alert('Ошибка загрузки формы');
			return false;
		}
		this.Typs[sType].Forms.push({ sTagID: sTagID, sName: sFormName });
	}
	
	// выбор типа ролика
	this.CheckTypeClip = function(oTag){
		jQuery('.itsall').css('display', 'none');
		if (oTag.value == '6') this.SetHoliday(true);
		else if (oTag.value == '9') this.SetAdsOnRouts(true);
		else this.SetHoliday(false);
		
		var sType = oTag.value;
		this.Forms.Activ = sType;
		this.AddClipOnPage(sType);
		this.SetData4Clip(sType);
		this.CheckFormOnPage(sType);
	}
	
	// скрытие/показ ролика на маршруте
	this.SetAdsOnRouts = function(bView){
		var sClassOn  = (bView) ? 'ads_on_route'  		  : this.Classes.HolidayOff;
		var sClassOff = (bView) ? this.Classes.HolidayOff : 'ads_on_route';
		jQuery('.' + sClassOff).css('display', 'none');
		jQuery('.' + sClassOn).css('display', 'block');
	}
	
	// обработка типа ролика для формы
	this.CheckFormOnPage = function(sType){
		if (this.Typs[sType] == undefined) return false;
		if (this.Typs[sType].Forms == undefined){
			alert('Ошибка! Для этой рубрики не определенна форма!');
			return false;
		}
		
		for (var i = 0; i < this.Typs[sType].Forms.length; i++){
			if (this.Forms.Content[this.Typs[sType].Forms[i].sName] == undefined) this.LoadForm(sType, i);
			else this.InsertFormOnPage(sType, i);
		}
	}
	
	// вставка на страницу форм
	this.InsertFormOnPage = function(sType, i){
		jQuery('#' + this.Typs[sType].Forms[i].sTagID).html(this.Forms.Content[this.Typs[sType].Forms[i].sName]);
	}
}

var Headinger = new Headinger();

// класс интерфейса страницы
// собснаэтот класс и используется на странице и с помощью его всюду творится добро!
Interface = function(){
	// имя класса загрузщика маршрутов
	this.sLoadRout				 = 'loading';
	// цвет найденного маршрута на карте
	this.sColorFindedRoutOnMap 	 = '#FF0000';
	// цвет выбранного маршрута на карте
	this.sColorSelectedRoutOnMap = '#00FF00';
	// цвет активного маршрута на карте
	this.sColorHoverRoutOnMap 	 = '#0000FF';
	// ид тэга где покоятся списки маршрутов
	this.sRouteListTag			 = 'RoutsLists';
	// имя тэга для копки удаления найденных маршрутов
	this.DropFindedRoutsTad		 = 'DropFindedRouts';
	// ид тэга для кнопки удаления выбранных маршрутов
	this.UnSelectRoutsTag	 	 = 'UnSelectRoutsTag';
	// имя класса для кнопок скролинга
	this.ScrollButtonClassName	 = 'Scroll';
	// ид тэга кнопки включения/выключения фильтра
	this.FiltrListButtonTag		 = 'RoutsFiltrs';
	// ид тэгов кнопок фильтров
	this.RouteFiltrButtonTag 	 = 'RouteFiltr';
	// ид тэгов
	this.Tags					 = {  // начало компании
									  StartCompany: 'StartCompany'
									  // длинна компании
									, LengthCompany: 'LengthCompany'
									  // конец компании
									, EndCompany: 'EndCompany'
									  // количество мониторов
									, Monitors: 'Monitors'
									  // среднее количество пассажиров за неделю
									, AverageMonitorsPerWeek: 'AverageMonitorsPerWeek'
									};
	// имена классов
	this.Classes				 = {
									FindedField: 'FindedField'
									};
	// длинна рекламной компании
	this.LengthCompany			 = -1;
	// максимально возможное число выбранных маршрутов
	this.iMaxCountSelectedRoute	 = 1000;
	// права пользователя
	this.AccessRights			 = 'unauth';
	// названия маршрутов
	this.RoutsName				 = Array();
	// инфа будет с ценой
	this.InfoWithMoney			 = false;
	// инфа будет с мониторами
	this.InfoWithMonitors		 = false;
    // показывать кнопки работы с выделением областей
    this.ShowZone4RoutsButton    = true;
    // показывать кнопки для работы с маршрутами
    this.ShowRoutsButton         = true;
    this.StopRouteMouseClick     = false;

	// загрузка интерфейса
	this.Load = function(){
		// загрузка карты
		Maper.Load();

        if (this.ShowZone4RoutsButton){
            Maper.AddLable('Zone4RoutTitle4M', 'Zone4RoutTitle', 'Область выделения', 45, 7);
            Maper.AddButton('AddZone4Rout4M', 'AddZone4Rout', 'Добавить', 45, 24, 'Maper.AddNewZone(); Socket.Send("MaperAddNewZone[a]=1");');
            Maper.AddButton('ClearAllZone4Rout4M', 'ClearAllZone4Rout', 'Удалить', 235, 24, 'Interface.DropZonesOnMap(); Socket.Send("DropZonesOnMap[a]=1");');
        }

        if (this.ShowRoutsButton){
            Maper.AddLable('ShowRoutsTitle4M', 'ShowRoutsTitle', 'Маршруты', 180, 7);
            Maper.AddButton('DelRoutsTitle4M', 'DelRoutsZone', 'Удалить', 124, 24, 'Interface.ClaerMap(); Socket.Send("ClaerMap[a]=1");');
            Maper.AddButton('ShowRoutsZone4M', 'ShowRoutsZone', 'Найти', 180, 24, 'Interface.SearchRoutInZoneOnMap(); Socket.Send("SearchRoutInZoneOnMap[a]=1");');
        }
		//Maper.AddButton('SearchAddress4M', 'SearchAddress', 'Найти', 180, 7, 'Interface.AddAddressMarker()');
		//Maper.AddInput('Address4Search4M', 'Address4Search', 'Найти адрес', 70, 7, 'this.value = "";');
		Maper.AddNewZone();
		Maper.AddClickOnMapFunction(ClickOnFuckingMap);
		// загрузка помошника
		Helper.Load();
		// первый шаг
		Steper.Step();

		$('#' + Maper.Tag4Map).mouseover(function(){ eval('Router.ViewRoutList(false);'); });
		$('#' + this.sRouteListTag).mouseover(function(){ eval('Router.ViewRoutList(true);'); }).mouseout(function(){ eval('Router.ViewRoutList(false);'); });
		$('#' + this.DropFindedRoutsTad).click(function(){ eval('Interface.DropFindedRouts();'); });
		$('#' + this.UnSelectRoutsTag).click(function(){ eval('Interface.DropSelectedRouts();'); });
		$('.' + this.ScrollButtonClassName).click(function(){ eval('Interface.Scroll(this);'); });
		$('#' + this.FiltrListButtonTag).click(function(){ eval('Interface.ViewFiltrs();'); });
		$('.' + this.RouteFiltrButtonTag).click(function(){ eval('Interface.ClickOnFiltr(this);'); });
		$('.' + this.Classes.FindedField).click(function(){ eval('Interface.ViewSearchSort();'); });
		$('.' + Headinger.Classes.TypeClips).click(function(){ eval('Interface.CheckHeading(this);'); });
		$('#' + this.Tags.StartCompany).change(function(){ eval('Interface.SetNewDateCamp();'); });
		$('#' + this.Tags.LengthCompany).change(function(){ eval('Interface.SetNewDateCamp();'); });

		//$('#Address4Search').keypress(function(event){ if (event.keyCode == 13){ $('#SearchAddress').click(); } });

		Calculator.Tags.LengthCompany = this.Tags.LengthCompany;

		this.SetNewDateCamp();
		this.GetRouts();
	}

	this.LastAddress = '';

	this.AddAddressMarker = function(){
		this.LastAddress = $('#Address4Search').val();
		Maper.SearchOnAddress(this.LastAddress, 'SetAddress');
	}

	// проверка полученной точки
	this.SetAddress = function(oPoint){
		if (oPoint){
			Maper.Map.setCenter(oPoint, 16);
			Maper.AddAddresIcon(oPoint);
			Maper.OpenInfoWindow(oPoint, this.LastAddress);
		} else {
			alert("Hе найдено!");
		}
	}

	this.GetRouts = function(){
		BaseObject.SimpleAjaxQuest('SearchRouts.php', 'onlyname=1&value=', 'eval(msg); Interface.AddRoutsName(aResult);', "", "");
	}

	this.AddRoutsName = function(aRoutes){
		for (var i = 0; i < aRoutes.length; i++){
			if (aRoutes[i] == undefined) continue;
			this.RoutsName.push(aRoutes[i]['sRout']);
		}
	}

	// после сохранения формы
	this.AfretFormSave = function(aResult){
		if (Former.AfretSave(aResult)) this.ViewSaveForm(false);
	}

	// сохранение формы
	this.FormSave = function(){
		Former.Save(Headinger.Forms.Activ);
	}

	// вызов калькуляции
	this.Calculation = function(){
		if (isNaN(parseInt(Headinger.Forms.Activ)) || Headinger.Forms.Activ <= 0 || Router.Routs.Selected.length <= 0){
			Calculator.SetData({ Money4: 0, NDS4: 0, CountContacts4: 0, Coverage4: 0, Money12: 0, NDS12: 0, CountContacts12: 0, Coverage12: 0, Money26: 0, NDS26: 0, CountContacts26: 0, Coverage26: 0 }, false);
			return false;
		}
		if (Calculator.CalculationProcess){
			Calculator.NeedCalculation = true;
			return false;
		}
		Calculator.Calculation(Router.GetRoutsData('Selected'));
		this.AddDataToForm();
        //Socket.Send('');
        return true;
	}

	this.MoreCalculation = function(){
		if (Calculator.NeedCalculation){
			Calculator.NeedCalculation = false;
			this.Calculation();
		}
	}

	// добавляет необходимые данные на форму
	this.AddDataToForm = function(){
		var LengthCompany = parseInt($('#' + this.Tags.LengthCompany).val())
		$('#IsMoney').html($('#Money' + LengthCompany).html());
		$('#IsNDS').html($('#NDS' + LengthCompany).html());
		$('#money_hid').val($('#Money' + LengthCompany).html());
		$('#nds_hid').val($('#NDS' + LengthCompany).html());
		var RoutsData = Router.GetRoutsData('Selected');
		$('#RoutList').html(RoutsData.sRoutsNumStr);
		$('#RoutListHide').val(RoutsData.sRoutsNumStr);
		$('#RoutCatAll').html('Категории А: ' + RoutsData.A + 'Категории B: ' + RoutsData.B + '<br />Категории C: ' + RoutsData.C + 'Категории D: ' + RoutsData.D);
		$('#DateBegin').html($('#StartCompany').val());
		$('#DateBeginHide').val($('#StartCompany').val());
		$('#DateEnd').html($('#EndCompany').html());
		$('#CountWeek').html($('#LengthCompany').val());
		$('#CountWeekHide').val($('#LengthCompany').val());
	}

	// отображение/скрытие формы для сохранения
	this.ViewSaveForm = function(bView){
		if (this.AccessRights == 'unauth'){
			if (confirm("Анонимные пользователи не могут создавать Рекламные Компании.\nЗарегистрируйтесь либо Авторизируйтесь.\n\nПереидти на страницу авторизации?")){
				location.href = '/auth.php';
			}
			return false;
		}

		if (Steper.GetNextStep() < Steper.GetCountSteps()){
			alert('Остались не выполненные действия');
			return false;
		}
		if (Calculator.CalculationProcess){
			alert('Дождитесь окончания расчета стоимости');
			return false;
		}

		if (Headinger.Forms.Activ == 6){
			if (this.CreateHoliday()){
				return this.FormSave();
			} else return false;
		}

		if (Headinger.Forms.Activ == 9){
			if (this.CreateAdsOnRouts()){
				return this.FormSave();
			} else return false;
		}

		this.AddDataToForm();
		Headinger.ViewSaveForm(bView);
		if (bView) PreLoader.ShowPreloads('preload-black');
		else PreLoader.HidePreloads('preload-black');
        return true;
	}

	// быстрое сохранение ролика на маршруте
	this.CreateAdsOnRouts = function(){
		var AdsFile = $('#OuchMy #AdsFileOK').html();
		var Phone	= $('#OuchMy #itsphone').val();
		if (AdsFile.length <= 0){
			alert('Выберите файл');
			return false;
		} else if (Phone.length <= 0){
			alert('Задайте контактный телефон');
			return false;
		}

		$('#' + Headinger.Tags.SaveForm).append('<input type="hidden" name="phone" value="' + Phone + '" />');
		var RoutsData = Router.GetRoutsData('Selected');
		$('#RoutListHide').val(RoutsData.sRoutsNumStr);
		$('#DateBeginHide').val($('#StartCompany').val());
		$('#CountWeekHide').val($('#LengthCompany').val());
		return true;
	}

	// быстрое сохранение поздравления
	this.CreateHoliday = function(){
		var sValue = $('#textholiday').val();
		if (sValue.length <= 0){
			alert('Наберите текст поздравления');
			return false;
		}
		$('#text4holiday').val(sValue);
		var RoutsData = Router.GetRoutsData('Selected');
		$('#RoutListHide').val(RoutsData.sRoutsNumStr);
		$('#DateBeginHide').val($('#StartCompany').val());
		$('#CountWeekHide').val($('#LengthCompany').val());
		return true;
	}

	// установка даты окончания рк
	this.SetNewDateCamp = function(){
		BaseObject.SetEndDate(this.Tags.StartCompany, this.Tags.LengthCompany, this.Tags.EndCompany);
		var NewLength = parseInt($('#' + this.Tags.LengthCompany).val());
		if (this.LengthCompany != NewLength){
			this.LengthCompany = NewLength;
			//this.Calculation();
		}

        Socket.Send('SetNewDate[date]=' + Selectors.Get(this.Tags.StartCompany).val() + '&SetNewEndDate[date]=' + Selectors.Get(this.Tags.EndCompany).html());
	}

	// выбор типа ролика
	this.CheckHeading = function(oTag){
		Headinger.CheckTypeClip(oTag);
		// следующий шаг
		Steper.AcceptStep(3);
		Steper.Step();
		var sLengthCompany 			= '';
		this.iMaxCountSelectedRoute = 1000;
		// задание длинны
		if (oTag.value == 4) {
			sLengthCompany = '<option value="26">26 нед.</option><option value="52">52 нед.</option>';
		} else if (oTag.value == 6 || oTag.value == 9) {
			sLengthCompany = '<option value="1">1 нед.</option>';
			this.iMaxCountSelectedRoute = 1;
		} else {
			sLengthCompany = '<option value="12">12 нед.</option><option value="26">26 нед.</option>';
		}
		$('#' + this.Tags.LengthCompany).html(sLengthCompany);
		Router.LimitationRouts(this.iMaxCountSelectedRoute);
		this.SetNewDateCamp();
		this.Calculation();
	}

	// переключение выдов поиска
	this.ViewSearchSort = function(){
		var sMetro = ($('#SearchOnMetro').attr('checked')) ? 'inline' : 'none';
		var s4Str  = ($('#SearchOnMetro').attr('checked')) ? 'none' : 'inline';
		$('#SearchOnMetroSel').css('display', sMetro);
		$('#Str4Search').css('display', s4Str);
		$('#SeachButton').css('display', s4Str);
	}

	// поиск по значению пользователя
	this.SearchOnUserQuest = function(sValue){
		if ($('#SearchOnRouts').attr('checked') || $('#SearchAllOnRouts').attr('checked')){
			BaseObject.SimpleAjaxQuest('SearchRouts.php', 'value=' + sValue, 'eval(msg); Interface.AddRouts(aResult);', "PreLoader.ShowPreloads('" + this.sLoadRout + "');", "alert('Ошибка!'); " + "PreLoader.HidePreloads('" + this.sLoadRout + "');");
            Socket.Send('SearchRouts[numbers]=' + sValue);
		} else if ($('#SearchRandomRouts').attr('checked')){
			BaseObject.SimpleAjaxQuest('RandomSearchRouts.php', 'value=' + sValue, 'eval(msg); Interface.AddRouts(aResult); Synchronizer.SendRouts();', "PreLoader.ShowPreloads('" + this.sLoadRout + "');", "alert('Ошибка!'); " + "PreLoader.HidePreloads('" + this.sLoadRout + "');");
		} else {
			Maper.SearchOnAddress(sValue, 'CheckPoint');
            Socket.Send('SearchOnAddress[address]=' + sValue);
		}
	}

	// проверка полученной точки
	this.CheckPoint = function(oPoint, sValue){
		if (oPoint){
			//this.DropZonesOnMap();
			Maper.ShowAreaRoundDot(oPoint);
			this.SearchRoutInZoneOnMap();
		} else {
			alert(sValue + " не найдено");
		}
	}

	// клик по фильтру
	this.ClickOnFiltr = function(oTag){
		Router.ClickOnFiltr(oTag);
		Router.ReDriveAllScrollRouts();
	}

	// скролинг маршрутов
	this.Scroll = function(oTag){
		var sTarget = (oTag.id.charAt(0) == 'f') ? 'Finded' : 'Selected';
		var iCount  = 0;
		switch(oTag.id.charAt(1) + oTag.id.charAt(2)){
			case 'up':
				iCount -= 5;
				break;
			case 'dw':
				iCount += 5;
				break;
		}

		Router.Scroll(sTarget, iCount);
	}

	// функция обрабатывает клик мыши на маршрут
	this.RouteMouseClick = function(iID){
        if (this.StopRouteMouseClick) return false;
		var sColor = '';
		// если уже выбранно
		if (Router.aRoutsInfo[iID]['Selected']){
			Router.UnSelectRoute(iID);
			sColor = this.sColorFindedRoutOnMap;
		} else if (Router.aRoutsInfo[iID]['Finded']){
			if (this.iMaxCountSelectedRoute <= Router.Routs.Selected.length){
				alert('Выбранно максимально возможное количество маршрутов');
				return false;
			}
			Router.SelectRoute(iID);
			sColor = this.sColorSelectedRoutOnMap;
		} else return false;
		Maper.SetLineColor(iID, sColor);
		Maper.SetLineMouseOut(iID, 'Maper.SetLineColor(' + iID + ', "' + sColor + '");');
		Router.ActionViewRouteList();
		Maper.CloseInfoWindow();
		Router.SetCountRoutsValueOnPage();

        Socket.Send('RouteMouseClick[id]=' + iID);

		if (Router.Routs.Selected.length > 0) Steper.AcceptStep(2);
		else Steper.UnAcceptStep(2);
		Steper.Step();
		this.Calculation();
		Calcer.Calculate();
        return true;
	}

	// отображение фильра
	this.ViewFiltrs = function(){
		Router.ViewFiltrs();
		Router.ActionViewRouteList();
	}

	// очистить карту от всех маршрутов
	this.ClaerMap = function(){
		this.DropSelectedRouts();
		this.DropFindedRouts();
		Router.SetCountRoutsValueOnPage();
	}

	// удалить найденные маршруты
	this.DropFindedRouts = function(){
		// удаление маршрутов с карты
		Maper.DropLineOnMap(Router.aRoutsInfo, 'Finded');
		// очистка списка найденых маршрутов
		Router.ClearRouts('Finded');
		Router.SetCountRoutsValueOnPage();
		// если небыло выбрано маршрутов
		if (Router.Routs.Selected.length <= 0){
			Steper.UnAcceptStep(1);
			Steper.Step();
		}
	}

	// удалить выбранные маршруты
	this.DropSelectedRouts = function(){
		Calculator.CalculationProcess = true;
		$('.' + Router.Classes.Selected).click();
		Calculator.SetData({ Money: 0, NDS: 0, CountContacts: 0, Coverage: 0 }, false);
		Calculator.NeedCalculation = false;
		Calculator.CalculationProcess = false;
	}

	// удаление зон со страницы
	this.DropZonesOnMap = function(){
		Maper.DropZonesOnMap();
		Maper.AddNewZone();
		Blinker.StopBlink("ShowRoutsZone");
	}

	// поиск маршрутов в выделенной зоне
	this.SearchRoutInZoneOnMap = function(){
		var aCoordZone = Maper.GetZone();
		BaseObject.SimpleAjaxQuest('map/RouteLoad.php', 'value=' + $.json.encode(aCoordZone), 'eval(msg); Interface.AddRouts(aResult);', "PreLoader.ShowPreloads('" + this.sLoadRout + "');", "alert('Ошибка!'); " + "PreLoader.HidePreloads('" + this.sLoadRout + "');");
	}

	// добавить маршруты
	this.AddRouts = function(aResult){
		// переcтает мигать кнопка
		Blinker.StopBlink("ShowRoutsZone");
		// отмена показа подсказки для карты
		Helper.Prohibit(Maper.Tag4Map);
		// удаление маршрутов с карты
		this.DropFindedRouts();
		// загрузка найденных маршурутов
		Router.UpdateRouts(aResult);
		// отфильтровать маршруты
		Router.SkipRoutsThroughFilter();
		// заполнение карты маршрутами
		this.AddRoutsOnMap(aResult);
		// нанести маршруты и данные о них на страницу
		Router.PutRoutsDataOnPage();
		// скрыть предзагрузщик
		PreLoader.HidePreloads(this.sLoadRout);
		// следующий шаг
		Steper.AcceptStep(1);
		Steper.Step();
	}

	// наносит найденные маршруты на карту
	this.AddRoutsOnMap = function(aResult){
		for (iNum in aResult){
			iNum = parseInt(iNum);
			if (aResult[iNum] == undefined || aResult[iNum].aCoord.length == 0) continue;

			Maper.AddLineOnMap(aResult[iNum].iID, aResult[iNum].aCoord, this.sColorFindedRoutOnMap, 'Interface.RouteMouseClick', 'Interface.RouteOnMapMouseOver', 'Interface.RouteOnMapMouseOut');
			var iCenterLine = Math.round(aResult[iNum].aCoord.length / 2);
            if (aResult[iNum].aCoord[iCenterLine] != undefined)
                Router.SetPoint(aResult[iNum].iID, Maper.GetPoint(aResult[iNum].aCoord[iCenterLine][0], aResult[iNum].aCoord[iCenterLine][1]));

			/***/



		}
	}

	// функция обрабатывает вход мыши на маршрут
	this.RouteOnMapMouseOver = function(iID){
		Maper.SetLineColor(iID, this.sColorHoverRoutOnMap);
		Maper.OpenInfoWindow(Router.aRoutsInfo[iID]['oPoint'], this.GetRoutInfoHTML(iID));
	}

	// функция обрабатывает выход мыши c маршрут
	this.RouteOnMapMouseOut = function(iID){
		var sColor = (Router.aRoutsInfo[iID]['Finded']) ? this.sColorFindedRoutOnMap : this.sColorSelectedRoutOnMap;
		Maper.SetLineColor(iID, sColor);
		Maper.CloseInfoWindow();
	}

	// получить текст для окна информации
	this.GetRoutInfoHTML = function(iID){
		var aRoute = Router.GetRouteInfo(iID);
		if (aRoute['sRout'] == undefined) return '';
		return '<div class="fs10 txtlef cdrk"><div class="w100p" style="text-align: center; font-size: 16px; font-weight: bold;"><b>Маршрут № ' + aRoute['sRout'] + '</b></div>' + (this.InfoWithMonitors ? 'Мониторов ' + aRoute['iCars'] + ' шт.<br />' : '') + ((this.InfoWithMoney) ? '<br />' + (aRoute['sCategory'] == 'D' ? 'Сервисные платежи согласно расчету<br /><br />' : 'Сервисный платеж в месяц: ' + (aRoute['sCategory'] == 'A' ? '1850 р.' : (aRoute['sCategory'] == 'B' ? '4625 р.' : '8325 р.')) + '<br />6 месяцев: ' + (aRoute['sCategory'] == 'A' ? Math.round(1850 * 6.5) + ' р.' : (aRoute['sCategory'] == 'B' ? Math.round(4625 * 6.5) + ' р.' : Math.round(8325 * 6.5) + ' р.')) + '<br /><br />') : '<br />') + aRoute['sKP1'] + '<br />' + aRoute['sKP2'] + '<br /></div>';
	}

	// обработка клика по карте
	this.ClickOnMap = function(overlay, point){
		Maper.AddDot(overlay, point);
		if (point){
			if (Maper.Markers[Maper.PolyCount].length >= 2){ Blinker.Blink("ShowRoutsZone"); }
			else if (Maper.Markers[Maper.PolyCount].length < 2) Blinker.StopBlink("ShowRoutsZone");
            Socket.Send('SetClickOnMap[x]=' + point.x + '&SetClickOnMap[y]=' + point.y);
		}
	}

	// позиционирование кнопок на карте
	// вход: 	iWindowWidth - ширина экрана
	this.ButtonOnMapPosition = function(iWindowWidth){
		// работа с выделением
		$('#Zone4RoutTitle').css('left',  	 (iWindowWidth - this.WidthMinus4Map - 243 + "px"));
		$('#AddZone4Rout').css('left',  	 (iWindowWidth - this.WidthMinus4Map - 243 + "px"));
		$('#ClearAllZone4Rout').css('left', (iWindowWidth - this.WidthMinus4Map - 187 + "px"));
		// кнопка с маршрутами
		$('#ShowRoutsTitle').css('left', (iWindowWidth - this.WidthMinus4Map - 125 + "px"));
		$('#ShowRoutsZone').css('left',  (iWindowWidth - this.WidthMinus4Map - 125 + "px"));
		$('#DelRoutsZone').css('left',   (iWindowWidth - this.WidthMinus4Map - 69 + "px"));
	}

	// изменение размера страницы
	this.ReSizePage = function(){
		var iWindowWidth = 640;
		var iWindowHeight = 480;

		if (self.innerHeight){ iWindowHeight = self.innerHeight; }
		else if (document.documentElement && document.documentElement.clientHeight){ iWindowHeight = document.documentElement.clientHeight; }
		else if (document.body){ iWindowHeight = document.body.clientHeight; }

		if (self.innerWidth){ iWindowWidth = self.innerWidth; }
		else if (document.documentElement && document.documentElement.clientWidth){ iWindowWidth = document.documentElement.clientWidth; }
		else if (document.body){ iWindowWidth = document.body.clientWidth; }

        this.MapSize(iWindowWidth);
		this.ButtonOnMapPosition(iWindowWidth);
	}

    this.WidthMinus4Map = 300;

    this.MapSize = function(iWindowWidth){
        Selectors.Get('map').css('width', (iWindowWidth - this.WidthMinus4Map) + 'px');
    }

	this.ChangeCountMonth = function(Obj, iCount){
		$('.CountMonthDigit').removeClass('DigitInMonths');
		$(Obj).addClass('DigitInMonths');
		$('.CountMonthOnAll').css('display', 'none');
		$('.CountMonthOn' + iCount).css('display', 'block');
	}

	this.HelpSearcher  = false;
	this.SearchOnRouts = false;

	this.UserPrintCharInSearcher = function(sStr){
		if (this.HelpSearcher == false) this.HelpSearcher = $('#HelpSearcher');
		if (this.SearchOnRouts == false) this.SearchOnRouts = $('#SearchOnRouts');
		if (this.SearchOnRouts.attr('checked') == false) return false;
		this.HelpSearcher.css('display', 'block');
		var sBody = '';
		var iMax  = 10;
		for (var i = 0; i < this.RoutsName.length; i++){
			if (this.StrInStr(sStr, this.RoutsName[i])){
				sBody += '<div onclick="Interface.SetUserRouteName(\'' + this.RoutsName[i] + '\');">' + this.RoutsName[i] + '</div>';
				iMax--;
				if (iMax == 0) break;
			}
		}
		this.HelpSearcher.html(sBody);
        return true;
	}

	this.SetUserRouteName = function(sName){
		$('#Str4Search').val(sName);
	}

	this.HideHelp4Searcher = function(){
		setTimeout("Interface.HelpSearcher.css('display', 'none');", 250);
	}

	this.StrInStr = function(sStr, sTarg){
		for (var i = 0; i < sStr.length; i++){
			if (sStr.charAt(i) != sTarg.charAt(i)) return false;
		}
		return true;
	}
}

// функция обрабатывающая клик по карте
function ClickOnFuckingMap(overlay, point){
	eval('Interface.ClickOnMap(overlay, point);');
}

var Interface = new Interface();

Helper.AddHelper('map', 'Выделите область рекламной кампании<br /> и нажмите на "Найти маршруты"');
Helper.AddHelper('HowSearch', 'Поиск маршрутов для рекламной кампании Вы можете осуществить любым из 5-и способов:<br /><br />1. Ввести адрес в строку поиска<br />2. Ввести номер маршрута в строку поиска (если маршрут не появился на карте, значит он не оборудован мониторами)<br />3. Выбрать станцию метро<br />4. Нанести все маршруты<br />или<br />5. Сразу выделить интересующую Вас область рекламной кампании на карте и нажать кнопку «Добавить маршруты».');
Helper.AddHelper('WhatIsCateg', 'Стоимость размещения в коммерческих рубриках зависит от категории маршрута.<br />Категории отличаются количеством мониторов на маршруте.<br /><br />В категории «I» 1-3 монитора. Стоимость размещения  на 4 недели - 2000 руб.*<br />В категории «II»  4-6 монитора. Стоимость размещения на 4 недели - 5000 руб.*<br />В категории «III» 7-12 монитора. Стоимость размещения на 4 недели - 8000 руб.*<br />В категория «IV»  более 12 мониторов. Стоимость размещения рассчитывается<br />от конкретного количества мониторов на маршруте по цене<br />стандартного размещения в рекламных блоках.*<br /><br />* - минимальный срок размещения - 3 месяца');
Helper.AddHelper('SelRout', 'Кликните для того, чтобы выбрать маршрут');
Helper.AddHelper('DelRout', 'Кликните для того, чтобы отменить выбор маршрута');
Helper.AddHelper('SelectAllRouts', 'Выбрать все маршруты');

Headinger.LoadClip('1', '<object id="videoplayer1005" type="application/x-shockwave-flash" data="http://marshrut.tv/flash/uppod.swf" width="240" height="192"><param name="wmode" value="opaque"><param name="bgcolor" value="#ffffff" /><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="movie" value="http://marshrut.tv/flash/uppod.swf" /><param name="flashvars" value="comment=Объявления на маршруте&amp;st=2iob3gRLvazh3IyR3IwbvIoavak8UfyRvcyb6xW43NJa2xo4013MyjtavIolGArr&amp;file=2iob3gRLvazh3IyR3IwbvIoavak8UfyRvak8GHJLUjnbtCm50iUr&amp;poster=http://marshrut.tv/flash/flv/ob240.jpg&amp;redirect=2iob3gRLvazh3IyR3IwbvIoavayL0Io40ITLG544GNsatCsbOSsr" /></object>');
Headinger.LoadClip('3', '<object id="videoplayer1003" type="application/x-shockwave-flash" data="http://marshrut.tv/flash/uppod.swf" width="240" height="192"><param name="wmode" value="opaque"><param name="bgcolor" value="#ffffff" /><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="movie" value="http://marshrut.tv/flash/uppod.swf" /><param name="flashvars" value="comment=Рубрика 24 часа&amp;st=2iob3gRLvazh3IyR3IwbvIoavak8UfyRvcyb6xW43NJa2xo4013MyjtavIolGArr&amp;file=2iob3gRLvazh3IyR3IwbvIoavak8UfyRvak8GHsNyFsNygABk5Wa&amp;redirect=2iob3gRLvazh3IyR3IwbvIoavayL0Io40ITLG544GNsaySsztSsr" /></object>');
Headinger.LoadClip('4', '<object id="videoplayer1006" type="application/x-shockwave-flash" data="http://marshrut.tv/flash/uppod.swf" width="240" height="192"><param name="wmode" value="opaque"><param name="bgcolor" value="#ffffff" /><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="movie" value="http://marshrut.tv/flash/uppod.swf" /><param name="flashvars" value="comment=Полезные телефоны&amp;st=2iob3gRLvazh3IyR3IwbvIoavak8UfyRvcyb6xW43NJa2xo4013MyjtavIolGArr&amp;file=2iob3gRLvazh3IyR3IwbvIoavak8UfyRvak8GHJbkxVNygABk5Wa&amp;poster=http://marshrut.tv/flash/flv/tel240.jpg&amp;redirect=2iob3gRLvazh3IyR3IwbvIoavayL0Io40ITLG544GNsayHsztHsr" /></object>');
Headinger.LoadClip('5', '<object id="videoplayer1007" type="application/x-shockwave-flash" data="http://marshrut.tv/flash/uppod.swf" width="240" height="192"><param name="wmode" value="opaque"><param name="bgcolor" value="#ffffff" /><param name="allowFullScreen" value="true" /><param name="allowScriptAccess" value="always" /><param name="movie" value="http://marshrut.tv/flash/uppod.swf" /><param name="flashvars" value="comment=Меню на маршруте&amp;st=2iob3gRLvazh3IyR3IwbvIoavak8UfyRvcyb6xW43NJa2xo4013MyjtavIolGArr&amp;file=2iob3gRLvazh3IyR3IwbvIoavak8UfyRvak8GHJMkxmzf1nbtCm50iUr&amp;poster=http://marshrut.tv/flash/flv/menu_240_1.jpg&amp;redirect=2iob3gRLvazh3IyR3IwbvIoavayL0Io40ITLG544GNsayNsztNsr" /></object>');
Headinger.LoadClip('6', '');

Headinger.LoadFormsType('1', 7, 15);
Headinger.LoadFormsType('3', 7, 15);
Headinger.LoadFormsType('4', 7, 15);
Headinger.LoadFormsType('5', 7, 15);
Headinger.LoadFormsType('7', 7, 15);
Headinger.LoadForm4Type('1', Headinger.Tags.SaveForm, 'main');
Headinger.LoadForm4Type('1', Headinger.Tags.SaveFormRe, '1');
Headinger.LoadForm4Type('4', Headinger.Tags.SaveForm, 'main');
Headinger.LoadForm4Type('4', Headinger.Tags.SaveFormRe, '4');
Headinger.LoadForm4Type('3', Headinger.Tags.SaveForm, 'main');
Headinger.LoadForm4Type('3', Headinger.Tags.SaveFormRe, '3');
Headinger.LoadForm4Type('5', Headinger.Tags.SaveForm, 'main');
Headinger.LoadForm4Type('5', Headinger.Tags.SaveFormRe, '5');
Headinger.LoadForm4Type('7', Headinger.Tags.SaveForm, 'discounts_in_city');
Headinger.LoadFormsType('6', 6, 15);
Headinger.LoadForm4Type('6', Headinger.Tags.SaveForm, 'holiday');
Headinger.LoadFormsType('9', 6, 15);
Headinger.LoadForm4Type('9', Headinger.Tags.SaveForm, '9');


Steper.InsertHelpLine(1, 'Шаг 1. Поиск');
Steper.InsertHelpLine(2, 'Шаг 2. Выбор маршрутов');
Steper.InsertHelpLine(3, 'Шаг 3. Выбор рубрики');
Steper.InsertHelpLine(4, 'Заполните заявку');

Former.AddFormType('1', 'AcceptAfert', 'checkbox', 'Подтвердите согласие с офертой');
Former.AddFormType('3', 'AcceptAfert', 'checkbox', 'Подтвердите согласие с офертой');
Former.AddFormType('4', 'AcceptAfert', 'checkbox', 'Подтвердите согласие с офертой');
Former.AddFormType('5', 'AcceptAfert', 'checkbox', 'Подтвердите согласие с офертой');
Former.AddFormType('7', 'AcceptAfert', 'checkbox', 'Подтвердите согласие с офертой');
FullRC = function(){
	this.URL				= 'http://client.marshrut.tv/';
	this.TagID 				= {
								Ads: 'Ads'
								};
	this.Classes			= {
								ClipsLength: 'Lengths'
								}
	this.ClipFreeqSelect 	= '';
	this.ClipLengthSelect 	= '';
	this.ClipWeeksSelect 	= '<option value="1">1</option>';
	this.AdNumer			= 1;
	
	this.AddAd = function(){
		jQuery('#' + this.TagID.Ads).append(this.GetAdHTML());
		this.AdNumer++;
	}
	
	this.GetAdHTML = function(){
		return '<tr id="ad_' + this.AdNumer + '"><td align="center"><select class="w100 freeq" id="' + this.AdNumer + '" name="ad_freeq_' + this.AdNumer + '" onchange="Calcer.Calculate();">' + this.ClipFreeqSelect + '</select></td><td align="center"><select class="w100 length" id="' + this.AdNumer + '" name="ad_length_' + this.AdNumer + '" onchange="Calcer.Calculate();">' + this.ClipLengthSelect + '</select></td><td align="center"><img src="/pictures/delete.a.gif" onclick="jQuery(\'#ad_' + this.AdNumer + '\').remove(); Calcer.Calculate();" style="cursor: pointer;" alt="Удалить ролик" title="Удалить ролик" /></td></tr>';
	}
	
	this.CreateLengthHTML = function(iNum){
		this.ClipWeeksSelect 	= '';
		for (var i = 1; i <= iNum; i++) this.ClipWeeksSelect += '<option value="' + i + '">' + i + '</option>';
		jQuery('.' + this.Classes.ClipsLength).html(this.ClipWeeksSelect);
	}
	
	this.Save = function(){
		var sValues = 'length=' + parseInt(jQuery("#LengthCompany").val()) + '&start=' + jQuery("#StartCompany").val() + '&title=' + jQuery("#TitleCompany").val() + '&client=' + parseInt(jQuery("#ClientCompany").val());
		var Routs = Router.GetRoutsData('Selected');
		for (var i = 0; i < Routs.ids.length; i++) sValues += '&routs[]=' + Routs.ids[i];
		jQuery('#' + FullRC.TagID.Ads + ' select.freeq').each(function(){ sValues += '&ad_freeq[]=' + parseInt(jQuery(this).val()); });
		jQuery('#' + FullRC.TagID.Ads + ' select.length').each(function(){ sValues += '&ad_length[]=' + parseInt(jQuery(this).val()); });
		
		BaseObject.SimpleAjaxQuest('campaign/FullCreate.php', sValues, 'FullRC.AfterSave(msg);', '', "");
	}
	
	this.AfterSave = function(msg){
		eval(msg);
		if (Request.error != undefined) alert(Request.error);
		else {
			alert(Request.message);
			window.location.href = this.URL + 'campaign.php?id=' + Request.id;
		}
	}
}

var FullRC = new FullRC();

/**
 * Синхронизатор действий на карте.
 */
Synchronizer = function(){
	// Таймаут запросов синхронизации
	//this.TimeOut 	= 3000;
	// Набор объектов отслеживания
	//this.Somtings	= Array();
	// статусы
	this.Statuses	= { 'off': 1, 'error': 2, 'load': 3, 'on': 4 };
    // статус работы синхронизатора
	this.Status	 = 'off';
	// идентификаторы
	this.IDs        = {
                          Title: 'TitleCompany'
                        , Start: 'StartCompany'
                        , Length: 'LengthCompany'
                        , End: 'EndCompany'
                        , Monitors: 'Monitors'
                        , AverageMonitorsPerWeek: 'AverageMonitorsPerWeek'
                        , Ads: 'Ads'
                        , Cost: 'Money'
                        , NDS: 'NDS'
                        , Exposures: 'Exposures'
                        , AverageExposures: 'AverageExposures'
                        , Coverage: 'Coverage'
                        , CPT: 'CPT'
                        , GRP: 'GRP'
                        , CPP: 'CPP'
                        , Money: 'Money'
                        };
    
	// данные полученные
	//this.Request	= {};
	
	// запуск синхронизации
	this.Power		= function(){
        if (this.Status == 'load') return false;
		if (this.Status == 'on'){
			this.SetStatus('off');
            this.StopSocket();
		} else {
			this.SetStatus('load');
			this.StartSocket();
		}
        return true;
	}

    // установить статус
	this.SetStatus = function(iStatus){
		this.Status = iStatus;
		Selectors.Get('StatusIcon').attr('src', '/pictures/status_' + this.Statuses[iStatus] + '.gif');
	}

    // старт сокета
	this.StartSocket = function(){
        if (Socket.Connect()) this.SetStatus('on');
        else this.SetStatus('error');
        
        var SyID = parseInt(Selectors.Get('ServerID').val());
        if (SyID > 0){
            Socket.Client = SyID;
        }
	}

    // стоп сокета
    this.StopSocket = function(){
        Socket.Disconnect();
    }

    this.SendStackData = function(){
        Socket.Send('SetNewTitle[title]=' + Selectors.Get(Synchronizer.IDs.Title).val()
                   + '&SetNewDate[date]=' + Selectors.Get(Synchronizer.IDs.Start).val()
                   + '&SetNewEndDate[date]=' + Selectors.Get(Synchronizer.IDs.End).html()
                   + this.GetDataAfterCalculate4Send()
                   + this.GetDataRouts4Send());
    }

    this.SendRouts = function(){
        Socket.Send(this.GetDataRouts4Send());
    }

    this.GetDataRouts4Send = function(){
        var Routs = Router.GetRoutsData('Selected');
        var sIDs  = '', sSel = '';
        var i     = 0;
        for (i = 0; i < Routs.ids.length; i++){
            sIDs += Routs.ids[i] + ',';
            sSel += Routs.ids[i] + ',';
        }

        Routs = Router.GetRoutsData('Finded');
        for (i = 0; i < Routs.ids.length; i++){
            sIDs += Routs.ids[i] + ',';
        }

        return '&SetRouts[finded]=' + sIDs + '&SetRouts[selected]=' + sSel
    }

    this.SendDataAfterCalculate = function(){
        Socket.Send(this.GetDataAfterCalculate4Send());
    }

    this.GetDataAfterCalculate4Send = function(){
        return '&SetNewLength[length]=' + Selectors.Get(Synchronizer.IDs.Length).val()
             + this.GetData4Send()
             + '&SetMonitors[SetMonitors]=' + Selectors.Get(Synchronizer.IDs.Monitors).html()
             + '&AverageMonitorsPerWeek[AverageMonitorsPerWeek]=' + Selectors.Get(Synchronizer.IDs.AverageMonitorsPerWeek).html()
             + '&SetMoney[Money]=' + Selectors.Get(Synchronizer.IDs.Money).html()
             + '&SetGRP[GRP]=' + Selectors.Get(Synchronizer.IDs.GRP).html()
             + '&SetCPP[CPP]=' + Selectors.Get(Synchronizer.IDs.CPP).html()
             + '&SetCPT[CPT]=' + Selectors.Get(Synchronizer.IDs.CPT).html()
             + '&SetCoverage[Coverage]=' + Selectors.Get(Synchronizer.IDs.Coverage).html()
             + '&SetExposures[Exposures]=' + Selectors.Get(Synchronizer.IDs.Exposures).html()
             + '&SetNDS[NDS]=' + Selectors.Get(Synchronizer.IDs.NDS).html()
             + '&SetAverageExposures[AverageExposures]=' + Selectors.Get(Synchronizer.IDs.AverageExposures).html()
    }

    // установка значения номера
    this.SetServer = function(Data){
        Selectors.Get('ServerID').html('Номер синхронизации: ' + Data.server);
        Socket.Server = Data.server;
        //Selectors.Get('ServerID').html('server = ' + Data)
        this.SendStackData();

    }

    this.RouteMouseClick = function(Data){
        var sColor = '';
		if (Router.aRoutsInfo[Data.id]['Selected']){
			Router.UnSelectRoute(Data.id);
			sColor = this.sColorFindedRoutOnMap;
		} else if (Router.aRoutsInfo[Data.id]['Finded']){
			if (this.iMaxCountSelectedRoute <= Router.Routs.Selected.length){
				alert('Выбранно максимально возможное количество маршрутов');
				return false;
			}
			Router.SelectRoute(Data.id);
			sColor = this.sColorSelectedRoutOnMap;
		} else return false;
		Maper.SetLineColor(Data.id, sColor);
		Maper.SetLineMouseOut(Data.id, 'Maper.SetLineColor(' + Data.id + ', "' + sColor + '");');
		Router.ActionViewRouteList();
		Maper.CloseInfoWindow();
		Router.SetCountRoutsValueOnPage();
        return true;
    }

    this.SetClickOnMap = function(Data){
        var oSquare   = new GIcon();
        oSquare.image = "pictures/dot_map_blue.png";
        Maper.AddIcon(oSquare);
		
        var oPoint = new GLatLng(Data.y, Data.x);
        Maper.AddMarker(oPoint, oSquare);

        //Maper.AddDot(null, eval(Data.point));
    }

    this.MaperAddNewZone = function(){
        Maper.AddNewZone();
    }

    this.ClaerMap = function(){
        Interface.ClaerMap();
    }

    this.SearchRoutInZoneOnMap = function(){
        Interface.SearchRoutInZoneOnMap();
    }

    this.DropZonesOnMap = function(){
        Interface.DropZonesOnMap();
    }

    // установка значения номера
    this.SetClient = function(Data){
        Socket.Client = Data.client;
        //Selectors.Get('ClientID').html('Client = ' + Data)
    }

    this.SelectSRouts = function(Data){
        Data = Data.split(',');
        for (var i = 0; i < Data.length; i++){
            if (parseInt(Data[i]) > 0) this.SelectSRout(Data[i]);
        }
    }

    this.SelectSRout = function(i){
        Interface.RouteMouseClick(i);
    }

    this.DeSelectSRout = function(i){
        Interface.RouteMouseClick(i);
    }

    this.SetRouts = function(sValue){
        if (sValue.finded.length > 0 || parseInt(sValue.finded) > 0)
            BaseObject.SimpleAjaxQuest('map/SearchRoutsByID.php', 'id=' + sValue.finded, 'eval(msg); Interface.AddRouts(aResult); Synchronizer.SelectSRouts("' + sValue.selected + '");', "PreLoader.ShowPreloads('loading');", "alert('Ошибка!'); PreLoader.HidePreloads('loading');");
    }

    this.SetMoney = function(Data){
        Selectors.Get(Synchronizer.IDs.Money).html(Data.Money);
    }
    
    this.SetGRP = function(Data){
        Selectors.Get(Synchronizer.IDs.GRP).html(Data.GRP);
    }
    
    this.SetCPP = function(Data){
        Selectors.Get(Synchronizer.IDs.CPP).html(Data.CPP);
    }

    this.SetCPT = function(Data){
        Selectors.Get(Synchronizer.IDs.CPT).html(Data.CPT);
    }

    this.SetCoverage = function(Data){
        Selectors.Get(Synchronizer.IDs.Coverage).html(Data.Coverage);
    }

    this.SetAverageExposures = function(Data){
        Selectors.Get(Synchronizer.IDs.AverageExposures).html(Data.AverageExposures);
    }

    this.SetExposures = function(Data){
        Selectors.Get(Synchronizer.IDs.Exposures).html(Data.Exposures);
    }

    this.SetNDS = function(Data){
        Selectors.Get(Synchronizer.IDs.NDS).html(Data.NDS);
    }

    this.AverageMonitorsPerWeek = function(Data){
        Selectors.Get(Synchronizer.IDs.AverageMonitorsPerWeek).html(Data.AverageMonitorsPerWeek);
    }

    this.SetMonitors = function(Data){
        Selectors.Get(Synchronizer.IDs.Monitors).html(Data.Monitors);
    }

    this.SetNewTitle = function(sTitle){
        Selectors.Get(Synchronizer.IDs.Title).html(sTitle.title);
    }

    this.SetNewDate = function(sDate){
        Selectors.Get(Synchronizer.IDs.Start).html(sDate.date);
    }

    this.SetNewEndDate = function(sDate){
        Selectors.Get(Synchronizer.IDs.End).html(sDate.date);
    }

    this.SetNewLength = function(iLength){
        Selectors.Get(Synchronizer.IDs.Length).html(iLength.length);
    }

    this.SearchOnAddress = function(sAdres){
        Maper.SearchOnAddress(sAdres.address, 'CheckPoint');
    }

    this.RandomSearchRouts = function(sValue){
        BaseObject.SimpleAjaxQuest('RandomSearchRouts.php', 'value=' + sValue.count, 'eval(msg); Interface.AddRouts(aResult);', "PreLoader.ShowPreloads('loading');", "alert('Ошибка!'); PreLoader.HidePreloads('loading');");
    }

    this.SearchRouts = function(sValue){
        BaseObject.SimpleAjaxQuest('SearchRouts.php', 'value=' + sValue.numbers, 'eval(msg); Interface.AddRouts(aResult);', "PreLoader.ShowPreloads('loading');", "alert('Ошибка!'); PreLoader.HidePreloads('loading');");
    }

    this.AddAd = function(){
        FullRC.AddAd();
    }

    this.AddAds = function(Data){
        $('#Ads tr.ad').remove();
        Data.ad_freeq  = Data.ad_freeq.split(',');
        Data.ad_length = Data.ad_length.split(',');
        for (var i = 0; i < Data.ad_freeq.length; i++) $('#Ads').append('<tr class="ad"><td align="center">' + Data.ad_freeq[i] + '</td><td align="center">' + Data.ad_length[i] + '</td><td align="center"></td></tr>');
    }

    this.SendAdsData = function(){
        Socket.Send(this.GetData4Send());
    }

    this.GetData4Send = function(){
        var sValue = '&AddAds[ad_freeq]=';
        $('#Ads select.freeq').each(function(){ sValue += (parseInt($(this).val()) * 2) + ','; });
        sValue += '&AddAds[ad_length]=';
		$('#Ads select.length').each(function(){ sValue += parseInt($(this).val()) + ','; });
        return sValue;
    }
}

var Synchronizer = new Synchronizer();

// выполняет расчет стоимости с помощью ajax
AjaxCalculator = function(){
	// идет/нет процесс вычисления
	this.CalculationProcess = false;
	// необходимо еще раз пересчитать
	this.NeedCalculation 	= false;
	// ид тэгов формы
	this.Tags				= {
								  Money: 'Money'
								, NDS: 'NDS'
								, CountContacts: 'CountContacts'
								, Coverage: 'Coverage'
								, LengthCompany: 'LengthCompany'
								};
	this.CalculationData	= { Cars: Array() };
	
	// установка значений формы отражающий данные расчета
	this.SetData = function(aData, bClear){
		if (!bClear) jQuery('.LoadRaschet').css('display', 'none');
		
		//jQuery('#Money').html(aData.Money);
		//jQuery('#NDS').html(aData.NDS);
		//jQuery('#CountContacts').html(aData.CountContacts);
		jQuery('#Coverage').html(aData.Coverage);
		
		if (bClear){
			jQuery('.LoadRaschet').css('display', 'inline');
		} else {
			this.CalculationProcess = false;
			if (this.NeedCalculation){
				this.NeedCalculation 	= false;
				this.CalculationProcess	= false;
				this.Calculation(this.CalculationData.Cars);
			}
		}
	}
	
	// получение данных
	this.GetData = function(aCars){
		return 'iLengthCompany=' + jQuery('#' + this.Tags.LengthCompany).val() + '&iAllCars=' + aCars.iAllCars + '&iCarsWithComplexes=' + aCars.iCarsWithComplexes + '&aGroup[1]=' + aCars.A + '&aGroup[2]=' + aCars.B + '&aGroup[3]=' + aCars.C + '&aGroup[4]=' + aCars.D + '&iSelectedRubrics=' + ((jQuery('#TypeClip4').attr('checked')) ? 4 : 1);
	}
	
	// вычисление
	this.Calculation = function(aCars){
		if (this.CalculationProcess){
			this.CalculationData.Cars 	= aCars;
			this.NeedCalculation 		= true;
			return false;
		}
		
		this.CalculationProcess = true;
		// установка загрузки
		this.SetData({ Money: '', NDS: '', CountContacts: '', Coverage: 'Идет расчет' }, true);
		
		BaseObject.SimpleAjaxQuest('CampaingCalculate.php', this.GetData(aCars), 'eval(msg); AjaxCalculator.SetData(aResult, false);', '', "alert('Ошибка при расчете стоимости!'); AjaxCalculator.CalculationProcess = false;");
	}
}

var AjaxCalculator = new AjaxCalculator();
