var common = {};

common.object = {
		extend : function(
			oSource,
			oDestination
			) {				
			for(var i in oSource) {		
				oDestination[i] = oSource[i];
			}
			return oDestination;
		}
	};

common.utils = 
	{
		oPopupDefaults : {	
			iWidth      : 630,
			iHeight     : 470,
			sToolbar    : 'no',
			sMenubar    : 'no',
			sResizeable : 'yes',
			sScrollbars : 'yes',
			sStatus     : 'yes'
		},
		popup : function (

			sUrl,
			sName,
			oOptions,
			bReplace
			) {

			oOptions = common.object.extend(
				oOptions,
				common.utils.oPopupDefaults
				);
			var iLeftOffset = screen.availWidth / 2 - oOptions.iWidth / 2;
			var iTopOffset = screen.availHeight / 2 - oOptions.iHeight / 2;			
			oNewWindow = window.open(
				sUrl,
				sName,
				'left=' + iLeftOffset + ', ' +
				'top = ' + iTopOffset + ', ' +
				'width=' + oOptions.iWidth + ', ' +
				'height=' + oOptions.iHeight + ', ' +
				'resizable=' + oOptions.sResizeable + ', ' +
				'toolbar=' + oOptions.sToolbar + ', ' +
				'scrollbars=' + oOptions.sScrollbars + ', ' +
				'status=' + oOptions.sStatus
				);
			if(sUrl.match(/\.(gif|jpe?g|png)$/i)) {
				oNewWindow.document.open();
				oNewWindow.document.write('<html><head></head>' +
					'<body style="background: #FFF; margin: 0px; padding: 0px;">' +
					'<table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%"><tr><td align="center">' + 
					'<img src="' + sUrl + '" </td></tr></table></body></html>'
					);
				oNewWindow.document.close();
			}
			oNewWindow.focus();				
			return false;
		}
	};


common.getLang = function() {
	return document.getElementsByTagName('HTML')[0].getAttribute('lang') || 'ru';
};


/* http://dean.edwards.name/weblog/2005/10/add-event2/ */
common.addEvent = function(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		if (!handler.$$guid) {
			handler.$$guid = common.addEvent.guid++;
		}
		if (!element.events) {
			element.events = {};
		}
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		handlers[handler.$$guid] = handler;
		element["on" + type] = common.handleEvent;
	}
};
common.addEvent.guid = 1;
common.removeEvent = function(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};
common.handleEvent = function(event) {
	var returnValue = true;
	event = event || common.fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	var handlers = this.events[event.type];
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};
common.fixEvent = function(event) {
	event.preventDefault = common.fixEvent.preventDefault;
	event.stopPropagation = common.fixEvent.stopPropagation;
	return event;
};
common.fixEvent.preventDefault = function() {
	this.returnValue = false;
};
common.fixEvent.stopPropagation = function() {
	this.cancelBubble = true;
};


common.testObjectByStatement = function(object, statement) {
	statement = statement.toString();
	return (function() {
		return eval(statement.replace(/\s+and\s+/g, ' && ').replace(/\s+or\s+/g, ' || ')
							 .replace(/\s*[^\!\<\>]=\s*/g, ' == ').replace(/\s*@([\S]+)\s*/g, " this.$1 "));
	}.bind(object))();
}

common.initRows = function(cssQuery) {
	var plusHandler = function(e) {
		var _this = $(this);
		var row = _this.parents('.row');
		var newRow = row.clone(true);
		newRow.find('input[type=text]').val('');
		row.after(newRow);
	}
	var minusHandler = function(e) {
		var row = $(this).parents('.row');
		if (row.siblings('.row').length > 0) {
			row.remove();
		} else {
			row.find('.f-subrow-field input').add('texrarea').add('select').val('');
		}
	}
	// alert(cssQuery +' .plus');
	var box = $(cssQuery);
	// console.log($(cssQuery +' .plus'));
	
	box.find('.plus').bind("click", plusHandler);
	box.find('.minus').bind("click", minusHandler);
}

/*common.popup = function(selector, url) {
	if (common.popup.__data[selector] !== undefined) {
		return common.popup._getWindow(common.popup.__data[selector]);
	}
	if (url) {
		$.get(url, function(data){
			common.popup.__data[selector] = data;
		});
	}
};
common.popup.__data = {};
common.popup._getWindow = function(data) {
	var w = document.createElement('div');
	w.innerHTML = '<table class="popup"><tr><td class="nw"><div></div></td><td class="n"><div></div></td><td class="ne"><div></div></td></tr><tr><td class="w"><div></div></td><td><div class="content">'+ data +'</div></td><td class="e"><div></div></td></tr><tr><td class="sw"><div></div></td><td class="s"><div></div></td><td class="se"><div></div></td></tr></table>';
	return w;
};*/

common.dropDownInit = function() {
	
	$('.dropdown-block .dropdown-title, .vacancy-block .dropdown-title').click(function() {
		var currentItem = $(this).parent('.dropdown-item');
		if (currentItem.hasClass('g-current')) {
			currentItem.removeClass('g-current');
			return;
		}
		currentItem.addClass('g-current');
	});
	
};


common.initTabs = function() {
	
	var tabHandler = function() {
		var tab = $(this).parent('.g-tab');
		if (tab.hasClass('g-current')) {
			return;
		}
		$(this.parentNode.parentNode).find('.g-tab').each(function() {
			$(this).removeClass('g-current');
			$(this.tabContent).hide();
		});
		tab.addClass('g-current');
		$(tab[0].tabContent).show();
	};
	
	$('.g-tabs .g-tab').each(function() {
		var _this = $(this);
		var label = _this.children('.g-label');
		var content = _this.children('.g-tab-content');
		this.tabContent = content;
		content[_this.hasClass('g-current') ? 'show' : 'hide']();
		label.click(tabHandler);
		content[0].parentNode.parentNode.appendChild(content[0]);
	});
};

var pskb = {};
pskb.initMainMenu = function() {
	var cont = $(this);
	var currentLevel = null;
	// var menus = cont.find('ul');
	switch (true) {
		case cont.hasClass('nav-l1'): currentLevel = 1; break;
		case cont.hasClass('nav-l2'): currentLevel = 2; break;
		case cont.hasClass('nav-l3'): currentLevel = 3; break;
	}
	var count = currentLevel;
	
	var handleButton = function() {
		var that = $(this), level = that.attr('level');
		cont.removeClass('nav-l'+ currentLevel).addClass('nav-l'+ level);
		currentLevel = level;
	};
	
	var btnCont = $(document.createElement('div'));
	btnCont.addClass('nav-btn-cont');
	cont.prepend(btnCont);
	for (var i = 0; i < count; i++) {
		var btn = $(document.createElement('div'));
		btnCont.prepend(btn);
		btn.attr('level', i + 1).addClass('nav-btn'+ (i + 1)).click(handleButton);
	}
};

pskb.setCurrentCity = function(e) {
	e.preventDefault();
	$('.filials-form input').attr('value', this.id.substring('city_'.length));
	$('.filials-form').submit();
};

pskb.toggleFilialsPopup = function(e) {
	e.preventDefault();
	$('#filialspopup').toggle();
};
pskb.cityWarning = {
	cookieName: 'cityWarnHide',
	setCookie: function() {
		$.cookie(pskb.cityWarning.cookieName, 1, {expires: 30, path: '/'});
	},
	checkCookie: function() {
		return ($.cookie(pskb.cityWarning.cookieName) == 1);
	},
	close: function() {
		$(this).parents('.city-warning-popup').hide();
		pskb.cityWarning.setCookie();
		return false;
	},
	unknownCity: function() {
		$(this).parents('.city-warning-popup').hide();
		pskb.cityWarning.setCookie();
		$('#filialspopup').toggle();
		return false;
	},
	setCurrentCity: function(e) {
		e.preventDefault();
		pskb.cityWarning.setCookie();
		$('.filials-form input').attr('value', this.id.substring('city_'.length));
		$('.filials-form').submit();
	}
};

$(document).ready(function() {
	common.initRows('.rows');
	$('.nav-cont').each(pskb.initMainMenu);
	$('#filialspopup .citybtn').click(pskb.setCurrentCity);
	$('#filialpicker, #filialspopup .closebtn').click(pskb.toggleFilialsPopup);
	
	if (!pskb.cityWarning.checkCookie()) {
		$('.city-warning-popup').show();
		$('.city-warning-popup .close-popup').click(pskb.cityWarning.close);
		$('.city-warning-popup .city-unknown').click(pskb.cityWarning.unknownCity);
		$('.city-warning-popup .citybtn').click(pskb.cityWarning.setCurrentCity);
	}
	
	
	$('div.curr-informer .curr-header').bind("click", pskb.currInformerHandler);
	$('.right-navigator .nav-item').bind("click", pskb.rightNagivagorHandler);
	$('#right-credit-nagivagor div.nav-item').bind("click", pskb.rightCreditNagivagorHandler);
	
	$('.right-navigator-content #for-'+ $('.right-navigator .g-current').attr('id')).addClass('nav-item-current');
	$('.right-navigator-content #for-'+ $('.right-context-navigator .g-current').attr('id')).addClass('nav-item-current');
	$('#right-credit-nagivagor-link').attr('href', '/ru/private/credit/mortgage/calculator/?'+ $('#right-credit-nagivagor .g-current').attr('id'));
	
	$('#credit-filter-result').scrollFollow({
		container: '#credit-filter',
		offsetTopBox: '#vklad-inset',
		offset: 150,
		speed: 300
	});
	
	common.initTabs();
	common.dropDownInit();
	
});

pskb.rightNagivagorHandler = function(e) {

	if (!this.id) {
		return;
	}
	if (typeof this.parentNode.navContent === 'undefined') {
		this.parentNode.navContent = $('.right-navigator-content');
	}
	var navContent = this.parentNode.navContent;
	var element = $(this);
	
	navContent.children().removeClass('nav-item-current');
	element.siblings().removeClass('g-current');
	element.addClass('g-current');
	navContent.find('#for-'+ this.id).addClass('nav-item-current');
};

pskb.rightCreditNagivagorHandler = function(e) {
	
	$('#right-credit-nagivagor-link').attr('href', '/ru/private/credit/mortgage/calculator/?'+ this.id);
};

pskb.currInformerHandler = function(e) {
	var box = $(this.parentNode);
	$(box).siblings().removeClass('g-current');
	$(box).addClass('g-current');
};

pskb.newsImageHandler = function(event) {
	event.preventDefault();
	var $this = $(this);
	if (!$this.hasClass('g_class')) {
		pskb.newsImagePubBlock.find('.image-link.g-current').removeClass('g-current');
		$this.addClass('g-current');
		var title = $this.attr('title') || false;
		pskb.newsImagePreviewA.attr('href', $this.attr('href')).attr('title', title).next('.image-comment').remove();
		pskb.newsImagePreviewImg.attr('src', $this.find('img:first').attr('src'));
		if (title !== false) {
			pskb.newsImagePreviewA.after('<span class="image-comment">' + title + '</span>');
		}
	}
	return false;
};
jQuery(function() {
	pskb.newsImagePubBlock = jQuery('.pub-images-block');
	pskb.newsImagePreviewA = pskb.newsImagePubBlock.find('.main');
	pskb.newsImagePreviewImg = pskb.newsImagePreviewA.find('img:first');
	pskb.newsImagePubBlock.find('.image-link').unbind('click').click(pskb.newsImageHandler);
});
