/**
* Project js Library
*/ 

// 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);
			 		if (typeof container.clear == 'function')
				 		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(ev);
			});
		
			
		} 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
			});
	}

}



/**
* on DOM ready
*/
portal.ready(function (){
	
	// connecting to the input fields events
	var fields_defaults = {'#search_q' : '',
		'#full_search_q' : '',
		'#subscribe_email' : '',
		'#qa_fio' : '',
		'#qa_email' : '',
		'#s-keys' : '',
		'#s-keys2' : '',
		'.b-faq-form #title': '',
		'.b-faq-form #email': '',
		'.b-faq-form #post': '',		
		'.b-faq-form #descr': ''
		};
	
	for (var i in fields_defaults){
		fields_defaults[i] = $(i).attr('value');
		$(i).attr('reg', i);
		$(i).bind('focus', function(){
			if ($(this).attr('value') == fields_defaults[$(this).attr('reg')])
				$(this).attr('value', '');
			});
		$(i).bind('blur', function(){
			if ($(this).attr('value') == '')
				$(this).attr('value', 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');
	    
	    // 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')
		        }
		    }
		});

	}
	

	
	
	// 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-langs-select').css('left', ($_('b-cur-ttl').offsetLeft-5)+'px').css('top', ($_('b-cur-ttl').offsetTop-10)+'px');
		$('#b-langs-select .active, #b-langs-select .close').click(function(){$('#b-langs-select').hide()});
		$('#b-cur-ttl').click(function(){$('#b-langs-select').show()});
			
	}
	
		
	// 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').attr('p-href', $('.b-leave-info').attr('href'));
		$('.b-menu-leave-info a').attr('p-href', $('.b-menu-leave-info a').attr('href'));
		
		$('.b-leave-info,.b-menu-leave-info a').attr('href', 'javascript:void(0);').click(function(e){

				var ticket = portal.loader.create('b-register-form');
				var container = {'insert' : function(e, data, callback){
						portal.loader.destroy(ticket);
						$_('b-register-form').innerHTML = data.content;
						post_loading(container);
					},
					'clear' : function(){
						$_('b-register-form').innerHTML = '';
					}};
									
		 		portal.ajax.load(e, {'url' : $(this).attr('p-href')}, container.insert);
		 	});
		 	
		 $('#b-register-close').live('click', function(){$_('b-register-form').innerHTML = ''});
	}
	
	// connect cooperation link
	if ($('.b-want-partnership, .b-want-partnership-menu').length > 0){
		$('.b-want-partnership a, .b-want-partnership-menu a').attr('p-href', $('.b-want-partnership a').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 listners to the contacts
	if ($('.b-contact-info').length > 0){
		$('.b-contact-info').attr('p-href', $('.b-contact-info').attr('href'));
		
		$('.b-contact-info').attr('href', 'javascript:void(0);').click(function(e){

				var ticket = portal.loader.create('b-qa-form');
				var container = {'insert' : function(e, data, callback){
						portal.loader.destroy(ticket);
						$_('b-qa-form').innerHTML = data.content;
						post_loading(container);
					},
					'clear' : function(){
						$_('b-qa-form').innerHTML = '';
					}};
									
		 		portal.ajax.load(e, {'url' : $(this).attr('p-href')}, container.insert);
		 	});
		 	
		 $('#b-qa-close').live('click', function(){$_('b-qa-form').innerHTML = ''});
	}

	// connect listeners to menu
	if ($('.b-menu').length > 0){
	
		$('.b-menu > li').bind('mouseover', function(){
			if (!$(this).hasClass('active'))
				$('.b-menu > li.active > ul').css('display', 'none');	
			});
			
		$('.b-menu > li').bind('mouseout', function(){
			$('.b-menu > li.active > ul').css('display', 'block');	
			});
			
		$('.b-menu > li > ul > li').bind('mouseover', function(){
			if (!$(this).hasClass('active'))
				$('.b-menu > li > ul > li.active > ul').css('display', 'none');	
			});
			
		$('.b-menu > li > ul > li').bind('mouseout', function(){
			$('.b-menu > li > ul > li.active > ul').css('display', 'block');	
			});
	
	}
	
	// adding listners to the faq
	function showFAQ(id){
		var id = id.replace(/faq\-/i, '');
		$('li[id^=faq-] .b-faq-item').each(function(){
			if ($(this).parent().attr('id').replace(/faq-/ig, '') != id)
				$(this).css('display', '');
				//$(this).hide(100);
		});
		
		$.scrollTo($('#faq-'+id), 400, {'onAfter' : function(){$('#faq-'+id+' .b-faq-item').show(400)}});
		portal.hash.set('#faq-'+id);
	}
	
	if ($('li[id^="faq-"]').length > 0){
		$('li[id^="faq-"] a').each(function(){
			$(this).attr('p-href', $(this).attr('href')).attr('href', 'javascript:void(0);').click(function(e){
				showFAQ($(this).parent().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();
		
		$('.b-calendars').css('top', ($('.b-ico-calendar')[0].offsetTop + $('.b-ico-calendar')[0].offsetHeight + 12) + 'px'); 
		$('.b-ico-calendar, .b-calendars .b-close').click(function(){
			if ($('.b-calendars').css('display') == 'none')
				$('.b-calendars').show();
			else
				$('.b-calendars').hide();
		
		});
		
	}

	// adding listner to the tips
	if ($('.b-hint').length > 0){

		$('.b-hint').css('top', ($('.b-ico-tips')[0].offsetTop + $('.b-ico-tips')[0].offsetHeight + 12) + 'px'); 
		$('.b-ico-tips, .b-hint .b-close').click(function(){
			if ($('.b-hint').css('display') == 'none')
				$('.b-hint').show();
			else
				$('.b-hint').hide();
		
		});
		
	}


	// 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;
		})
	}
	
	// add listner to the slider
	if ($('.b-promo li').length > 0)
		$(".b-promo").easySlider({
			prevText:'UP',
			nextText:'DOWN',
			orientation:'horizontal',
			titleId: 'b-gal-title',
			descrId: 'b-gal-descr',
			counterId: 'b-item-counter',
			autoslide: 7000
		});

	// connect banner hider
	if ($('.b-banner-switcher').length > 0){
	
		function bannerSwitch(id, state){
			if (state == 1){
				$_('bswitcher-'+id).innerHTML = portal.mess.banner.hide;
				portal.css.removeClass('bswitcher-'+id, 'b-banner-switcher-off');
				portal.css.removeClass('banner-'+id, 'hide');
								
			} else {
				$_('bswitcher-'+id).innerHTML = portal.mess.banner.show;
				portal.css.addClass('bswitcher-'+id, 'b-banner-switcher-off');
				portal.css.addClass('banner-'+id, 'hide');

			}
		
		}
		
		var banners = portal.storage.get('banners', 'object');
		typeof banners == 'undefined' || !banners ? banners = {} : '';

		$('.b-banner-switcher').each(function(){
			var id = $(this).attr('id').replace('bswitcher-', '');
			if (banners && id in banners){				
				bannerSwitch(id, banners[id]);
			}
		})
		// connect banner events
		$('.b-banner-switcher').click(function(){
			var id = $(this).attr('id').replace('bswitcher-', '');
			if (id in banners && !banners[id]){
				banners[id] = 1;
			} else
				banners[id] = 0;
				
			bannerSwitch(id, banners[id]);
			portal.storage.set('banners', banners, 'object');
			
		});
	
	}

	// connect maps api
	if ($('#b-map').length > 0 && $('#b-contact-image').length == 0){
		/*$('#b-map').css('width', '563px');
		$('#b-map').css('height', '330px');
		var map = new YMaps.Map(YMaps.jQuery("#b-map")[0]);
		map.setCenter(new YMaps.GeoPoint(30.501137, 50.448933), 21);
		//map.setType(YMaps.MapType.HYBRID);
		
		// 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-map-title').html();
		placemark.setIconContent($('#b-map .b-map-title').html());
		
		map.addOverlay(placemark); 
		
		map.enableRuler();
		map.addControl(new YMaps.Zoom());
        map.addControl(new YMaps.ToolBar());
        map.addControl(new YMaps.TypeControl());

		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){
		var result = portal.hash.parse();
 		if (result['id'] || result['url']){
 			//popup = new oPopupLayer();
 			//popup.create();
 			//popup.addParams({'insert_callback' : function (){post_loading(popup)}});
 			
 			//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);
 				}
 			}
 		}
	} 
		
});


