$(function(){
	$.ajaxSetup({
		cache: false
	});
	
	/*
	 *  FB JS API APPEND
	 */
	
	(function(d){
     var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
     js = d.createElement('script'); js.id = id; js.async = true;
     js.src = "//connect.facebook.net/en_US/all.js";
     d.getElementsByTagName('head')[0].appendChild(js);
   }(document));
   
   /*
    * 
    */
   
	
		window.fbAsyncInit = function () {
			
			var userAuthWrapper = $('#user_auth_inner');
			var userAuthWrapperContent = userAuthWrapper.html();
			var FBUser = {};
			var FBUserName = '';
			var FBUserEmail = '';
			
		    FB.init({ appId: '170454853029332', status: true, cookie: true, xfbml: true, oauth: true });
	          
	          function FBRenderProfile(response){
	          	var FBUserInfo;
	          	FB.api('/me', function(response){
	           		userAuthWrapper.html('<img class="fb_user_avatar left" src="https://graph.facebook.com/'+response.id+'/picture" style="margin-right:5px"/><span class="fb_user_name left">'+response.name+'</span><a id="fb_login" class="fb_logout left" href="javascript:void(0)"><img src="/images/logout_fb_btn.png" alt="facebook login button" /></a>');
	           		userAuthWrapper.addClass('logged_in_fb_panel');
	           		var fbBtn = document.getElementById('fb_login');
	           		fbBtn.style.display = 'inline';
	           		fbBtn.onclick = FBLogout;
	           		FBUserName = response.name;
	           		FBUserEmail = response.email;	
	           		$.ajax({
	           			url: '/lib/ajax/fb_user.php?uid='+response.id+'&name='+response.name+'&email='+response.email,
	           			success: function(result){
	           			
	           			}
	           		});
	           	});	
	          }
	          
	           function FBLogIn(){
	           		FB.login(function(response){
	           			if(response.authResponse){
	           				ffg = FBRenderProfile(response);
	           				var uid = response.authResponse.userID;	
	           				$('#login_panel').hide();
	           				if($('#comment_input').length > 0){
		           				$.ajax({
									url: '/lib/ajax/comments_load.php',
									beforeSend: function(){
										$('#comment_input').html(loader);
								    },
									success: function(result){
										
										$('#comment_input').html(result);
										$logged_in = $('#user_id').length;
										$user_id = $('#user_id').val();
										attachInputFocus();
										attachCommAddClick();
									}
								});
							}
	           			}else{
	           				//alert('User cancelled login or did not grant authorization.');
	           			}
	           			
	           		}, {scope: 'email'});
	           }
	           function FBLogout(){
	           		FB.logout(function(response){
	           			//alert('User logged out!');
	           			userAuthWrapper.html(userAuthWrapperContent);
	           			userAuthWrapper.removeClass('logged_in_fb_panel');
	           			$('#user_auth_inner a').show();
	           			$('#login_btn').click(loginBtnClick);
	           			var fbBtn = document.getElementById('fb_login');
	           			fbBtn.onclick = FBLogIn;
	           			if($('#comment_input').length > 0){
		           				$.ajax({
									url: '/lib/ajax/comments_load.php',
									beforeSend: function(){
										$('#comment_input').html(loader);
								    },
									success: function(result){
										$('#comment_input').html(result);
										$logged_in = $('#user_id').length;
										$user_id = $('#user_id').val();
										//loadComments(); //verovatno nije potreban za sada (provera)
										attachInputFocus();
										attachCommAddClick();
										var fbBtnInp = document.getElementById('fb_login_input');
										fbBtnInp.onclick = FBLogIn;
									}
								});
							}
	           		});
	           }
	        if($('#fb_connect').val() == 'enable'){
	        	
	           FB.getLoginStatus(function (response) {
	            	if(response.status == 'connected'){
	            		//alert('user is connected');
	            		FBRenderProfile(response);
	            		var fbBtn = document.getElementById('fb_login');
	            		var uid = response.authResponse.userID;
	   					var accessToken = response.authResponse.accessToken;
	   					fbBtn.onclick = FBLogout;
	            	}else if(response.status == 'not_authorized'){
	            		//alert('The user is logged in on facebook, but not connected to app.');	
	            		$('#user_auth_inner a').show();
	            		var fbBtn = document.getElementById('fb_login');
	            		fbBtn.onclick = FBLogIn;
	            		if($('#comment_input').length > 0){
		            		var fbBtnInp = document.getElementById('fb_login_input');
		            		fbBtnInp.onclick = FBLogIn;
		            	}
	            	}else{
	            		//alert('The user is not logged in on facebook.');	
	            		$('#user_auth_inner a').show();
	            		var fbBtn = document.getElementById('fb_login');
	            		fbBtn.onclick = FBLogIn;
	            		if($('#comment_input').length > 0){
		            		var fbBtnInp = document.getElementById('fb_login_input');
		            		fbBtnInp.onclick = FBLogIn;
		            	}
	            	}
	           }); 
	         }else{
        		$('#user_auth_inner a').show();
       	  	 }
	        };
        
	var $newsletter = $('#newsletter');
	var bodyId = $('body').attr('id');
	
	(function($) {
    $.fn.goTo = function() {
        $('html, body').animate({
            scrollTop: $(this).offset().top + 'px'
        }, 'fast');
        return this; // for chaining...
    }
	})(jQuery);
/*
* LOGIN
*/
	var loginPanel = $('#login_panel');
	function loginBtnClick(e){
		loginPanel.toggle();
		$('#login_username').focus();
		
		e.stopPropagation();
	}
	$('#login_btn').click(loginBtnClick);
	
	$(document).click(function() {
    	loginPanel.hide();
	});
	loginPanel.click(function(e){
		e.stopPropagation();
	});

	//NAPOMENA: submit formu na enter za IE uraditi
	function addInputClickEvent(input, btn) {
		var btn = $('#'+btn);
		var input = $('#'+input);
	    input.keydown(function(e) {
	        e = e || window.event;
	        if (e.keyCode == 13) {
	            btn.click();
	            return false;
	        }
	    });
	}
	
	if(document.all){ // if its IE
		addInputClickEvent('login_password','login_submit');
		addInputClickEvent('login_username','login_submit');
	}
	
	//image preload
	if (document.images) {
	    img1 = new Image();
	    img1.src = "../images/login_panel.png";
	    img1 = new Image();
	    img1.src = "../images/pagemenu-sub-bg.png";
	}
/*	
 * 
 */
	
	$('#subsc_btn').click(function(){
		$.ajax({
			url: '/lib/ajax/subscription.php',
			type: 'POST',
			data: 'email='+$newsletter.val(),
			success: function(result){
				if(result.indexOf('error:')>-1){
					$('#subscr_wrapper p').html(result.replace('error: ',''));
					return;
				}
				$('#subscr_wrapper').html('<p>'+result+'</p>');
			}
		});
	});
	$('#page_top').click(function(){
		$('body').goTo();
	});
	
	//VIDEO TAGS FORM SUBMIT 
	
	if(document.video_tag_form){
		var videoTags = document.getElementById('video_tags').getElementsByTagName('a');
		var videoTagForm = document.video_tag_form;
		for(var i=0;i<videoTags.length;i++){
			videoTags[i].onclick = function(){
				videoTagForm.external_input.value = this.innerHTML;
				document.video_tag_form.submit();
			}	
		}
	}	
	  
/*
 * NEWS ROTATOR
 */
if($('.main_view .window').length>0){
	//Show the paging and activate its first link
	$(".paging").show();
	$(".paging a:first").addClass("active");
	$(".paging img:first").attr('src','/images/news_rotator/paging_active.gif');
	
	//Get size of the image, how many images there are, then determin the size of the image reel.
	var imageWidth = $(".window").width();
	var imageSum = $(".image_reel div.item").size();
	//alert(imageSum);
	var imageReelWidth = imageWidth * imageSum;
	
	//Adjust the image reel to its new size
	$(".image_reel").css({'width' : imageReelWidth});
}
//Paging  and Slider Function
rotate = function(slide){
	if(!slide){
		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide
		
		$(".paging #paging_steps a").removeClass('active'); //Remove all active class
		$(".paging #paging_steps a img").attr('src','/images/news_rotator/paging_inactive.gif');
		$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)
		$active.find('img').attr('src','/images/news_rotator/paging_active.gif');
		
		//Slider Animation
		$(".image_reel").animate({
			left: -image_reelPosition
		}, {queue:false, duration:500});
	}else{
		var actA = $(".paging #paging_steps a.active");
		var actImg = $('#paging_steps img[src="/images/news_rotator/paging_active.gif"]');
		var reelPos = parseInt($('.image_reel').css('left'));
		if(reelPos % imageWidth!=0)
			return;
		$(".paging #paging_steps a").removeClass('active');
		$(".paging #paging_steps a img").attr('src','/images/news_rotator/paging_inactive.gif');
		if($active.attr("rel") == 'left'){
				reelPos += imageWidth;
				var prev = actA.prev('a');
				if(prev.length != 0){
					prev.addClass('active');
					prev.find('img').attr('src','/images/news_rotator/paging_active.gif');
				}else{
					$(".paging #paging_steps a:last").addClass("active");
					$(".paging #paging_steps a:last").find('img').attr('src','/images/news_rotator/paging_active.gif');
					reelPos = -(imageReelWidth-imageWidth);
				}
		}else{
			reelPos -= imageWidth;
			var next = actA.next('a');
			if(next.length != 0){
				next.addClass('active');
				next.find('img').attr('src','/images/news_rotator/paging_active.gif');
			}else{
				$(".paging #paging_steps a:first").addClass("active");
				$(".paging #paging_steps a:first").find('img').attr('src','/images/news_rotator/paging_active.gif');
				reelPos = 0;
			}
		}
		//alert(reelPos);
		$('.image_reel').animate({
			left: reelPos	
		}, {queue:false, duration:500});
		
	}
}; 
	
	//Rotation  and Timing Event
rotateSwitch = function(){
	play = setInterval(function(){ //Set timer - this will repeat itself every 7 seconds
		$active = $('.paging #paging_steps a.active').next(); //Move to the next paging
		if ( $active.length === 0) { //If paging reaches the end...
	    	$active = $('.paging #paging_steps a:first'); //go back to first
	    }
	    rotate(); //Trigger the paging and slider function
	}, 7000); //Timer speed in milliseconds (7 seconds)
};
	
if($('.main_view .window').length>0){
	rotateSwitch(); //Run function on launch
	
	//On Hover
	$(".image_reel a").hover(function() {
	    clearInterval(play); //Stop the rotation
	}, function() {
	    rotateSwitch(); //Resume rotation timer
	});	
	
	//On Click
	$(".paging #paging_steps a").click(function() {
	    $active = $(this); //Activate the clicked paging
	    //Reset Timer
	    clearInterval(play); //Stop the rotation
	    rotate(); //Trigger rotation immediately
	    rotateSwitch(); // Resume rotation timer
	    return false; //Prevent browser jump to link anchor
	});
	if($('.paging #slide_ctrl').length>0){
		$(".paging #slide_ctrl a").click(function(){
			$active = $(this);
			clearInterval(play);
			rotate(true);
			rotateSwitch();
			return false;
		});
	}
}

/*
 * 
 */

/*
 *  FEATURE SLIDER
 */
	if($('#features_slider').length > 0){
		var $slider = $('#features_inner');
		var $channels = $slider.children('div');
		//alert($channels.length);
		for(var i = 0;i < $channels.length;i++){
			var width = $channels[i].getElementsByTagName('div').length * 209;
			//alert(width);

			$channels[i].style.width = width+'px';
			//alert($channels[i].getElementsByTagName('div').length);
		}
		var jsp = $('#features_inner:visible').jScrollPane({
			maintainPosition: false
		}).data('jsp');
		
		$('#features_nav a').click(function(){
			var $rel = $(this).attr('rel');
			$(this).siblings().removeClass('active_feat');
			$(this).addClass('active_feat');
			$slider.find('div.channel_item').removeClass('active_tab');
			$('#'+$rel).addClass('active_tab');
			//alert($('#'+$rel).css('width'));
			jsp.getContentPane().css('width', $('#'+$rel).css('width'));
			//alert(typeof jsp);
			jsp.reinitialise();
		});
		
		
		
		
		
	}
/*
 * 
 */


/*
 * jCarousel
 */

$('#photo_carousel').jcarousel({
	scroll: 1,
	//wrap: 'circular', /* problem se javlja kada ima manje slika u wrapperu  */
	animation: 'fast'
});

// article jcarousel version

if($('img#current_image').length>0){
	$('#photo_carousel img').click(function(){
		$('img#current_image').attr('src',$(this).parent('a').attr('rel'))
		return false;
	});
}
/*
 * 
 */

/*
 *  articles
 */

if($('#art_cat_nav').length>0){
	
	url = '/lib/ajax/paging_articles_cat.php';
	var catLinks = $('#art_cat_nav a');
	var articlesPage = $('#article_by_cat');

	var artHeading = $('#art_cat_heading h2');
	$.ajax({
	  url: url+'?cat_id='+$('#art_cat_nav a').attr('rel'),
	  beforeSend: function(){
	    $('#article_by_cat').html(loader);
	  },
	  success: function(result) {
	  	articlesPage.html(result);
		artHeading.html('Muzika');
		catLinks.removeClass('active_cat');
		catLinks.first().addClass('active_cat');
	  	buildPagination();
	  	
	  }
	});
	catLinks.click(function(){	
		var $obj = $(this);
		$.ajax({
			url: url+'?cat_id='+$(this).attr('rel'),
			beforeSend: function(){
				$('#articles_wrapper').html(loader);
			},
			success: function(result) {
			    articlesPage.html(result);
			    artHeading.html($obj.html());
				catLinks.removeClass('active_cat');
				$obj.addClass('active_cat');
			    buildPagination();
		    }
		});
	});
}
	/*
 * AJAX - HASH CHANGE
 */

	$(window).hashchange( function(){
		/*var hash = location.hash;
		var catLinks = $('#art_cat_nav a');
		if(hash != ''){
		
			document.title = 'The hash is ' + ( hash.replace( /^#/, '' ) || 'blank' ) + '.';
	
			catLinks.each(function(){
				var that = $(this);
				that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'active_cat' );
			});
		}*/
	});

	//$(window).hashchange();
});
var loader = '<img id="ajax_loader" src="/images/ajax-loader.gif" alt="Loading animation" />';
function buildPagination(){
	//if server dont return pagination
	$paginLinks = $('#pagination a');
	if($paginLinks.length<=0)
	  		return;
	url = '/lib/ajax/paging_articles_cat.php';  		
	  		
	  		
	////if server return pagination  
	$paginLinks.click(paginClick); 
	$paginLinks.first().addClass('active_page');
	  		
	$paginLinks.parent().prepend('<a id="previous_page" href="javascript:void(0)">Prethodna</a>');
	$paginLinks.parent().append('<a id="next_page" href="javascript:void(0)">Sledeca</a>');
	
	var $active = $('#pagination a.active_page');
	$('#previous_page').bind('click', { param: 'left' }, paginClick);

	$('#next_page').bind('click', { param: 'right' }, paginClick);

}

function paginClick(event){
	var $evtTarg = $(this);
	if(event.data === null){ //code for pagination numbers
		
		$.ajax({
			url: url+'?cat_id='+$('#current_cat_id').val()+'&limit='+$(this).attr('rel'),
			beforeSend: function(){
				$('#articles_wrapper').html(loader);
			},
			success: function(result) {
				$('#articles_wrapper').css('opacity','0');
				$('#articles_wrapper').html(result);
				$('#articles_wrapper').animate({
					opacity: 1
				}, 200);
				$paginLinks.removeClass('active_page');
				$evtTarg.addClass('active_page');
			    window.scrollTo(0,0);  	
			}
		});
	}else{ //code for previous and next buttons
		var $active = $('#pagination a.active_page');
		
		if(event.data.param == 'left'){
			var $new_active = $active.prev('a[rel]');
		}else if(event.data.param == 'right'){
			var $new_active = $active.next('a[rel]');
		}
		if($new_active.length > 0){
			//alert(loader);
			$.ajax({
				url: url+'?cat_id='+$('#current_cat_id').val()+'&limit='+$new_active.attr('rel'),
				beforeSend: function(){
					$('#articles_wrapper').html(loader);
				},
				success: function(result) {
					$('#articles_wrapper').css('opacity','0');
					$('#articles_wrapper').html(result);
					$('#articles_wrapper').animate({
						opacity: 1
					}, 200);
					$active.removeClass('active_page');
					$new_active.addClass('active_page');
					window.scrollTo(0,0);  
				}
			});
		}
	
	}

}

window.onload = function(){
	var bgBanners = document.getElementById('bg_banners_wrap');
	
	if(bgBanners){
		bgBannersPosition();
	}
}

function bgBannersPosition(){
	var $bgBannersBoth = $('div.banners_bg');
		
	var bannerImgWidth1 = $bgBannersBoth.eq(0).find('img').width()+2;
	var bannerImgWidth2 = $bgBannersBoth.eq(1).find('img').width()+2;
		
	$bgBannersBoth.eq(0).css('margin-left','-'+bannerImgWidth1+'px');
	$bgBannersBoth.eq(1).css('margin-right','-'+bannerImgWidth2+'px');
	
	$bgBannersBoth.css('visibility', 'visible');
}


