/**
* Project js Library
*/ 


// 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);
			//});
		}
		
		
		// connect gallery
	}
	
	connectGallery();			
	
}

function connectGallery(){

	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()
				};
			}
		});
		
		$('#b-gallery-std').css('display', 'block');
	}
}


/**
* 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 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')){
		

	}
		
	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);
					}
		    }); 

	}
	
	
	// add listner to the slider
	if ($('.b-photogallery li').length > 0)
		$('.b-photogallery').easySlider({
			prevId: 		'galPrevBtn',
			//prevText: 		'Previous',
			nextId: 		'galNextBtn',	
			//nextText: 		'Next',
			orientation:'horizontal'
			/*titleId: 'b-gal-title',
			descrId: 'b-gal-descr',
			counterId: 'b-item-counter',*/
			/*autoslide: 7000*/
		});

	if ($('.b-videogallery li').length > 0)
		$('.b-videogallery').easySlider({
			prevId: 		'vidPrevBtn',
			//prevText: 		'Previous',
			nextId: 		'vidNextBtn',	
			//nextText: 		'Next',
			orientation:'horizontal'
			/*titleId: 'b-gal-title',
			descrId: 'b-gal-descr',
			counterId: 'b-item-counter',*/
			/*autoslide: 7000*/
		});

	if ($('.b-books li').length > 0)
		$('.b-books').easySlider({
			prevId: 		'booksPrevBtn',
			//prevText: 		'Previous',
			nextId: 		'booksNextBtn',	
			//nextText: 		'Next',
			orientation:'horizontal'
			/*titleId: 'b-gal-title',
			descrId: 'b-gal-descr',
			counterId: 'b-item-counter',*/
			/*autoslide: 7000*/
		});
	
		// 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()
	            };
	        }
	    });

	}

	
	// 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);
	});
	
	
	
	// parsing all virtual links
	if ($('a.ajax').length > 0){
		$('a.ajax').each(function(){
			$(this).attr('p-href', $(this).attr('href')).attr('href', 'javascript:void(0);').bind('click', function(e){
				e.returnValue = false;
				e.preventDefault ? e.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(e, {'url' : $(this).attr('p-href')}, popup.insert);
			});
		})
	}
	
	// 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();
	}
	
		
	// 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);
 				}
 			}
 		}
	}
	
	
	// checking for ie
	function vIE(){return (navigator.appName=='Microsoft Internet Explorer')?parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):-1;}
	var ie = vIE();
	if (ie < 8 && ie > 0){
		$('#.g-header h2').css('position', 'static').css('position', 'absolute');
	}	
	 
		
});


