// JavaScript Document
/* IEHTML5 */
  document.createElement('header');
  document.createElement('nav');
  document.createElement('article');
  document.createElement('section');
  document.createElement('aside');
  document.createElement('footer');
/* IEHTML5 */

var counter, curlink;
var App = {
	init: function(){
	counter = yaCounter1253563 || false;
		App.initObjects();
		$('noindex').children(':first-child').unwrap();
		curlink = $('a.current-link').attr('href') || false;
		
		App.beforeOne();
		App.fire(document);
		App.afterOne();
		
		$(document).keydown(function(e){
			if(e.keyCode == 65 && e.ctrlKey && e.altKey){
				 $('#news-block').toggle();
				 if($('#news-block').is(':visible'))
				 	$.cookie('news',  'on');
				else $.cookie('news',  'off');
			}
		});
		$('#news-block')[$.cookie('news') == "off" ? 'hide' : 'show']();
	},
	
	clear : [],
	clearAll : function(){
		$.each(App.clear, function(i, el){
			el.call();
		});
	},
	change : [],
	changeAll : function(){
		$.each(App.change, function(i, el){
			el.call();
		});
	},
	
	/****
	*****  Функции инициализации
	*****/
	
	//Добавление обработчика
	readyHandlers: [],
	add : function(ready, rate, where){
		var where = where || this.readyHandlers;
		switch(typeof ready){
			case "object": 
				if(!ready.init) break;
				if(typeof ready.objects == "object") this.objects.push(ready);
				where.push({
					'f': ready.init,
					'scope': ready,
					'rate': rate || 0
				});
				break;
			case "function":
				where.push({
					"f": ready, 
					"scope": window,
					'rate': rate || 0
				});
				break;
			case "array":
				for(var index in ready)
					this.add(ready[index]);
		}
	},
	
	//Private. Добавление обработчика
	append : function(readyObj){
		this.readyHandlers.push(readyObj);
	},
	
	//fireReady
	fire : function(context, handlers){
		var handlers = handlers || this.readyHandlers;
		window.context = context || document;
		var rh = $.isArray(handlers) ? handlers.sort(function(a, b){ return (a.rate || 0) - (b.rate || 0); }) : handlers
		
		for(var index in rh)
				(rh[index].f || rh[index]).call(
					rh[index].scope || document
				);
				
		//return default value
		window.context = document;
	},
	
	/***
	**** Добавление объектов 
	***/
	objects : [],
	initObjects : function(){
		for(var index in this.objects)
			for(var i in this.objects[index].objects)
				this.objects[index][i] = $(this.objects[index].objects[i], window.context);
	},
	
	/***
	**** Ресайз
	***/
	resizeHandlers : [],
	resize: function(f, rate){
		this.add(f, rate || 0, this.resizeHandlers);
	},
	
	/***
	ONE
	***/
	afterOne: function(){
		catalog.initBC();
		fix.initFix();
		map.mainInit();
		App.history.init();
		App.history.emuHref();
		other.init(); 
		other.initTop();
		catalog.initScroll();
		catalog.staticScroll();
	},
	beforeOne: function(){},
	
	/********
	*********   HISTORY
	********/
	history : {
		q : [],
		oldMethod : '',
		oldHash : [],
		restoreLink : function(){
			if($('ul.catalog:not(.certificates)').length){
				catalog.inScroll();
				return true;
			}else if($('#map').length){
				if($('#map:visible').length)
					return App.history.jump(!window.location.hash.length, 'map/', true), true;	
				else{
					return App.history.jump(false, 'map/' + $('div.manager').attr('id').substr(4), true), true;	
				}
			}
			return false
		},
		hits : [],
		emuHrefFirst: true,
		emuHref: function(){
			var realLink = (function(){
				if(window.location.hash.length > 1 && window.location.hash.indexOf('catalog/') == 1) return window.location.origin + '/' + window.location.hash.substr(1);
				return window.location.toString();
			})();
			if(App.history.hits[App.history.hits.length-1] == realLink) return;
			App.history.hits.push(realLink);
			
			
			if(!App.history.emuHrefFirst) _gaq.push(["_trackPageview", realLink]); 
			App.history.emuHrefFirst = false;
			
			//if(counter) 
				counter.hit(realLink, null, App.history.hits[App.history.hits.length-2] || null); 
			//console.warn('HIT', realLink, null, App.history.hits[App.history.hits.length-2] || null);
		},
		parselink : function(hash){
			var reg = /(catalog\/.*$)/.exec(window.location.pathname);
			var hash = hash ||  window.location.hash.toString().substr(1);
			if(reg) reg = reg[1];
			return hash || reg || hash;
		},
		hashes : [
			'catalog/manometers',
			'catalog/termometers',
			'catalog/dop_oborudovanie',
			'catalog/manometers/s_elektrokontaktnoy_pristavkoy',
			'catalog/termomanometers/standartnoe_ispolnenie_2'
		],
		refreshTitle : function(hash){
			if($.inArray(hash, this.hashes) == -1) return false;
			
				var data =  {},
					result = (/catalog\/([^\/]+)(\/([^\/]+))?/).exec(hash);
				data.categoryAlias = result[1];
				if(result[3]) data.itemAlias = result[3];
				
				$.ajax(W_AJAX + 'item/get_seo_info', {data: data, dataType: 'json', type: 'post'}).done(function(json){
					document.title = json.data.title;
					
					var div;
					if((div = $('section > div.text-description')).length == 0){
						div = $('<div class="text-description" />').appendTo('section');
						$('body').addClass('with-text-description');
					}
					div.html(json.data.seo_text);
				});
		},
		init: function(){
			$.history.init(App.history.loadHandler = function(hash, firstLaunch){
				
				var hash = hash || window.location.hash.substr(1);
				var firstLaunch = firstLaunch || false;
				$(document).trigger('returnBack');
				App.history.refreshTitle(hash);
				App.history.oldHash.push(hash);
				//Если выключен парсинг ссылки выходим
				if(App.history.noparsing) 
					return App.history.noparsing = false; 
				//if(window.location.pathname.substr(1) == hash) return false;
				hash = App.history.parselink(hash);
				//Если нулевой хэш — то убираем все лишнее
				if(hash.length == 0){
					fix.free();
					App.clearAll();
					if(!$('#map').length) $(window).scrollTop(0);
					return $(document).trigger('clearAll');
				}
				
				var hash = hash.split('#'), reg = /^\/?([a-z]*)(\/|:)?(.*)?$/;
				
				if(hash.length == 0 && !reg.test(hash[0])){
					$(document).trigger('clearAll');
				}
				
					
					
				if(reg.exec(hash[0])[1] != App.history.oldMethod && !firstLaunch){
					App.history.oldMethod = reg.exec(hash[0])[1];
					fix.free();
				}
				
				//App.history.resumeHistoryLink = hash.join('#');
			//	console.log('Прошел: ', hash);			
				App.history.q = [];		
				$.each(hash, function(i, hash){
					var cmd, args;
					
					//Определяе комманду и параметры
					cmd = reg.exec(hash)[1], args = reg.exec(hash)[3] || '';
					switch(cmd){
						case 'catalog' : 
							App.history.q.push([function(next){
								catalog.goto(args, function(){
									catalog.checkOldBC();
									next()
								});
							}, cmd]);
							break; 
						
						case 'news' :
							App.history.q.push([function(next){
								fix.openNews(args, hash, next);
								App.history.emuHref();
							}, cmd]);
							break;
							
						case 'lightbox' :
							App.history.q.push([function(next){
								App.history.emuHref();
								if(args == "map")
									fix.lightBox('<iframe width="500" height="500" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.ru/maps/ms?hl=ru&amp;ie=UTF8&amp;msa=0&amp;msid=202366030235926081557.0004a4a0e6cc06835abf7&amp;ll=59.951637,30.237808&amp;spn=0.010745,0.021415&amp;z=14&amp;output=embed"></iframe>', 'html', next);
								else if (args == "map_bi") {
									fix.lightBox('<iframe width="500" height="500" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps/ms?msa=0&amp;msid=202366030235926081557.0004a8550ddd6a521a709&amp;ie=UTF8&amp;ll=55.691375,37.654524&amp;spn=0.024189,0.04283&amp;z=14&amp;output=embed"></iframe>', 'html', next);
								}
								else{
									if(args.indexOf('id:') == 0)
										fix.lightBox(args.substr(3), 'id', next);
									else
										fix.lightBox(args, 'image', next);
								}
							}, cmd]);
							break;
						case 'popup' : 
							App.history.q.push([function(next){
								fix.lightBoxId(args, next);
								App.history.emuHref();
							}, cmd]);
							break;
						case 'map' :
							App.history.q.push([function(next){
								map.openRegion(args, next);
								App.history.emuHref();
							}, cmd]);
							break;
					}
					
				});
				var i = 0, next = function(i){
					if(App.history.q.length <= i) return App.history.q = [];
					App.history.q[ i++ ][0](function(){
						next(i);
					});
				};
				next(i);
			}, { unescape: ":/()" });
			return this;
		},
		
		/*goto link without store in history
		** @param nostore	Незаписывать страницу в историю (переписать текущую)
		** @param hash		Ссылка хэш
		** @param noparsing Не обрабатывать новую ссылку
		*/ 
		jump : function(nostore, hash, noparsing){
			if(typeof hash == 'undefined') var hash = App.history.hash || false;
			
			if(typeof nostore == 'undefined') var nostore = false;
			
			//Если мы пришли с цепочки причем цепочка вернула фальш
			if(hash === false) return false;
			
			//Если хэш у нас с шарпом то мы убираем шарп
			if(hash.indexOf("#") != -1) hash = hash.substr(hash.indexOf("#") + 1);
			
			if(App.history.parselink() == hash || (window.location.hash.toString().length == 0 && hash.length == 0)) return false;
			
			var noparsing = App.history.noparsing = noparsing || App.history.noparsing || false;
			
			//If need to store last stable link
			if (App.history.resumeHistoryLink && !App.history.hash) {
		//		console.log('Восстановление ссылки');
				var tmpHash = App.history.resumeHistoryLink;
				delete App.history.resumeHistoryLink;
				
				App.history.jump(true, tmpHash, true);
				//restore value after another method launch;
				App.history.noparsing = noparsing;
				//alert('загрузка2 ' + hash);
				$.history.load(hash);
				delete App.history.hash;
				return;
			}
			hash = (/^\/?(.*)$/).exec(hash)[1];
			if(nostore && App.history.oldHash.length > 1){
				window.location.replace(!hash.length ? '' : '#' + hash);
			}else
				$.history.load(hash); 
				
		//	if(hash.length == 0) window.location.replace(window.location.pathname);
			delete App.history.hash;
		},
		
		//link which store in history without the possibility been replaced
		storeLink : function(hash, noparsing){
			//Если хэш у нас с шарпом то мы убираем шарп
			//alert(hash);
			if(hash.substr(0, 1) == "#") hash = hash.substr(1);
			if(window.location.hash.toString() == '#'+hash) return this;
			App.history.hash = hash;
		//	console.log('На востановление', hash);
			
			App.history.resumeHistoryLink = hash;
			App.history.noparsing = noparsing || false;
			//console.warn('this was been stored');
			return this;
		}
	},
	autoscroll : function(cmd){
		if(typeof cmd == "undefined") return App.autoscroll.stat || false;
		return App.autoscroll.stat = cmd ? true : false;
	},
	/******
	REGEX COMMAND
	*****/
	commandRegEx : /^#(.+)\((.+)\)$/,
	getAnchorByHref: function(url){ 
		var url = url.substr(url.length-1) == "/" ? url.substr(0, url.length-1) : url;
		url = url.substr(0, 1) == "/" ? url.substr(1) : url;
		
		
		return $('a[href$="' + url + '"]').filter('.js-link, .anchor').first(); 
	}
};
$(document).ready(App.init);
$(window).resize(function(){
	App.fire(window, App.resizeHandlers);
});

var ie6 = $.browser.msie && parseFloat($.browser.version) < 7;

$(function(){
	$('nav#main-menu li.dd-link').hover(function(){
		$('div.dd-box').show();
	},function(){
		$('div.dd-box').hide();
	});
});
