$(document).ready(function(){
	
    MB.switchOs();
	MB.faqList();
	MB.demoSlides();
	if($('.scroll-pane').length){
		MB.demoScrollContet();		
	}

});


//mobilny bank namespace
if(window.MB === undefined){MB = {};}

MB.demoScrollContet = function(){
	
	
	var init = function(){
		var scrollPanes  = $('.scroll-pane');
		
		scrollPanes.each(function(){
			var scrollPane = $(this),
				scrollContent  = scrollPane.children('.scroll-content'),
				//compare the height of the scroll content to the scroll pane to see if we need a scrollbar
				difference = scrollContent.height()-scrollPane.height(),
				sliderWrap = {},
				sliderVertical = {};
			
			//change the main div to overflow-hidden as we can use the slider now
			scrollPane.css('overflow','hidden');
	
			//if the scrollbar is needed, set it up...
			if(difference>0){
			   var proportion = difference / scrollContent.height();//eg 200px/500px
			   var handleHeight = Math.round((1-proportion)*scrollPane.height());//set the proportional height - round it to make sure everything adds up correctly later on
			   handleHeight -= handleHeight%2;
				
				if(scrollPane.children('.slider-wrap').length === 0){
					
				   scrollPane.append('<\div class="slider-wrap"><\div class="slider-vertical"><\/div><\/div>');//append the necessary divs so they're only there if needed
				   sliderWrap = scrollPane.children('.slider-wrap');
				   sliderWrap.height(scrollPane.height());//set the height of the slider bar to that of the scroll pane
				   sliderVertical = sliderWrap.children('.slider-vertical');
			
				   //set up the slider
				   buildSliderUI(sliderVertical,scrollContent,difference);
					
				   //set the handle height and bottom margin so the middle of the handle is in line with the slider
				   sliderWrap.find(".ui-slider-handle").css({height:handleHeight,'margin-bottom':-0.5*handleHeight});
					
				   var origSliderHeight = sliderVertical.height();//read the original slider height
				   var sliderHeight = origSliderHeight - handleHeight ;//the height through which the handle can move needs to be the original height minus the handle height
				   var sliderMargin =  (origSliderHeight - sliderHeight)*0.5;//so the slider needs to have both top and bottom margins equal to half the difference
				   sliderWrap.find(".ui-slider").css({height:sliderHeight,'margin-top':sliderMargin});//set the slider height and margins
				   
					//code to handle clicks outside the slider handle
					sliderWrap.find(".ui-slider").click(function(event){//stop any clicks on the slider propagating through to the code below
					   	event.stopPropagation();
					   });
					   
					sliderWrap.click(function(event){//clicks on the wrap outside the slider range
						  var offsetTop = $(this).offset().top;//read the offset of the scroll pane
						  var clickValue = (event.pageY-offsetTop)*100/$(this).height();//find the click point, subtract the offset, and calculate percentage of the slider clicked
						  sliderVertical.slider("value", 100-clickValue);//set the new value of the slider
					});
					
					 
					//additional code for mousewheel
					$([scrollPane,sliderWrap]).each(function(){
						$(this).mousewheel(function(event, delta){
							var speed = 5;
							
							var sliderVal = sliderVertical.slider("value");//read current value of the slider
										sliderVal += (delta*speed);//increment the current value
					
							sliderVertical.slider("value", sliderVal);//and set the new value of the slider
						
							event.preventDefault();//stop any default behaviour
						});
					});
				}					
				
					
			}//end if	 
		});
	},
	
	buildSliderUI = function(sliderVertical,scrollContent,difference){
	   sliderVertical.slider({
	      orientation: 'vertical',
	      min: 0,
	      max: 100,
	      value: 100,
	      slide: function(event, ui) {//used so the content scrolls when the slider is dragged
	         var topValue = -((100-ui.value)*difference/100);
	         scrollContent.css({top:topValue});//move the top up (negative value) by the percentage the slider has been moved times the difference in height
	      },
	      change: function(event, ui) {//used so the content scrolls when the slider is changed by a click outside the handle or by the mousewheel
	         var topValue = -((100-ui.value)*difference/100);
	         scrollContent.css({top:topValue});//move the top up (negative value) by the percentage the slider has been moved times the difference in height
	      }

	   });

	};
	
	init();
	
}; 

MB.switchOs = function(){

	if( $('.buttons-os-wrapper').length > 0){
    		var trigger = $('.buttons-os-wrapper').children('div'),
			phonesWrapper = $('#mb-demo'),
			phones = $('.mb-demo-device'),
            currentPhone = phones[0],
            osName = $.cookie('MOBILE-BANK-FAVORED-OS'),
			demoSticker = $('.button-interactive-demo'),
			isAnimating = false,
			curtain = $('<div>',{
				id: 'mb-demo-curtain'
			}).appendTo(phonesWrapper);

            if(osName){
               phonesWrapper.removeClass().addClass(osName);
               phones.not('#mb-demo-' + osName).hide();
               trigger.addClass('mb-demo-os-switch-off').removeClass('mb-demo-os-switch-on');
               $('#mb-demo-switch-' + osName).removeClass('mb-demo-os-switch-off').addClass('mb-demo-os-switch-on');
            }else{
                osName = trigger.eq(0).attr('id').slice(15);
                phonesWrapper.removeClass().addClass(osName);
                phones.not(phones[0]).hide();
                trigger.addClass('mb-demo-os-switch-off').removeClass('mb-demo-os-switch-on');
                trigger.eq(0).removeClass('mb-demo-os-switch-off').addClass('mb-demo-os-switch-on');
            }

			trigger.click(function(){
				if(isAnimating === false){
					if($(this).hasClass('mb-demo-os-switch-on')){
						return false;
					}else{
						isAnimating = true;
                        osName = $(this).attr('id').slice(15);
						phonesWrapper.removeClass().addClass(osName);
						trigger.addClass('mb-demo-os-switch-off').removeClass('mb-demo-os-switch-on');
						$(this).removeClass('mb-demo-os-switch-off').addClass('mb-demo-os-switch-on');
						demoSticker.hide();
						curtain.fadeIn('slow',function(){		
								phones.css('display','none');
								$('#mb-demo-' + osName).css('display','block');
							$(this).fadeOut('slow',function(){
								demoSticker.show();
								MB.demoScrollContet();
								currentPhone = '#mb-demo-' + osName;
                                $.cookie('MOBILE-BANK-FAVORED-OS', osName, {
                                    expires : 7,
                                    path : '/'
                                });
                                isAnimating = false;
							});
						});
					}
				}		
			});				
	}
};

MB.faqList = function(){
	var faqTriggers = $('.faq-entry-header'),
		faqContents = $('.faq-entry-content');
	
		faqContents.not(':first').hide();
		faqTriggers.not(':first').addClass('faq-entry-close');
		
		faqTriggers.click(function(){
			if($(this).hasClass('faq-entry-close')){
				$(this).removeClass('faq-entry-close');
				$(this).next('.faq-entry-content').slideDown('fast');
			}else{
				var that = this; 
				$(this).next('.faq-entry-content').slideUp('fast',function(){
					$(that).addClass('faq-entry-close');	
				});
			}
		});

}; 

MB.demoSlides = function(){
	var lists = $('.mb-demo-slides');
	
	lists.each(function(){
		var slideList = $(this),
			slideItems = $(this).find('img'),
			listLeftPos = 0,
			itemWidth = $(this).parent('.mb-demo-device-screen').width(),
			slideListWidth = slideItems.length * itemWidth,
			goBack = false,
			isAnimating = false;

        //gdy jest tylko jeden slajd przerywa dzialanie skryptu
        if(slideItems.length < 2){
            return;
        }
		slideList.css('width',slideListWidth);
			
		slideItems.click(function(){
			if(!isAnimating){
				isAnimating = true;
				if(!goBack){
					slideList.animate({
						left: listLeftPos - itemWidth					
					},{
						duration: 800,
						easing: 'easeOutBack',
						complete: function(){
							listLeftPos = listLeftPos - itemWidth;
							isAnimating = false;
							if(Math.abs(listLeftPos)+itemWidth === slideListWidth){
								goBack = true;
							}
						}
					});				
				}else{
					slideList.animate({
						left: listLeftPos + itemWidth					
					},{
						duration: 800,
						easing: 'easeOutBack',
						complete: function(){
							listLeftPos = listLeftPos + itemWidth;
							isAnimating = false;
							if(Math.abs(listLeftPos) === 0){
								goBack = false;
							}
						}
					});	
				}				
			}
		});
	});
};

