// JavaScript Document
var rootPath = '/';
var mainUrl = 'http://www.dansetsu.pl';

var scriptsToAppend = '<link href="' + rootPath + 'default/styles/jsglobal.css" rel="stylesheet" type="text/css" media="screen"/>';
document.write(scriptsToAppend);

// main function
$(document).ready(function(){
	if($('.breadCrumbTrailContainer').length){
		$('.breadCrumbTrailContainer ul li:last-child').addClass('lastChild');
	}
	
   appendUserCloud.init();
   
	if ( $('#episodesBox').length > 0 ){
      initEpisodesCategoriesBox();
      episodesBox.init();
   }
   if ( $('#shoutBoxForm').length >0 ){
      shoutBox.init();
   }
   if ( $('#shoutBox').length >0 ){
      shoutBoxNav.init();
   }
   if ( $('#articleMenu').length >0 ){
      articleMenu.init();
   }
   if ( $('#animeShortBox').length >0 ){
      animeShortBox.init();
   }
   if ( $('#animelistWidok').length >0 ){
      $('#colorpicker').farbtastic('#dan_form_color');
   }
   if ( $('#animeListContent').length >0){
      $('#animeListBg').css("height", $('#animeListContent').height());
      $('#animeListContentWrapper').css("height", $('#animeListContent').height());
   }
	$('#jsRequiredContainer').remove();	
});

var popup = {
	show: function(message, type, append){
		var popup = $('#popup');
		var className = 'popup' + type.substr(0, 1).toUpperCase() + type.substr(1);

		if(!popup.length){
			$('#content').prepend('<div id="popup" class="' + className + '">' + message + '<div>');
		} else {
			var html = '<p>' + message + '</p>';
			if(append){
				popup.append(html);	
			} else {
				popup.html(html)
				popup.removeClass();
				popup.addClass(className);
			}
		}
	}
}

//expanding jQuerry functions
  $.fn.setCursorPosition = function(pos) {
    if ($(this).get(0).setSelectionRange) {
      $(this).get(0).setSelectionRange(pos, pos);
    } else if ($(this).get(0).createTextRange) {
      var range = $(this).get(0).createTextRange();
      range.collapse(true);
      range.moveEnd('character', pos);
      range.moveStart('character', pos);
      range.select();
    }
  }

// shoutbox ajax form
var shoutBox = {
   init: function(){
      setInterval( "updateContent", 10000 );
		
      $('#shoutBoxForm #dan_form_submit').click(function(){
      var content= $('#shoutBoxForm #dan_form_content').val();
		if(content.length == 0){
			alert('Najpierw wpisz wiadomość.');
			return false;	
		}
		if(content.length > 500){
			alert('Maksymalnie 500 znaków.');
			return false;	
		}
      $.ajax({
         url: 'ajax/shoutbox',
         type: 'POST',
         data: 'content=' + content,

         success: function(result){
         $('#shoutBoxContent').html(result);

         }
      });
		clearForm();
		return false;// disable the default action of the submit action

      });
   }
}

//nie sprawdza, tylko pobiera z htmla, nie mozna jej ufac. wiec tylko do spraw blachych.
var auth = {
	hasIdentity: function(){
		if($('#profileBox').length){
			return true;	
		} else {
			return false;	
		}
	},
	getIdentity: function(){
		if(this.hasIdentity()){
			return $('#profileBox a.username').text();
		} else {
			return null;	
		}
	}
}

// shoutBox helper functions
function updateSBContent(bbCode, type){
   if (type=="smile"){
      $('#dan_form_content').val($('#dan_form_content').val()+bbCode);
   } else {
      var bbTags = new Array('[b]','[/b]','[i]','[/i]','[u]','[/u]','[quote]','[/quote]','[img]','[/img]','[url]','[/url]');
      if ($('#dan_form_content')[0].selectionEnd-$('#dan_form_content')[0].selectionStart > 0){
         wrapText('dan_form_content',bbTags[bbCode],bbTags[bbCode+1])
      } else {
         $('#dan_form_content').val($('#dan_form_content').val()+bbTags[bbCode]+bbTags[bbCode+1]);
         $('#dan_form_content').focus();
         $('#dan_form_content').setCursorPosition($('#dan_form_content').val().length-bbTags[bbCode+1].length);
      }
   }
  // $('#shoutBoxBBCode > div').css("visibility", "hidden");
  //  $('#shoutBoxBBCode > div').css("height", 0);
}

function showBBHelper(id){
    $('#'+id).toggle();
}

function updateContent(){
$.ajax({
         url: 'ajax/shoutbox',
         type: 'POST',

         success: function(result){
         $('#shoutBoxScrollContent').html(result);

         }
      });
}

function wrapText(elementID, openTag, closeTag) {
    var textArea = $('#' + elementID);
    var len = textArea.val().length;
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    var selectedText = textArea.val().substring(start, end);
    var replacement = openTag + selectedText + closeTag;
    textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}

function clearForm(){
   $('#dan_form_content').val("");
}
//shoutBox navigation arrows
var shoutBoxNav = {
   init: function(){
      var itemToScroll = $('#shoutBoxScrollContent');
      var realHeight = itemToScroll[0].scrollHeight;
      $('.shoutBoxArrowDown').hover(
         function(){
            var scrollTo = itemToScroll.css('top');
            itemToScroll.animate({
               top: '-='+scrollTo
            }, 1500 );
         },
         function(){
            itemToScroll.stop(true, false).animate();
         }
      );
     $('.shoutBoxArrowUp').hover(
         function(){
            var scrollTo = parseInt(itemToScroll.css('top').replace('px','')) + realHeight + 'px';
            itemToScroll.animate({
               top: '-='+scrollTo
            }, 1500 );
         },
         function(){
            itemToScroll.stop(true, false).animate();
         }
      );
   }
}


//newsBox
var newsBox = {
	show: function(dir){
		var cnt = $('#newsBox .news').size();
	
		for(var i=1; i<=cnt; i++){
			if($('#newsBox .current').hasClass('n'+i)){
				var next = $('#newsBox .n'+(i+dir));
				if(next.length){
					$('#newsBox .current').removeClass('current');
					next.addClass('current');
					break;
				}
			}
		}
	},
	showNext: function(){
		this.show(1);
	},
	showPrev: function(){
		this.show(-1);
	}
}


//episodesCategoriesBox
function initEpisodesCategoriesBox() {
	if(!$('#episodesCategoriesBox ul').length){
		return false;
	}

	$('#episodesCategoriesBox ul ul').hide();

	//zaznaczanie wedle adresu
	var cnt = mainUrl.length;
	var currentUrl = '/' + document.location.href.substring(cnt + 1);

	if(currentUrl != '/'){
		$("a[href='"+currentUrl+"']").addClass('selected');
	}

	$('#episodesCategoriesBox ul a.selected').parents("ul").show();

	//dodaje selected tez dla rodzicow
	$('#episodesCategoriesBox ul a.selected').parents("li").children('a').addClass('selected');

	$('#episodesCategoriesBox ul li:last').addClass('lastChild');

	$('#episodesCategoriesBox ul li a').click(
		function() {
			$('#episodesCategoriesBox ul a.selected').removeClass('selected');
			$(this).addClass('selected');

			var checkElement = $(this).next();
			var parent = this.parentNode.parentNode.id;

			if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
				//ajax(this);
				if(parent){
					$('#' + parent + ' ul:visible').slideUp('normal');
				}
				checkElement.slideDown('normal');
				return false;
			}
		}
	);
}


var episodesBox = {
	isPending:  false,
	seriesChunks:	null,

	showTab: function(name){
		$('#episodesBox .header .selected').removeClass('selected');
		$('#episodesBox .header .' + name + 'Link').addClass('selected');

		if(!this.isPending){
			this.isPending = true;
			$('#episodesBox .currentTab').removeClass('currentTab').hide('slow', function(){;
				$('#episodesBox .' + name).addClass('currentTab').show('slow', function(){
					episodesBox.isPending = false;
				});
			});
		}
	},
	init: function(){
		/*$('#episodesBox .tab').each(function(i){
			if(!$(this).hasClass('currentTab')){
				$(this).hide(0);
			}
		});*/

		//przygotuj podzial wszystkich serii na grupy alfabetyczne
		var lastFirstLetter = null;

		var rest = new Array();
		var others = true;
		var chunks = new Object();
		chunks.rest = new Array();
		var newFirstLetter = null;
		
		$('#episodesBox .series .columns ul li').each(function(i){
			newFirstLetter = $(this).text().substr(0,1).toLowerCase();
			var ep = {name: $(this).text(), url: $(this).children('a').attr('href')};
			
			//oblsuga tego co jest przed litera a
			if(newFirstLetter.match(/^[^a-z]$/)){
				chunks.rest.push(ep)							
			} else {
				if(!chunks[newFirstLetter]){
					chunks[newFirstLetter] = new Array();
				}
				chunks[newFirstLetter].push(ep);
			}
		});
		
		episodesBox.seriesChunks = chunks;
		/*episodesBox.seriesChunks = new Array();
		episodesBox.seriesChunks.push(rest);

		//przeindeksowanie na liczby
		var charCodeRange = {
			start: 97,
			end: 122
		}
		for (var cc = charCodeRange.start; cc <= charCodeRange.end; cc++) {
			var letter = String.fromCharCode(cc);
			
			if(chunks[letter]){
				//alert(letter);
				episodesBox.seriesChunks.push(chunks[letter]);
			} else {
				//alert('ok');
				episodesBox.seriesChunks.push(new Array());
			}
		}*/

	},

//series
	showSeries: function(dir){
		var cnt = $('#episodesBox .series .listContainer .columns').size();

		for(var i=1; i<=cnt; i++){
			if($('#episodesBox .series .listContainer .currentSerie').hasClass('c'+i)){
				var next = $('#episodesBox .series .listContainer .c'+(i+dir));
				if(next.length){
					$('#episodesBox .series .listContainer .currentSerie').removeClass('currentSerie');
					next.addClass('currentSerie');
					break;
				}
			}
		}
	},
	showNextSeries: function(){
		episodesBox.showSeries(1);
	},
	showPrevSeries: function(){
		episodesBox.showSeries(-1);
	},
//alphaseries
	showAlphaSeries: function(index){
		//zaznacz biezaca litere
		$('#episodesBox .series .alphabet ul li a.selected').removeClass('selected');
		$('#episodesBox .series .alphabet ul li a').each(function(i){
			if($(this).text().toLowerCase() == index){
				$(this).addClass('selected');
			}
		});
		//zabierz 1 bo 0 to wszystkie i nie ma ich w tej tablicy
		//index = index - 1;
		$('#episodesBox .series .listContainer').hide('slow', function(){

			$('#episodesBox .series .subListContainer .columns').hide('slow', function(){
				$('#episodesBox .series .subListContainer .columns').empty();

				//pokaz wszystkie
				if(index == '666'){
					$('#episodesBox .series .listContainer').show('slow');
					return;
				}
				
				if(!episodesBox.seriesChunks[index]){
					return;
				}
				//podziel na 3 kolumny
				var length = episodesBox.seriesChunks[index].length;
				var columnLength = Math.ceil(length / 3);
				for(var i=0; i<3; i++){
					episodesBox.appendColumn(episodesBox.seriesChunks[index].slice(i * columnLength, (i + 1) * columnLength), i);
				}

				$('#episodesBox .series .subListContainer .columns').show('slow');
			});

		});
	},
	appendColumn: function(series, index){
		$('#episodesBox .series .subListContainer .columns').append('<ul class="ac'+index+'"></ul>');
		var ul = $('#episodesBox .series .subListContainer .columns ul.ac'+index);
		for(var i=0; i < series.length; i++){
			ul.append('<li><a href="' + series[i].url + '">' + series[i].name + '</a></li>');
		}
	}
};

var articleMenu = {
   init: function(){
      $('#menu>li>ul>li.dir').click(
      function(){
         $(this).children('ul').children('li').toggle();

      }
   )
   }
};

var currentlyWatching = {
	episode_id:null,
	user_id:null,
	
   init: function(episode_id, user_id){
		this.episode_id = episode_id;
		this.user_id = user_id;
		
		setInterval(function(){
			$.getJSON('/ajax/update-currently-watching', {episode_id: episode_id, userId: user_id}, function(data){

			});									
		}, 180000 );
   }
};

var animeShortBox = {
   init: function(){
      $('#animeShortBox img').click(function(){
         $('#animeShortBoxMenu').toggle();
      });
      $('#animeShortBoxMenu').hover(
         function(){
         },
         function(){
            $(this).hide();
         }
      );
		$('#animeShortBoxMenu a').click(function(){
			//var url = $(this).attr('href');
			//$.getJSON(url, {is_ajax:1}, function(data){
			//	popup.show(data.message, data.type);
			//});
			//return false;
		});
   }
}
function showEpisodesList(userId, status, seriesId){
      $('#episodesFromSeries'+seriesId+' span').toggle();
      $.ajax({
      url: '/ajax/getepisodeslist/',
      type: 'POST',
      data: 'userId=' + userId +'&status=' + status +'&seriesId=' + seriesId,
      success: function(result){
         var html = ""
         $.each( jQuery.parseJSON(result), function(i, val){
         html += val.name + "<br/>"
         });
         $('#episodesFromSeries'+seriesId+' span').html(html);
      }
      });
}

function setStyle(value){
      var data = value.split(';');
      if (data[0] == "") {
         alert('Wybierz element');
      } else {
      $.ajax({
      url: '/ajax/setStyle/',
      type: 'POST',
      data: 'value=' + data[1] +'&element=' + data[0],
      success: function(result){ 
         var data = result.split(';');
         $('#animeListEditTable table tbody tr td#'+data[0]).css('background-color', data[1]);
      }
      });
      }
}

var appendUserCloud = {
   init: function(){
      $('.avatar').hover(
        function(){
            username = $(this).attr('href').split('/').pop();
            
				if(username == auth.getIdentity()){
					return false;										  
			   }
				
				$(this).append('<div class="appendUserCloud">' + 
                           	'<a href="/wiadomosci/wyslij/do/' + username + '">Wyślij wiadomość</a>' +
                           	'<a href="/znajomi/zaproszenie/znajomy/' + username + '">Zaproś do znajomych</a>' +
										'<a href="/animelist/' + username + '/ogladalem">Zobacz listę anime</a>' +
                           '</div>'
				);
				
				var width = $(this).width();				
				var left = width - 12;
				$('.appendUserCloud').css('left', left + 'px');
        },
        function(){
            $('.appendUserCloud').remove();
        });
}
}

var episodePlayer = {
	url:null,
	domain:null,
	width:244, height:200,
	getPlayerUrl:'/getPlayer.php',
	
	init: function(){
		return;
		this.url = $('.fakedPlayer').attr('rel');
		//this.domain = this.getDomain(this.url);
		
		/*$.post(this.getPlayerUrl, {episode_link: this.url}, function(data){
			if(data){
				$('#episodePlayer').html(data);
				//alert(data);
			} else{
				$('.fakedPlayer').attr('href', $this.url);
				$('.fakedPlayer .loading').hide();
				$('.fakedPlayer span').show();				
				$('.fakedPlayer').attr('target', 'blank');
			}
		});*/
		var url = this.getPlayerUrl + '?episode_link=' + this.url;
		$('#episodePlayer').html('<object data="' + url + '" />');
	},
	
	anyfiles: function(){
		var arr = this.url.split('/');
		var episodeId = arr.pop();

      var playerUrl = 'http://video.anyfiles.pl/Draw?v=' + episodeId + ',' + this.width + ',' + this.height + '&r=0';
		$.get(playerUrl, function(data){
			if(data){
				$('.player').after('<script type="text/javascript">' + data + '</script>');
				$('.player').remove();
			}
	  	});
	},
	
	getDomain: function(url){
		return url.match(/:\/\/(www\.)?(.[^/:]+)/)[2];
	}
}

function appendDialogForm(formName, title, height, width){
      var fields = "";
 
      $.ajax({
      url: '/ajax/getformfields/',
      type: 'POST',
      async: false,
      dataType: 'json',
      data: 'name=' + formName,
      success: function(result){ 
          fields = result.toString().split(",");
        }
      });
      
      $.ajax({
      url: '/ajax/getform/',
      type: 'POST',
      async: false,
      data: 'name=' + formName,
      success: function(result){ 
              $('#container').append(
      '<div id="dialog-form" title="' + title + '">' + result + '</div>'
      );
        }
      });
   
     dialgogForm(fields, height, width);
     $( "#dialog-form" ).dialog( "open" );
}

function dialgogForm(fields, height, width){ 
    $( "#dialog:ui-dialog" ).dialog( "destroy" );


         //$.each(fields, function(key, value) { 
        //  alert(value); 
       // });
         		//var name = $( "#name" ),
			//email = $( "#email" ),
			//password = $( "#password" ),
			//allFields = $( [] ).add( name ).add( email ).add( password ),
		var field1 = $( "#dan_form_title" ),	
                    field2 = $( "#dan_form_content" ),	
                    field3 = $( "#dan_form_keywords" ),	
			allFields = $( [] ).add( field1 ).add( field2 ).add( field3 ),
			tips = $( ".validateTips" );

		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( n + " może być od " +
					min + " do " + max + "." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}

		$( "#dialog-form" ).dialog({
			autoOpen: false,
			height: height,
			width: width,
			modal: true,
			buttons: {
				"Zapisz": function() {
					var bValid = true;
					allFields.removeClass( "ui-state-error" );
					//bValid = bValid && checkRegexp( name, /^[0-9]+$/i, "Tylko cyfry." );
					//bValid = bValid && checkLength( name, "wysokość", 1, 3);

					if ( bValid ) { //alert(field1.val());
						//$( "#headerHeight" ).text(name.val());
                                                //$('#header').height(parseInt(name.val()));
						$( this ).dialog( "close" );
					}
				},
				"Anuluj": function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});

}
