// $('.news-headline-box').css({'visibility':'hidden'});


$(document).ready(function(){
	
	//resizeMenu();	
	createGallery();
	
    // init menu
	if (typeof(qm_create) == "function" && typeof(sd)!="undefined") {
		qm_create(0, false, 0, 500, false, false, false, false, false);
	}
	
	// News headlines preview  
    var nh_enebled = true;
    var nh_newsBg = '/img/basic_template/sipka.png';
	var nh_mover = 1;
	var nh_visibleCount = 3;
	var nh_count = $('.news-headline-ul > li').size();

	$('.news-headline-box').css({'visibility':'visible'});
	$('.news-headline-up,.news-headline-down').hide();
   
    if (nh_enebled) {
		if (nh_count > nh_visibleCount) {
			$('.news-headline-up', '.news-headline-down').show();
		}

	    function nhTogle(x, src){
	        $('#new-head-img-view').css('background-image', 'url(' + src + ')');
	        $('.news-headline-ul > li').css('background-image', 'none');
	        $(x).css('background-image', 'url(' + nh_newsBg + ')');
	        $('.news-headline-li-hover-color').removeClass('news-headline-li-hover-color');
	        $(x).addClass('news-headline-li-hover-color');
	        $(x).find('a').addClass('news-headline-li-hover-color');
	        $(x).find('p').addClass('news-headline-li-hover-color');
	    }
		
		function moveNews(dir){
			if (nh_count > nh_visibleCount) {
				if (dir == 'up') {
					$('.news-headline-ul li:nth-child(' + nh_mover + ')').hide();
					$('.news-headline-ul li:nth-child(' + (nh_mover + nh_visibleCount) + ')').fadeIn();
					nh_mover += 1;
				}
				if (dir == 'down') {
					$('.news-headline-ul li:nth-child(' + nh_mover + ')').fadeIn();
					$('.news-headline-ul li:nth-child(' + (nh_mover + nh_visibleCount) + ')').hide();
					nh_mover -= 1;
				}
				
				if (nh_mover > nh_count - nh_visibleCount - 1) {
					nh_mover = nh_count - nh_visibleCount - 1;
				}
				if (nh_mover < 1) {
					nh_mover = 1;
				}
			}
        }
		
        $('.news-headline-content').append('<div id="new-head-img-view" class="rounded"></div>');
        $('.news-headline-ul > li').each(function(i, x){
            var src = $(x).find('img').attr('src');
            var url = $(x).find('a').attr('href')
            
            $(x).bind('click', function(){
                window.location.href = url;
            });
            $('#new-head-img-view').bind('click', function(){
                window.location.href = url;
            });
            $(x).bind('mouseover', function(){
                nhTogle(x, src);
            });
            if (i == 0) {
                nhTogle(x, src);
            }
            if (i > 2) {
                $(x).css('display', 'none');
            }
            $('.news-headline-item-img').hide();
        });
        
        $('.news-headline-up').bind('click mouseover', function(m){
            moveNews('up');
        });
		 $('.news-headline-down').bind('click mouseover', function(m){
            moveNews('down');
        });
    }
	
	// init shadowbox
    // http://www.shadowbox-js.com/options.html
    /*
	if (typeof(Shadowbox) == "object"){
	    Shadowbox.init({
	        handleOversize: "drag"
	    });
	}
	*/
});

// flash msg popup
$('#flashMessage').ready(function(){
	var f = $('#flashMessage');
	if (f.length>0) {
		var winW = $(document).width();
		var winH = $(document).height();
		$('body').prepend('<div class="popupWindow"></div>');
		$('.popupWindow').width(winW).height(winH).fadeTo("slow", 0.7).click(function(x){
			hideAll(x);
		});
		f.addClass('flashPopup').prependTo('body').width(winW - 80).click(function(x){
			hideAll(x);
		});
		function hideAll(x){
			$('#flashMessage').fadeOut("slow", function(){
				$(this).hide();
			});
			$('.popupWindow').fadeOut("slow", function(){
				$(this).hide();
			});
		}
	}
});


function resizeMenu(){
	console.log('resize menu');
 		var sw  = $('#stacks').height() || 0;
		var pw  = $('#stack_1 > .page-box').height() || 0;
		var mw  = $('.navigation_submenu_list').height();
		$('.navigation_submenu_list').css('margin-top',sw-pw-(mw));
		$('#stacks').bind('resize', null, 'resizeMenu');
}

/**
 * insert code to page:
 * <div id="player"> Loading ...</div><script type="text/javascript" >$(document).ready(function(){loadPlaylist('https://gdata.youtube.com/feeds/api/playlists/FF1AA6E5C2887C6B?v=2')});</script>
 */	
function loadPlaylist(url){
	var d=new Date().getTime();
	$.getJSON('/pls?q='+encodeURIComponent(url), function(data) {
	    if(data.data){
        		var toPlay = false, img, cn=1;
        		for(var i in data.data){
        			var item = data.data[i];
        			var img = getScreen(item.link,'small') ;
        			toPlay = item.link;
        			img = pushImage(img, item.link, item.title, item.description);
        			// add first
        			if (toPlay!=false && cn==1){
	        			toPlay = parseYid(toPlay);	        			
	        			$('#player').tubeplayer('play', toPlay);
	        			createPlayer(toPlay);
	        			$('.page-box h1').html(item.title);
	        			img.fadeTo(500,1).attr('selected',1);
        			}
        			cn++;
        		}
	        return true;
	    } else {
	        return false;
	    }
	});
}

function createPlayer(video){
	if (!video) video = "QFgNlg_uraY";
	jQuery("#player").tubeplayer({
		width: 600, // the width of the player
		height: 450, // the height of the player
		initialVideo: video,
		allowFullScreen: "true", // true by default, allow user to go full screen
		preferredQuality: "hd720",// preferred quality: default, small, medium, large, hd720
		onPlay: function(id){}, // after the play method is called
		onPause: function(){}, // after the pause method is called
		onStop: function(){}, // after the player is stopped
		onSeek: function(time){}, // after the video has been seeked to a defined point
		onMute: function(){}, // after the player is muted
		onUnMute: function(){} // after the player is unmuted
	});
}

function pushImage(img, link, title, desc){
	if (!img || img == '') return;
	if (!title) title = '';
	if (!desc) desc = '';
	var fader = 0.6;
	var img;
	$("#stack_1 > .page-box")
		.append(
			img = $("<div class='show-img' style='background-image:url(" + img + ")' ref='"+ link +"'>")
				.fadeTo(500, fader)
				.bind('mouseover', function(){ $(this).fadeTo(500, 1);  })
				.bind('mouseout', function(){ 
					var t = $(this);
					if (t.attr('selected')!=1){
						t.fadeTo(500, fader)
					}
				})
				.bind('click', function(){ 
					$('.show-img').fadeTo(500, fader).attr('selected',0);
					$(this).fadeTo(500, 1).attr('selected',1);  
					$('#player').tubeplayer('play', parseYid(link));
					
					$('.page-box h1').html(title);
					$('#player').parent().find('p').remove();
					$('#player').after('<p>' + desc + '</p>');
				})
	);
	return img;
}


function getScreen( url, size )	{
	
  if(url === null){ return ""; }

  size = (size === null) ? "big" : size;
  var vid;
  var results;
  results = url.match("[\\?&]v=([^&#]*)");
  vid = ( results === null ) ? url : results[1];

  if(size == "small"){
    return "http://img.youtube.com/vi/"+vid+"/2.jpg";
  }else {
    return "http://img.youtube.com/vi/"+vid+"/0.jpg";
  }
}

function parseYid(url){
	var results = null;
	if(url === null){ return ""; }
	results = url.match("[\\?&]v=([^&#]*)");
	vid = ( results === null ) ? url : results[1];
	return vid; 
}

/**
 * Gallery
 */

function createGallery(){
	var link = false;
	var cn = 1;
	$.each($('a[rel^=lightbox]'), function (){
		var a = $(this).attr('href');
		var img = $(this).find('img').attr('src');
		
		if (cn==1){
			link = a;
			pushImg(img, a, 1);
		} else {
			pushImg(img, a);
		}
		cn++;
		$(this).remove();
	});
	if (link){
		$('#stack_2 .page-body').append(
			$('<img src="'+ link +'" width="580" />').fadeTo(500, 1)
		);
	}
}

function pushImg(img, link, fader){
	if (!img || img == '') return;
	if (!fader) fader = 0.5;
	return $("#stack_1 .page-box")
		.append(
			$("<div class='show-img' style='background-image:url(" + img + ")' ref='"+ link +"'>")
				.fadeTo(500, fader)
				.bind('mouseover', function(){ 
					$(this).fadeTo(500, 1);  
				})
				.bind('mouseout', function(){
					var t = $(this); 
					if (t.attr('selected')!=1){
						t.fadeTo(500, fader);  
					}
				})
				.bind('click', function(){ 
					$('.show-img').fadeTo(500, fader).attr('selected', 0);;
					$(this).fadeTo(500, 1).attr('selected', 1);
					$('#stack_2 .page-body > img').remove();
					$('#stack_2 .page-body').append(
						$('<img src="'+ link +'" width="580" />').fadeTo(500, 1)
					);
					console.log(link);
				})
		);
}


