/**
* Project js Library
*/ 

function parseHash(){

	var result = portal.hash.parse();
	if (result['id'] || result['url']){

			// additional parameters for the popup
			var popupParams = {
				'invite-friend' : {'width' : 690, 'callback': function(){}},
				'anketa': {callback: function(){
				
					window.checkFormFields = checkFormFields = function (){
						
							var all_approved = true;
							if (typeof fields != 'undefined' || typeof fields != 'null'){
								var steps = $_('step').value.toString(),
									step,
									obj,
									stop,
									i,
									approved,
									points = 0;
								
								// parsing step
								if (steps.indexOf(',') >= 0)
									steps = steps.split(',');
								else
									steps = [steps];
								
								var j = steps.length;
								for (var j in steps){
											
									step = steps[j];
									i = 1;
									approved = false;
									stop = false;
									
									switch (fields[step].type){
						
									case 'checkbox':
										while (!stop && (obj = $_('answers['+step+']['+i+']'))){
											if (obj.checked){
												approved = true;
												stop = true;
												points += fields[step]['answers'][i-1]['points'];
											}
											i++;
										}
										// check for empty
										if (!approved && typeof fields[step].empty != 'undefined' && fields[step].empty)
											approved = true;
											
										all_approved = all_approved && approved;
										break;
						
									case 'radio':
										while (!stop && (obj = $_('answers['+step+']['+i+']'))){
											if (obj.checked){
												approved = true;
												//stop = true;
												//console.log(fields[step]['answers']);
												points += fields[step]['answers'][i-1]['points'];
												
											}
											i++;
										}
										// check for empty
										if (!approved && typeof fields[step].empty != 'undefined' && fields[step].empty)
											approved = true;
										
										all_approved = all_approved && approved;
										//console.log(step + ' = ' +approved);
										
										break;
						
						
									case 'text':
										approved = true;
										while (!stop && (obj = $_('answers['+step+']['+i+']'))){
											if (obj.value.replace(' ','') != ''){
												approved = approved && true;
												points += fields[step]['answers'][i-1]['points'];
												
											} else 
												approved = approved && false;
											i++;
										}
										// check for empty
										if (!approved && typeof fields[step].empty != 'undefined' && fields[step].empty)
											approved = true;
										
										all_approved = all_approved && approved;
										
										break;
						
									case 'multiradio':
										var ans_cnt = fields.answers.length;
										approved = true;
										for (i=1; i<=ans_cnt; i++){
										
											var obj2, approved2 = false;
											
											for (var z = fields[step].minvalue; z <= fields.maxvalue; z++){
												
												obj2 = $_('answers['+step+']['+i+']['+z+']')
												if (obj2.checked){
													approved2 = true; 
													points += fields[step][i][z]['points'];
													points += fields[step]['answers'][i-1][z]['points'];
													
													//break;
												}
											}
											approved = approved && approved2;
						
										}
						
										all_approved = all_approved && approved;
										
										break;
						
									}
						
								}	
							}
							if (!all_approved){
								alert(portal.mess.ilc.err_anketa);
							} else {	
								// apply points
								$_('b-points-collector').style.display = 'block';
								$_('b-points-value').innerHTML = points;
							}
							return false;//all_approved;
						
						}
						var json_decode = function (str_json) {

						    var json = this.window.JSON;
						    if (typeof json === 'object' && typeof json.parse === 'function') {
						        try {
						            return json.parse(str_json);
						        } catch (err) {
						            if (!(err instanceof SyntaxError)) {
						                throw new Error('Unexpected error type in json_decode()');
						            }
						            this.php_js = this.php_js || {};
						            this.php_js.last_error_json = 4; // usable by json_last_error()
						            return null;
						        }
						    }
						 
						    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
						    var j;
						    var text = str_json;
						 
						    // Parsing happens in four stages. In the first stage, we replace certain
						    // Unicode characters with escape sequences. JavaScript handles many characters
						    // incorrectly, either silently deleting them, or treating them as line endings.
						    cx.lastIndex = 0;
						    if (cx.test(text)) {
						        text = text.replace(cx, function (a) {
						            return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
						        });
						    }
						 
						    // In the second stage, we run the text against regular expressions that look
						    // for non-JSON patterns. We are especially concerned with '()' and 'new'
						    // because they can cause invocation, and '=' because it can cause mutation.
						    // But just to be safe, we want to reject all unexpected forms.
						    // We split the second stage into 4 regexp operations in order to work around
						    // crippling inefficiencies in IE's and Safari's regexp engines. First we
						    // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
						    // replace all simple value tokens with ']' characters. Third, we delete all
						    // open brackets that follow a colon or comma or that begin the text. Finally,
						    // we look to see that the remaining characters are only whitespace or ']' or
						    // ',' or ':' or '{' or '}'. If that is so, then the text is safe for veal.
						    if ((/^[\],:{}\s]*$/).
						    test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
						    replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
						    replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
						 
						        // In the third stage we use the veal function to compile the text into a
						        // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
						        // in JavaScript: it can begin a block or an object literal. We wrap the text
						        // in parens to eliminate the ambiguity.
						        j = eval('(' + text + ')');
						 
						        return j;
						    }
						 
						    this.php_js = this.php_js || {};
						    this.php_js.last_error_json = 4; // usable by json_last_error()
						    return null;
						}
						
						window.fields = json_decode($_('hFields').getAttribute('data'));

						var asubmit = function (e){
							e.returnValue = checkFormFields();
							
							if (!e.returnValue){
								e.preventDefault ? e.preventDefault() : '';
							} else {
							
							}
							
							return e.returnValue;
						};
						
						portal.events.attach($_('ankForm'), "submit", asubmit, false);
					}},
				'themselves' : {'width' : 800}, 
				'cooperate' : {'width' : 800}, 
				'company-profile' : {'width' : 800}, 
				'about' : {'width' : 750, 'title_class' : 'about'},
				'moodle-login' : {'width' : 400, 'close_text' : '', callback: function(){}},
				'register' : {'width' : 700, 'close_text' : '', callback: function(){}},
				'subscribe' : {'width': 370, 'title_class' : 'h', 'correctHeight': false, callback: function(){$('.tours-list-up').click(function(){popup.destroy(popup)})}}
			};
			
			// try to find params for current page
			var params = null;
			
			//var result = {'url' : $(this).attr('p-href')};
			
			if (result['url']){
				for (var i in popupParams){
					//console.log(result['url'].indexOf(i));
					if (result['url'].indexOf(i) != -1){
						params = popupParams[i];
						break;
					}
				}
			}		
					
			if (typeof popup != 'undefined') 	
				popup.destroy(popup);
			popup = new oPopupLayer({'insert_callback' : function (popup){
					$(popup.getContent()).find('form:not(.noAjx)').addClass('frmAjx');
					portal.ajax.attach_forms(popup);
					//post_loading(popup);
					//$('#l-content .close').click(function(){popup.destroy(popup)}); 
		
					if (params && typeof params.callback == 'function'){
						params.callback();
					}
				}, 
				'window' : params,
				'doch' : getClientHeight()
			});
			popup.create();
			portal.ajax.load(null, result, popup.insert);
			

	} else if ('print' in result){
		portal.print();
	} else if ('comments' in result){	
		// parsing comments page - add some timeout
		setTimeout("window['comments'][0].updPage("+result['comments']+")", 500);
	} else {
		var fmid = null;
		for (var i in result){
			if ((fmid = /^oFMailer_(.*)/i.exec(i)) && typeof(oFMailer[fmid[1]]) == 'object'){
				addMailerClick(fmid[1]);
				break;
			} else if (/^faq-(.*)/i.test(i)){
				showFAQ(i);
			}
		}
	}
	
}

// show cv video
function showCvVideo(id) {
	$('#video'+id).jOverlay({color:'black', opacity : 0.9});
}

// vacancies form
function sendVacForm() {
	//var fid = 'b-brief-search';
	//if($_(fid).style.display == 'none') {
		fid = 'b-full-search';
	//}
	
	$_(fid.replace('b-','f-')).submit();
}

// set prog type
function setProgType() {
	if(getCookie('PROG_TYPE') == null || getCookie('PROG_TYPE') == '') {
		setCookie('PROG_TYPE',1,3600*24*365,'/');
		location.href = location.href;
	}else{
		setCookie('PROG_TYPE','',3600*24*365,'/');
		location.href = location.href;
	}
}

// set prog
function setProg(pic,title,slogan,href) {
	$('#b-prog').css('background','url("'+pic+'") no-repeat');
	$('#b-prog-link').attr('href',href).html(title);
	$('#b-prog-descr').html(slogan);
}

// for connect events to the elements
function post_loading(container){

	if ($_('frmAddQA')){
		
		var _always_submit = false;
		$_('frmAddQA').setAttribute('action', '');
		
		function sbForm(container){
		
			if (_always_submit){
				return false;
			} else {
				//ev.returnValue = athis._checkForm(e, athis);
				
				/*if (!ev.returnValue){
					ev.preventDefault ? ev.preventDefault() : '';
				} else {*/
				_always_submit = true;
				var result = portal.hash.parse();
 				if (result['id'] || result['url']){
					result['form'] = $_('frmAddQA');
					result['method'] = 'post';
			 			
			 		portal.events.remove($_('frmAddQA'), "submit");
			 		
			 		portal.ajax.load(null, result, container.insert);
			 		container.clear(null);
			 	}
				//}
			}
		
		}
		// for webkit browser we need to use another method
		if (navigator.userAgent.toLowerCase().indexOf('webkit') > -1){
		
			$('#frmAddQA').submit(function(e){
				e.stopPropagation();
				e.preventDefault();
				return false;
			});
		
			$('#frmAddQA input[type=submit]').bind("click", function(e){
				sbForm(container);
				return portal.events.stop(e);
			});
		
			
		} else {
			
			portal.events.attach($_('frmAddQA'), "submit", function (e){
				
				var ev = e ? e : window.event;
				ev.returnValue = false;
				sbForm(container);
				
				return portal.events.stop(ev);
			}, false);
			//});
		}
			
	}
	
}


/**
* reminde user login and password
*/
function remindLogin(){

	// check fields
	if ($_('fldControlWord').value == '' || $_('fldControlWord').value == 'control_word'){

		showError('logError2', 'cword_error'+'<br/>'+'<a href="">write_to_support</a>');		

	} else {
		var req = new JsHttpRequest();
		var ticket = portal.loader.create('logLoader');
			
		req.onreadystatechange = function (){
				
			if (req.readyState == 4){
				if (typeof ticket != "undefined")
					portal.loader.destroy(ticket);
				showHide('login_f');				

				if (req.responseJS.status == 1){					
					showError('logError2', 'email_from_support', true);
				} else {					
					showError('logError2', 'cword_error'+'<br/>'+'<a href="">write_to_support</a>');
				}
			}
		
		}
		// show uploader
		showHide('logLoader');
		showHide('login_f');
		
		req.open(null, '/ajax.php', true);
		req.send({'resource' : 'chckword',
			'cword' : $_('fldControlWord').value
			});
	}

}


portal.changer = function(id){

	if ($('#cont-'+id).css('display') == 'none'){
		$('#link-'+id).css('display', 'none');
		$('#unlink-'+id).css('display', 'block');
	} else {
		$('#link-'+id).css('display', 'block');
		$('#unlink-'+id).css('display', 'none');
	}
	
	$('#cont-'+id).slideToggle(200);

}



/**
* on DOM ready
*/
portal.ready(function (){
	
	// connecting to the input fields events
	var fields_defaults = {'#search_q' : '',
		'#full_search_q' : '',
		'#subscribe_email' : '',
		'#subscribe_fname' : '',
		'#subscribe_surname' : '',
		'#qa_fio' : '',
		'#qa_email' : '',
		'#s-keys' : '',
		'#s-keys2' : '',
		'.b-faq-form #title': '',
		'.b-faq-form #email': '',
		'.b-faq-form #post': '',		
		'.b-faq-form #country': '',		
		'.b-faq-form #descr': '',
		'#moologin' : '',
		'#moopassword' : ''
		};

	for (var i in fields_defaults){
		fields_defaults[i] = typeof $(i).attr('defvalue') != 'undefined' ? $(i).attr('defvalue') : $(i).attr('value');
		$(i).attr('reg', i);
		$(i).live('focus', function(){
			if ($(this).attr('value') == fields_defaults[$(this).attr('reg')] || $(this).attr('value') == $(this).attr('defvalue'))
				$(this).attr('value', '');
			});
		$(i).live('blur', function(){
			if ($(this).attr('value') == '')
				$(this).attr('value', typeof $(this).attr('defvalue') != 'undefined' ? $(this).attr('defvalue') : fields_defaults[$(this).attr('reg')]);
			});
	}
	
	var popup;
			
	// connect to calendar helper
	if ($_('h-calendar')){
		$('#h-calendar').attr('p-href', $('#h-calendar').attr('href')).attr('href', 'javascript:void(0);').click(function(e){
			popup = new oPopupLayer();
			popup.addParams({'insert_callback' : function (){post_loading(popup);}})
			popup.create();
	 		portal.ajax.load(e, {'url' : $(this).attr('p-href')}, popup.insert);
	 		});
	}
	
	
		
	// connect galleryview and lightbox
	if ($('.c-press-gallery').length > 0){
	
		$('.c-press-gallery a').lightBox();
		
		/*$('#photos').galleryView({
			gallery_width: 600,
			gallery_height: 120,
			gallery_padding: 20,
			panel_width: 550,
			panel_height: 367,
			frame_width: 180,
			frame_height: 123,
			pause_on_hover: true,
			show_panels : true,
			show_filmstrip : true,
			frame_opacity: 1
		});*/	
	}
	
	// connect standart gallery
	if ($_('b-gallery-std')){
	
		// Load theme
	    Galleria.loadTheme('/js/jquery/galleria/src/themes/ilc/galleria.ilc.js?'+((new Date()).getTime()));
	    
	    // run galleria and add some options
	    $('#b-gallery-std').galleria({
	        image_crop: true,
	        transition: 'fade',
	        image_margin: '5',
	        data_config: function(img) {
	            return {
	                description: $(img).next('p').html()
	            };
	        }
	    });

	}
		
	if ($_('b-all-gallery')){
	
	    Galleria.loadTheme('/js/jquery/galleria/src/themes/lightbox/galleria.lightbox.js');
		$('#gallery').galleria({
			data_source: '#b-all-gallery',
	        keep: '#b-all-gallery',
	        image_margin: '5',
	        data_config: function(img) {
		        return {
		            description: $(img).attr('alt')
		        }
		    }
		});

	}
	
	if (/#link\-(\d+)/.test(document.location.hash)){
		var id = /#link\-(\d+)/.exec(document.location.hash);
		portal.changer(id[1]);
	}
	

	if ($('.ajx').length > 0){
		$('.ajx').live('click', function (event){

			event.returnValue = false;
			event.preventDefault ? event.preventDefault() : '';
			
			if (typeof $(this).attr('p-href') == 'undefined')
				$(this).attr('p-href', $(this).attr('href')).attr('href', 'javascript:void(0);');

			portal.hash.set('#url='+$(this).attr('p-href')+'&redirect='+document.location.href);
			parseHash(event);

		});
	}	
	
	
	// connect countries gallery
	if ($_('b-gallery')){
	
		var onMouseOutOpacity = 0.67;
				$('#b-gallery ul.thumbs li').opacityrollover({
					mouseOutOpacity:   onMouseOutOpacity,
					mouseOverOpacity:  1.0,
					fadeSpeed:         'fast',
					exemptionSelector: '.selected'
				});
	
		var gallery = $('#b-gallery').galleriffic({
		        delay:                     7000, // in milliseconds
		        numThumbs:                 4, // The number of thumbnails to show page
		        preloadAhead:              40, // Set to -1 to preload all images
		        enableTopPager:            false,
		        enableBottomPager:         true,
		        maxPagesToShow:             4,  // The maximum number of pages to display in either the top or bottom pager
		        imageContainerSel:         '#slideshow',
				controlsContainerSel:      '#controls',
				captionContainerSel:       '#g-cap-container',
				loadingContainerSel:       '#gal-loader',
				renderSSControls:          true, // Specifies whether the slideshow's Play and Pause links should be rendered
		        renderNavControls:         true, // Specifies whether the slideshow's Next and Previous links should be rendered
		        playLinkText:              'Play',
		        pauseLinkText:             'Pause',
		        prevLinkText:              'Previous',
		        nextLinkText:              'Next',
		        nextPageLinkText:          'Next &rsaquo;',
		        prevPageLinkText:          '&lsaquo; Prev',
		        enableHistory:             false, // Specifies whether the url's hash and the browser's history cache should update when the current slideshow image changes
		        enableKeyboardNavigation:  true, // Specifies whether keyboard navigation is enabled
		        autoStart:                 true, // Specifies whether the slideshow should be playing or paused when the page first loads
		        syncTransitions:           true, // Specifies whether the out and in transitions occur simultaneously or distinctly
		        defaultTransitionDuration: 900,
				onSlideChange:             function(prevIndex, nextIndex) {
						// 'this' refers to the gallery, which is an extension of $('#thumbs')
						this.find('ul.thumbs').children()
							.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
							.eq(nextIndex).fadeTo('fast', 1.0);
					},
				onPageTransitionOut:       function(callback) {
						this.fadeTo('fast', 0.0, callback);
					},
				onPageTransitionIn:        function() {
						this.fadeTo('fast', 1.0);
					}
		    }); 

	}
	
	// attach to the vac list
	if ($('.b-fav').length > 0){
		
	}
	
	// attach to the languages
	if ($('#b-langs').length > 0){
	
		$('#b-cur-ttl').click(function(){
			
			$('#b-langs').slideToggle('70');
			
		});
		
	
		/*var _curr_lang_title = $('#b-cur-ttl').html();
		$('#b-langs li img').bind('mouseover', function(){
				$('#b-cur-ttl').html($(this).attr('alt'));
			}).bind('mouseout', function(){
				$('#b-cur-ttl').html(_curr_lang_title);
			});
		*/
	}
	
	
	// attach to the news2 block
	if ($('.btn-news-slide').length > 0){
		var news_cur_pos = 1;
		function scrollTabs(move){
			switch (move){
			case 'left':
				if ($('#ni'+(news_cur_pos-1)+'-tb').length > 0){
					news_cur_pos--;
					$('#n-page').html(news_cur_pos);
					var i=1;
					while ($('#ni'+i+'-tb').length > 0){
						if (i != news_cur_pos){
							$('#ni'+i+'-tb').css('display', 'none');
							$('#ni'+i).css('display', 'none');
						}else{
							$('#ni'+i+'-tb').css('display', 'block');
							$('#ni'+i).css('display', 'block');
						}
						i++;
					}
					// check for next element
					if ($('#ni'+(news_cur_pos-1)+'-tb').length > 0)
						$('.btn-news-l').removeClass('btn-news-l-pass');
					else
						$('.btn-news-l').addClass('btn-news-l-pass');
					if ($('#ni'+(news_cur_pos+1)+'-tb').length > 0)
						$('.btn-news-r').removeClass('btn-news-r-pass');
					else
						$('.btn-news-r').addClass('btn-news-r-pass');
					
				}
			
				break;
			
			case 'right':
			default:
				if ($('#ni'+(news_cur_pos+1)+'-tb').length > 0){
					news_cur_pos++;
					$('#n-page').html(news_cur_pos);
					var i=1;
					while ($('#ni'+i+'-tb').length > 0){
						if (i != news_cur_pos){
							$('#ni'+i+'-tb').css('display', 'none');
							$('#ni'+i).css('display', 'none');
						}else{
							$('#ni'+i+'-tb').css('display', 'block');
							$('#ni'+i).css('display', 'block');
						}i++;
					}
					// check for next element
					if ($('#ni'+(news_cur_pos+1)+'-tb').length > 0)
						$('.btn-news-r').removeClass('btn-news-r-pass');
					else
						$('.btn-news-r').addClass('btn-news-r-pass');
					if ($('#ni'+(news_cur_pos-1)+'-tb').length > 0)
						$('.btn-news-l').removeClass('btn-news-l-pass');
					else
						$('.btn-news-l').addClass('btn-news-l-pass');
					
				}
				break;
			}
				
		}
	
		$('.btn-news-l').bind('click', function(){
			scrollTabs('left');
		})
		$('.btn-news-r').bind('click', function(){
			scrollTabs('right');
		})
		
		var btn_news_cntr = $('.btn-news-slide').length;
		function setNewInterval(){
			return setInterval(function(){if (news_cur_pos >= btn_news_cntr){news_cur_pos=0} scrollTabs('right')}, 5000);
		}
		var newsInt = setNewInterval();
		
		$('.b-news-item2').bind('mouseover', function(){
			clearInterval(newsInt);
		});
		
		$('.b-news-item2').bind('mouseout', function(){
			newsInt = setNewInterval();
		});
	}
	
	
	// attach to the vacs block
	if ($('.b-vac-clip-list').length > 0){
		var vac_cur_pos = 1;
		function scrollTabs2(){
			if ($('#vac-ni'+(vac_cur_pos+1)+'-tb').length > 0){
				vac_cur_pos++;
				$('#n-page').html(vac_cur_pos);
				var i=1;
				while ($('#vac-ni'+i+'-tb').length > 0){
					if (i != vac_cur_pos){
						$('#vac-ni'+i+'-tb').css('display', 'none');
						$('#vac-ni'+i).css('display', 'none');
					}else{
						$('#vac-ni'+i+'-tb').css('display', 'block');
						$('#vac-ni'+i).css('display', 'block');
					}
					i++;
				}
			}
		}
	
		var btn_vac_cntr = $('.b-vac-clip-list ul').length;
		function setNewInterval2(){
			return setInterval(function(){if (vac_cur_pos >= btn_vac_cntr){vac_cur_pos=0} scrollTabs2('right')}, 5000);
		}
		var vacInt = setNewInterval2();
		
		$('.b-vac-clip-list').bind('mouseover', function(){
			clearInterval(vacInt);
		});
		
		$('.b-vac-clip-list').bind('mouseout', function(){
			vacInt = setNewInterval2();
		});
	}
		
	
		
	// attach to the program docs blocks
	if ($('.b-docs h3').length > 0){
		$('.b-docs h3').click(function(){
			if ($(this).hasClass('act')){
				$('.b-docs .b-form-container').css('display', 'none');
				$(this).removeClass('act');
			} else {
				$('.b-docs .b-form-container').css('display', 'block');
				$(this).addClass('act');
			}
		})
	}
	
	// attach to the partners
	if ($('.b-p-opener').length > 0){
		$('.b-p-opener').click(function(){
			// determine id
			var id = /b-p-opener-([0-9]+)/.exec($(this).attr('id'))[1];
			if ($(this).hasClass('b-p-closed')){
				$('#b-p-list-'+id).removeClass('h');
				$(this).removeClass('b-p-closed');
			} else {
				$('#b-p-list-'+id).addClass('h');
				$(this).addClass('b-p-closed');
			}
		})
	}

	// career
	if ($('.b-career-desc').length > 0){
		
		$('.b-career h3').click(function(){
			var athis = $(this);
			$('.b-career h3').each(function (){
				if ($(this).attr('id') != athis.attr('id') || ($(this).attr('id') == athis.attr('id') && $(this).hasClass('opened'))){
					$(this).removeClass('opened');
					$('#'+$(this).attr('id')+'_full').removeClass('opened');
				} else {
					$(this).addClass('opened');
					$('#'+$(this).attr('id')+'_full').addClass('opened');				
				}
			})		
		})	
	}
	
	// search form
	if ($('#s-keys').length > 0){
		var s_types = [1, 2];
		$('.b-more-fields').click(function(){
			if ($_('s-type').value == '2'){
				$('#b-full-search').css('display', 'none');
				$('#b-brief-search').css('display', '');
				$_('s-type').value = '1';
			} else {
				$('#b-full-search').css('display', '');
				$('#b-brief-search').css('display', 'none');
				$_('s-type').value = '2';
			}
			for (var i=0,l=s_types.length; i<l; i++){
				if ($_('s-type').value == s_types[i])
					$_('b-mf'+s_types[i]).style.display = '';
				else
					$_('b-mf'+s_types[i]).style.display = 'none';
			}
		});
	}
	
	// connect to the leave info controllers
	if ($('.b-leave-info').length > 0 || $('.b-menu-leave-info').length > 0){
		$('.b-leave-info a').attr('p-href', $('.b-leave-info a').attr('href'));
		$('.b-menu-leave-info a').attr('p-href', $('.b-menu-leave-info a').attr('href'));
		
		$('.b-leave-info a, .b-menu-leave-info a').attr('href', 'javascript:void(0);').click(function(e){
				popup = new oPopupLayer();
				popup.addParams({'insert_callback' : function (){post_loading(popup);}})
				popup.create();
		 		portal.ajax.load(e, {'url' : $(this).attr('p-href')}, popup.insert);
		 	});
	}
	
	// connect cooperation link
	if ($('.b-want-partnership a, .b-want-partnership-menu a').length > 0){
		$('.b-want-partnership a, .b-want-partnership-menu a').each(function(){
			$(this).attr('p-href', $(this).attr('href')).attr('href', 'javascript:void(0);').click(function(e){
			popup = new oPopupLayer();
			popup.addParams({'insert_callback' : function (){post_loading(popup);}})
			popup.create();
	 		portal.ajax.load(e, {'url' : $(this).attr('p-href')}, popup.insert);
		});
		});
	}
	
	// adding listners to the faq
	function showFAQ(id){
		var id = id.replace('faq-a-', '');
		$('li[id^=faq-] .b-faq-item').each(function(){
			var aid = $(this).attr('id').replace('faq-cont-', '');
			if (aid != id){
				/*$(this).css('display', '');
				$('#header-'+aid).css('display', 'block');
				$('#faq-a-'+aid).css('display', 'block');
				//$(this).hide(100);
				*/
			}
		});
		
		$('#faq-'+id+' .b-faq-item').show(200, function(){/*$.scrollTo($('#faq-'+id), 400)*/})
		$('#header-'+id).css('display', 'none');
		$('#faq-a-'+id).css('display', 'none');
		
		//portal.hash.set('#faq-'+id);
	}
	
	window.hideFAQ = function(id){
		$('li[id^=faq-'+id+'] .b-faq-item').each(function(){
			var aid = $(this).attr('id').replace('faq-cont-', '');
			$(this).css('display', '');
			$('#header-'+aid).css('display', '');
			$('#faq-a-'+aid).css('display', '');
			//$(this).hide(100);
		});
	}
	
	
	if ($('li[id^="faq-"]').length > 0){
		$('li[id^="faq-"] a.more').each(function(){
			if (/javascript/i.test($(this).attr('href')) == false){
				$(this).attr('p-href', $(this).attr('href')).attr('href', 'javascript:void(0);').click(function(e){
					showFAQ($(this).attr('id'));
				});
			}
		});
	}
	
	
	$('.b-login-link').live('click', function (event){
		event.returnValue = false;
		event.preventDefault ? event.preventDefault() : '';
		
		if (typeof $(this).attr('p-href') == 'undefined')
			$(this).attr('p-href', $(this).attr('href')).attr('href', 'javascript:void(0);');
		
		if (typeof popup != 'undefined')
			popup.destroy(popup);

		popup = new oPopupLayer();
		popup.addParams({'insert_callback' : function (){post_loading(popup);}})
		popup.create();
		portal.ajax.load(event, {'url' : $(this).attr('p-href')}, popup.insert);
	});
	
	$('.b-lost-password').live('click', function (event){
		event.returnValue = false;
		event.preventDefault ? event.preventDefault() : '';
		
		if (typeof $(this).attr('p-href') == 'undefined')
			$(this).attr('p-href', $(this).attr('href')).attr('href', 'javascript:void(0);');
		
		if (typeof popup != 'undefined')
			popup.destroy(popup);
					
		popup = new oPopupLayer();
		popup.addParams({'insert_callback' : function (){post_loading(popup);}})
		popup.create();
		portal.ajax.load(event, {'url' : $(this).attr('p-href')}, popup.insert);
	});
	
	$('#b-reg-link').attr('href', 'javascript:void(0);').click(function(e){
		popup = new oPopupLayer();
		popup.create();
		portal.ajax.load(e, {'url' : 'register'}, popup.insert);
	});
		
	// adding listner to the calendar
	if ($('#b-cal-container').length > 0){
		var oCalendar = new ajxCalendar({'objID' : 'b-cal-container', 'ajxhref' : '/lang/'+lang_nick+'/calendar/smphr/1/ajx/1/', 'elem' : '0', 'callback': function(){}});
		if (oCalendar) oCalendar.load();
	}
	
	// adding listener to the search form
	if ($('#b-search-form').length > 0){
		$('#b-search-form').bind('submit', function(e){
			e.returnValue = true;
			//e.preventDefault ? e.preventDefault() : '';
			$('#b-search-form').attr('action', '/lang/'+lang_nick+'/search/q/'+$(this).find("input[name='ch_elem[q]']").val());
			return e.returnValue;
		})
	}
	
	if ($('#b-mini-search-form').length > 0){
		$('#b-mini-search-form').bind('submit', function(e){
			e.returnValue = false;
			e.preventDefault ? e.preventDefault() : '';
			document.location.href = '/lang/'+lang_nick+'/search/q/'+$('#search_q').val();
			return e.returnValue;
		})
	}
	
	// connect maps api
	if ($('#b-map').length > 0){
		$('#b-map').css('height', '350px');
		var map = new YMaps.Map(YMaps.jQuery("#b-map")[0]);
		map.setCenter(new YMaps.GeoPoint(30.501137, 50.448933), 17);
		
		// create maps placement
		var placemark = new YMaps.Placemark(new YMaps.GeoPoint(30.501137,50.448933), {style: "default#whitePoint"});
		placemark.name = '';
		placemark.description = $('#b-map .b-float').html();
		placemark.setIconContent($('#b-map .b-float').html());
		
		map.addOverlay(placemark); 
		
		//map.enableMagnifier();
		map.enableRuler();
		map.update();
	}
	
	// connect send to friend links
	if ($('.b-send-friend').length > 0){
		// we need global namespace
		oFMailer = {};
	
		//function post_loading
		function addMailerClick(index){
			popup = new oPopupLayer();
			popup.addParams();
			popup.create();
			oFMailer[index].addParams({'callback' : popup.insert, 'container' : popup});
			oFMailer[index].Load();
		};

		$('.b-send-friend').each(function (index){
			var i = index + 1;
			oFMailer[i] = new FMailer({'elem' : 'oFMailer'+i, 'add_id' : i, 'ajx_href' : document.location.pathname+'smphr/1/fmailer/yes'});
			$(this).click(function(e){addMailerClick(i)});
		})
			
	}
		
	// connect print links
	if ($('.b-ico-print').length > 0){
		$('.b-ico-print').click(function (){portal.print()});
	}
		
	// checking for input hash
	if (document.location.hash){
		parseHash();	
	} 
		
});


