/* Author: RBC SOFT


*/
Cufon.replace('.promo h2', {
				color: '-linear-gradient(#317C31, #195219)'	
	
}); 



jQuery(function() {
	//Fancybox для анонсов.
	fancyboxInit();
	
	//Ajax-пагинация для главной страницы.
	mainNewsPagination();
	
	
	$(".sectors-menu li a").hover(function() {
		$(this).parent().addClass("over");
	}, function() {
		$(this).parent().removeClass("over");
	});
	
	$("#navSecondary").tabs("div.tabs > div", { history: true, current:'active' });

		var mapBoxId = 'api-map';
	var map;
	// looking for the diw with #api-map
	if ($('#' + mapBoxId).length){ 
		
		GmapInstallation();
	}

	// imageStyling
	imageStyler($('div.ImageSet'));
});

// ImageStyler, you can check here http://test.newsite.dev.rbcsoft.ru/goals_and_solutions/project_info/index.php?project_name=novikom
function imageStyler($obj) {
	if ($obj == null || $obj == undefined) return false;

	var $_images = {src:'',width:'',height:'',alt:'',rel:''},
		output = '';

	$obj.each(function(i) {
		var $imgWrap = $(this);
		var $_imgs = $imgWrap.children('img');
		
		
		$_imgs.each(function() {
			var $_img = $(this);
			$_images = {
				src:   $_img.attr('src'),
				width: $_img.attr('width'),
				height:$_img.attr('height'),
				alt:   $_img.attr('alt'),
				rel:   $_img.attr('rel')
			}
			
			if ($_images.src.length)
			{
				output = '<figure><div class="window-wrapper">';
				output += '<div class="window-top"><span class="l"></span><span class="r"></span></div>';
				output += '<div class="window-content">';
				output += '<img src=' + $_images.src;
					if ($_images.width.length)
					{ output += ' width="' + $_images.width + '"'; }
					if ($_images.height.length)
					{ output += ' height="' + $_images.height + '"'; }
					if ($_images.alt.length)
					{ output += ' alt="' + $_images.height + '"'; }
					if ($_images.rel.length)
					{ output += ' rel="' + $_images.rel + '"'; }
				output += '/>'
				output +='</div>';
				output += '<div class="window-bottom"><span class="l"></span><span class="r"></span></div>';
				output += '</div></figure>';

				$imgWrap.before(output);
			} // if
		}); // each .ImagesSet > imgs

		$imgWrap.remove() //remove all .ImagesSet

	}); // each .ImageSet
} // function

// Add gmap script to the document
function GmapInstallation() {
	var script = document.createElement("script");
	script.src = "https://www.google.com/jsapi?key=ABQIAAAAHOJBR86a45BflQuhsFNB6xRy4By4xlIx5g4uJdQZYWVONtsCBBRjoClzAPqiXy3mUChVZguUy--ZIA&callback=GmapSettings";
	script.type = "text/javascript";
	document.getElementsByTagName("head")[0].appendChild(script);
}

// gmap settings
function GmapSettings() {
	google.load("maps", "2", {"callback" : mapLoaded});

}
// map loading and construct
function mapLoaded() {
	// default settings
	var mapId = 'api-map'; 
	var metro = ["55.70698,37.588488", "59.985436,30.300847", "56.297998,43.93625"],

		dirPanel = [],
		dir = [];

	//  map -- global varible; 
		map = new google.maps.Map2(document.getElementById(mapId));
		map.setCenter(new google.maps.LatLng(55.707554,37.593949), 16);
		map.setUIToDefault();
		map.disableScrollWheelZoom();

	// block for routing
	$('#' + mapId).after('<div id="routes">&nbsp;</div>');
	var $routeBox = $('#routes');

	// get coordinates from content
	var points = hotspots.latlng($("div.tabs > div"),'.geo');
	// to count the array size
	var counter = points.length;
	var marker = [];
	//set the markers & dirs to the map
	for (var i=0; i < counter ; i++ )
	{ 
//		$routeBox.append('<div id="route-'+ i +'"></div>');
//		dirPanel[i] = document.getElementById("route-" + i);

		marker[i] = markers.addMarkers(points[i].lat, points[i].lng);
		GEvent.addListener(marker[i], "click", function(){
				this.openInfoWindowHtml('<div class="popUp">' + $('div.tab:visible > div.info-map').html() + '</div>');
		});
		map.addOverlay(marker[i]);
//		GEvent.addListener(dir[i], "error", onGDirectionsLoandErrors);
	}//for
	onGDirectionsLoad();
// set map
	mapNavigation(window.location.hash, $('#block-351'),marker);

// waiting action for change location on the map
	$(window).bind('hashchange', function() {
		mapNavigation(window.location.hash, $('#block-351'),marker);
	});


} // gmap loaded
function onGDirectionsLoad(){
		var polyLineRoute = [];
//msk
		polyLineRoute[0] = new GPolyline.fromEncoded({color: "#FF0000", weight: 3, opacity:.5, points: "eo_sIefldFpDgLnDiKfBwFxDyTyDyDlCgN_GuFGX", levels: "BBBBBBBBB", zoomFactor: 32, numLevels: 3});
		polyLineRoute[1] = new GPolyline.fromEncoded({color: "#00FF00", weight: 3, opacity:.5, points: "qg_sIcoldFmQe_@@}BSmRnEyAxAaIfOhOhC{MwFmF", levels: "BBBBBBBBB", zoomFactor: 32, numLevels: 3});
//nvg
		polyLineRoute[2] = new GPolyline.fromEncoded({color: "#00FF00", weight: 3, opacity:.5, points: "c|rvIghbkGhKoQbA{Cz@mGf@aM_C{E_AsLwBqA", levels: "BBBBBBBB", zoomFactor: 32, numLevels: 3});
//spb
		polyLineRoute[3] = new GPolyline.fromEncoded({color: "#00FF00", weight: 3, opacity:.5, points: "u|bmJee}wDuEdCApABhEZzC`AfFf@dJtBvp@qATGqBw@L@R", levels: "BBBBBBBB", zoomFactor: 32, numLevels: 3});

		for (var i=0;i< polyLineRoute.length;i++)
		{
			map.addOverlay(polyLineRoute[i]);
		}

}
function onGDirectionsLoandErrors(){
			var message = '';
			if (this.getStatus().code == 500) {
				message = "Не удалось успешно обработать запрос маршрутов или геокодирования, однако точная причина сбоя неизвестна. Код Ошибки:" + this.getStatus().code;
			} else if(this.getStatus().code == 604) {
				message = "Не удалось вычислить направления между точками. Обычно это происходит из-за отсутствия доступного маршрута между двумя точками или данных о маршрутах в этом регионе. Код Ошибки: " + this.getStatus().code;
			} else if (this.getStatus().code == 610) {
				message = "Указанный ключ либо недопустим, либо не совпадает с доменом, для которого он был выдан. Код Ошибки: " + this.getStatus().code;
			} else 
			{
				message = "Не удалось установить причину ошибки. Код Ошибки: " + this.getStatus().code;
			}
			alert(message);
}
function mapNavigation(hash, $navTarget,marker) {
	var $li = $navTarget.find('li');
	var curId = 0,
		size = $li.length;

	// if one tab only
	if (size == 0) return false;

	if (hash) {
		curId = $li.find('a[href='+ hash +']').parent().index();
	} else {
		curId = 0; 
	}
	if (curId === -1)
	{
		curId = 0;
	}
/*	alert(curId);*/
	displayPoint(curId,marker[curId]);

} // navigation 

var hotspots = {
	latlng:function($containers,ClassWCoord) {
	 var _LatLng = [],
		 _Lat = 0,
		 _Lng = 0;
		$containers.each(function(i){
			_Lat = parseFloat($(this).find(".latitude").text());
			_Lng = parseFloat($(this).find(".longitude").text());
			/*_Lat = parseFloat($(this).find(ClassWCoord).text().split(',')[0]);
			_Lng = parseFloat($(this).find(ClassWCoord).text().split(',')[1]);*/
			_LatLng[i] = {lat:_Lat,lng:_Lng};
		
		});
	return _LatLng;
	}

/*	,
	html:function($containers,ClassWTeaser){
		var teaser = [];
		$containers.each(function(i){
			teaser[i] = $(this).find(ClassWTeaser).html();
		});
		return teaser;
	}*/


} // coordParser

// add map to the content-block and sets center of the map;

var markers = {
				addMarkers:function(Lat,Lang) {
							var image = new GIcon(G_DEFAULT_ICON);
							var imgWidth = 57;
							var imgHeight = 43;
								image.image='http://rbcsoft2009.dev.rbcsoft.ru/common/upload/rbc.png';
								image.iconSize=new GSize(imgWidth, imgHeight);
								image.shadow="";
								image.iconAnchor=new GPoint(parseInt((imgWidth - 21)/ 2),parseInt((imgHeight + 21)/ 2));
								image.imageMap=[0,0,0,imgHeight,imgWidth,imgHeight,imgWidth,0];

							var point = new GLatLng(Lat,Lang);
								marker = new GMarker(point, {icon: image});
							return marker;
				}
} // addMarkers

function displayPoint(id,marker){

	$('#routes > div#route-' + id).addClass('active').fadeIn();
	$('#routes > div:not(#route-'+ id +')').removeClass('active').hide();


	map.panTo(marker.getLatLng());

}

function cloneRecursion(obj){
	var newObj = {}, i;
	for(i in obj)
		newObj[i] = obj[i];
	return newObj;
}

//function translite


var ru2en = { 
	ru_str : "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя ", 
	en_str : ['A','B','V','G','D','E','JO','ZH','Z','I','J','K','L','M','N','O','P','R','S','T','U','F','H','C','CH','SH','SHH',String.fromCharCode(35),'I',String.fromCharCode(39),'JE','JU','JA','a','b','v','g','d','e','jo','zh','z','i','j','k','l','m','n','o','p','r','s','t','u','f','h','c','ch','sh','shh',String.fromCharCode(35),'i',String.fromCharCode(39),'je','ju','ja','_'], 
	translit : function(org_str) { 
    var tmp_str = ""; 
    for(var i = 0, l = org_str.length; i < l; i++) { 
      var s = org_str.charAt(i), n = this.ru_str.indexOf(s); 
      if(n >= 0) { tmp_str += this.en_str[n]; } 
      else { tmp_str += s; } 
    } 
    return tmp_str; 
  } 
}

function strip_tags(string) {
 return string.replace(/<\/?[^>]+>/gi, '');  
} 

function trim(string) {
 return string.replace (/(^\s+)|(\s+$)/g, "");
}



/**
 * edmitriev
 */

function fancyboxInit() {
	var
		_getTotalWidth = function() {
			var width = $(document).width();
			
			if ($("#fancybox-wrap").is(":visible")) {
				$("#fancybox-overlay, #fancybox-wrap").hide();
				width = $(document).width();
				$("#fancybox-overlay, #fancybox-wrap").show();
			}
			
			return width;
		};
	
	$(".headline ul li a").attr("rel", "news").fancybox({
		"navPosition" : "vertical",
		"showCloseButton" : false,
		"padding" : 0,
		"margin": 0,
		"overlayShow" : true,
		"overlayOpacity" : 0,
		"shadow" : false,
		"autoDimensions" : false,
		"position" : {
			"left" : 0,
			"top" : 85
		},
		"onStart" : function() {
			return {width : _getTotalWidth()};
		},
		"width" : _getTotalWidth(),
		"height" : 200
	});
	
	$(window).resize(function() {
		$("#fancybox-overlay, #fancybox-wrap, #fancybox-outer, #fancybox-content, #fancybox-content > div:first-child").width(_getTotalWidth());
	});
}

function mainNewsPagination() {
	var newsOnPage = 10;
	var newsContainer = $("#main .news-list");
	var newsList = $(newsContainer).find("ul");
	
	if (newsContainer.length && $(newsList).find("li").length >= newsOnPage) {
		$(newsContainer).append("<a class=\"more\" href=\"#more\"><b>Еще</b></a>");
		var moreLink = $(newsContainer).find("a[href='#more']");
		
		$(moreLink).attr("from", 2).click(function() {
			$(moreLink).addClass("loading");
			$.get("/common/ajax.php?page_id=1&area_id=3&from_3=" + $(moreLink).attr("from"), function(data) {
				var list = $(data).find("li");
				$(list).attr("new", true).hide();
				$(list).find("a").each(function() {
					$(this).attr("href", $(this).attr("href").split("&")[0]);
				});
				$(newsList).append(list);
				
				if (list.length >= newsOnPage) {
					$(moreLink).attr("from", parseInt($(moreLink).attr("from"), 10) + 1).removeClass("loading");
					
				} else {
					$(moreLink).remove();
				}
				
				$(newsContainer).find("li[new]").fadeIn("slow").removeAttr("new");
			});
			
			return false;
		});
	}
}

$("a[href$='#call']").each(function() {
	var linkParts = $(this).attr("href").split("#call");
	linkParts = linkParts[0].split("?");
	$(this).attr("href", linkParts[0] + "?theme=" + ($(this).attr("title") ? $(this).attr("title") : $(this).text()) + "#call");
});


/**
	 * Подключаем UniForm.
	 */
	$.getScript("/common/js/libs/jquery.uniform.min.js", function() {
		$("select").uniform();
		$("span.hider").each(function() {
			var elID = $(this).attr("rel");
			
			if (elID) {
				var el = $(elID);
				
				if (el.length) {
					$(this).hide(0, function() {
						$(el).show();
					});
				}
			}
		});
	});
