/**
* 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);
			 		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' : '',
		'#qa_company' : '',
		'#qa_phone' : '',
		'#qa_descr' : '',
		'#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')){
		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 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, .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);
		});
	}
	
	$('.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-contact-image').length == 0){
		$('#b-map').css('width', '700px');
		$('#b-map').css('height', '500px');
		var map = new YMaps.Map(YMaps.jQuery("#b-map")[0]);
		map.setCenter(new YMaps.GeoPoint(30.427362,50.507606), 21);
		//map.setType(YMaps.MapType.HYBRID);
		
		// create maps placement
		var placemark = new YMaps.Placemark(new YMaps.GeoPoint(30.427362,50.507606), {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;
 				}
 			}
 		}
	} 
		
});

