function encodeToURL (string) 
{
	var inp = ['á', 'é', 'í', 'ú', 'ü', 'ű', 'ö', 'ő', 'ó', ' '];	
    var outp = ['a', 'e', 'i', 'u', 'u', 'u', 'o', 'o', 'o', '-'];
    	
    string = string.toLowerCase();
     
    for (var i = 0; i < inp.length; i++) 
    {
    	string = string.replace(inp[i], outp[i]);	
    }

    return string;
}

function getModule () 
{
	return $('input#module').val();
}

function getBaseUrl () 
{
	return $('base').attr('href');
}
			
function searchBySrc (image, src) 
{
	var ret;
	ret = false;
	
	if (image.length > 0) 
	{
		$.each(image, function (k, v){
			if ($(v).attr('src') == src) ret = v;
		}); 	
	}
	
	return ret;
}

function validLogin () 
{
	$('#loginError').html('');
	$('#loginError').hide();
	var error;
	var errorMessage = new Array();
	error = 0;
	
	if ($('#username').val() == '') 
	{
		error++;
		errorMessage.push('Felhasználónév megadása kötelező!');
	}
	
	if ($('#password').val() == '') 
	{
		error++;
		errorMessage.push('Jelszó megadása kötelező!');
	}
	
	if (error == 0) 
	{
		if ($('#password').val() != '' && $('#username').val() != '') 
		{		
			$.post('http://hhmm.hu/felhasznalok/getuserbydataajax/', {username: $('#username').val(), password: $('#password').val()}, function(data){				
				if (data == 'no') 
				{
					error++;	
					errorMessage.push('Nincsen felhasználó a megadott adatokkal!');
					
					if (errorMessage.length > 0) 
					{
						$.each(errorMessage, function(k, v) {
							$('#loginError').append(v + '<br />');	
						});	
					}
					return false;	
				}
				else 
				{
					error = 0;	
					return true;
				}
				
			});
		}	
	}
	else 
	{

			if (errorMessage.length > 0) 
			{
				$.each(errorMessage, function(k, v) {
					$('#loginError').append(v + '<br />');	
				});	
			}
			return false;	

	}
}

$(document).ready(function() {
	/*tinyMCE.init({
	    theme : "advanced",
	    mode : "textareas",
	    //mode : "exact",
	    elements : "description",
	    
	    theme: "advanced",
//	    plugins : "ajaxfilemanager,autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
	    plugins : "autolink,lists,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

        // Theme options
        theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,spellchecker,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,blockquote,pagebreak,|,insertfile,insertimage",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,
                
//        imagemanager_contextmenu: true
	});*/
	
	/*tinyMCE.init({
        // General options
        mode : "textareas",
        theme : "advanced",
        plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

        // Theme options
        theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
        theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Example content CSS (should be your site CSS)
        content_css : "css/example.css",

        // Drop lists for link/image/media/template dialogs
        template_external_list_url : "js/template_list.js",
        external_link_list_url : "js/link_list.js",
        external_image_list_url : "js/image_list.js",
        media_external_list_url : "js/media_list.js",

        // Replace values for the template plugin
        template_replace_values : {
                username : "Some User",
                staffid : "991234"
        }
	});*/

	
	var baseUrl = getBaseUrl();
	
	$('a.homeProjectCatLink').hover(
		function() {		
			var element = $(this);
			$('#indexBoxRight').find('#left').find('h1').text(element.text());			
			var newImg = element.attr('rel');	
			$('#indexBoxRight').find('#left').find('#content').html('<a href="' + element.attr('href') + '" alt="' + element.text() + '" title="' + element.text() + '"><img alt="' + element.text() + '" src="./upload/projects_images/last_' + newImg + '" /></a>');			
		},
		function () {
//			$('#indexBoxRight').find('#left').find('h1').text('');
//			$('#indexBoxRight').find('#left').find('#content').html('');
		}
	);
	
	$('a.homeProjectVideoLink').hover(
			function() {		
				var element = $(this);
				$('#indexBoxRight').find('#left').find('h1').text(element.text());			
				var newImg = element.attr('rel');					
				$('#indexBoxRight').find('#left').find('#content').html('<a href="' + element.attr('href') + '" alt="' + element.text() + '" title="' + element.text() + '"><img alt="' + element.text() + '" src="http://img.youtube.com/vi/' + newImg + '/0.jpg" width="360" height="320" /></a>');				
			},
			function () {
//			$('#indexBoxRight').find('#left').find('h1').text('');
//			$('#indexBoxRight').find('#left').find('#content').html('');
			}
	);
	
	$('a.homeProjectCatLink').click(function () {
//		return false;
	});
	
	function fetchProjects (cat, start) 
	{
		$('#projectListHolder').find('#picBoxHolder').load(baseUrl + getModule() + '/fetchProjects/' + cat + (start ? '/' + start : ''), {}, function(result) {
			var actualPage = $('.actualPage').attr('id').split('_')[1];
			var allPagerLinks = $('a.projectPager');
			
			$('a#projectListPrev').unbind();
			$('a#projectListNext').unbind();
			
			if (actualPage == 0 && allPagerLinks.length > 1) 
			{
				$('a#projectListPrev').css('background', 'none');
				$('a#projectListPrev').css('cursor', 'default');
				
				$('a#projectListPrev').click(function () {
					return false;
				});
			}
			else 
			{
				$('a#projectListPrev').css('background', '');
				$('a#projectListPrev').css('cursor', '');
				
				$('a#projectListPrev').click(function () {
					if ($(this).css('background') != 'none') 
					{
						fetchProjects ($('#actCategory').val(), (parseInt($('.actualPage').attr('id').split('_')[1]) - 1));
					}				
					
					return false;
				});
			}
			
			if (parseInt(actualPage) + 1 >= allPagerLinks.length) 
			{
				$('a#projectListNext').css('background', 'none');
				$('a#projectListNext').css('cursor', 'default');
				
				$('a#projectListNext').click(function () {
					return false;
				});
			}
			else 
			{
				$('a#projectListNext').css('background', '');
				$('a#projectListNext').css('cursor', '');
				
				$('a#projectListNext').click(function () {
					if ($(this).css('background') != 'none') 
					{
						fetchProjects ($('#actCategory').val(), (parseInt($('.actualPage').attr('id').split('_')[1]) + 1));
					}					
					
					return false;
				});
			}
			
			$("a.project_image").fancybox({
				'transitionIn'	:	'fade',
				'transitionOut'	:	'fade',
				'speedIn'		:	600, 
				'speedOut'		:	200,
				'padding'		: 	0,
				'cyclic'		: 	true,
				'onComplete'	:	function (e) {
					var pieces = $('img#fancybox-img').attr('src').split('/');
					if (e && e.length > 0) 
					{
						$.each (e, function (k, v) {
							if ($(v).attr('href').match(pieces[pieces.length - 1]))  
							{
								$('td#fancybox-title-float-main').html($(v).next('div.project_image_description').html());
							}
						});
					}
				}
			});
		});
	}
	
	function fetchVideos (start) 
	{
		$('#projectVideoListHolder').find('#picBoxHolder').load(baseUrl + getModule() + '/fetchVideos/' + (start ? '/' + start : ''), {}, function(result) {
			var actualPage = $('.actualPage').attr('id').split('_')[1];
			var allPagerLinks = $('a.projectPager');
			
			$('a#projectListPrev').unbind();
			$('a#projectListNext').unbind();
			
			if (actualPage == 0 && allPagerLinks.length > 1) 
			{
				$('a#projectListPrev').css('background', 'none');
				$('a#projectListPrev').css('cursor', 'default');
				
				$('a#projectListPrev').click(function () {
					return false;
				});
			}
			else 
			{
				$('a#projectListPrev').css('background', '');
				$('a#projectListPrev').css('cursor', '');
				
				$('a#projectListPrev').click(function () {
					if ($(this).css('background') != 'none') 
					{
						fetchVideos ((parseInt($('.actualPage').attr('id').split('_')[1]) - 1));
					}				
					
					return false;
				});
			}
			
			if (parseInt(actualPage) + 1 >= allPagerLinks.length) 
			{
				$('a#projectListNext').css('background', 'none');
				$('a#projectListNext').css('cursor', 'default');
				
				$('a#projectListNext').click(function () {
					return false;
				});
			}
			else 
			{
				$('a#projectListNext').css('background', '');
				$('a#projectListNext').css('cursor', '');
				
				$('a#projectListNext').click(function () {
					if ($(this).css('background') != 'none') 
					{
						fetchVideos ((parseInt($('.actualPage').attr('id').split('_')[1]) + 1));
					}					
					
					return false;
				});
			}

			$("a.project_image").click(function () {				
				jQuery.fancybox({
/*					overlayShow: true,
		            frameWidth:640,
		            frameHeight:360*/

					'padding'             : 0,
	                'autoScale'   		: false,
	                'transitionIn'        : 'none',
	                'transitionOut'       : 'none',
	                'title'               : this.title,
	                'width'               : 640,
	                'height'              : 480,
	                'href'                : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/') + '&autoplay=1',
	                'type'                : 'swf',    // <--add a comma here
	                'swf'                 : {'allowfullscreen':'true'}, // <-- flashvars here
					'transitionIn'	:	'elastic',
					'transitionOut'	:	'elastic',
					'speedIn'		:	600, 
					'speedOut'		:	200
				});
				
				return false;
			});
		});			
	}
	
	if (getModule() == 'projects' && $('#projectListHolder').length > 0) 
	{	
		fetchProjects ($('#actCategory').val());		
		
		$('a.projectPager').live('click', function () {			
			var element = $(this);				
			
			fetchProjects ($('#actCategory').val(), element.attr('id').split('_')[1]);
			return false;
		});
	}
	
	if (getModule() == 'projects' && $('#projectVideoListHolder').length > 0) 
	{	
		fetchVideos ();		
		
		$('a.projectPager').live('click', function () {			
			var element = $(this);				
			
			fetchVideos (element.attr('id').split('_')[1]);
			return false;
		});
	}
	
	if (getModule() == 'press' && $('.pressLink').length > 0) 
	{		
		$('.pressLink').click (function () {
			var element = $(this);
			
			$('#pressLeft').find('h2').text(element.find('.title').text());
			$('#pressLeft').find('div').html('');
			$('#pressLeft').find('div').load(baseUrl + getModule() + '/fetchPressImages/' + element.find('input[type=hidden]').val(), {}, function(result) {
				$('.pressLinkActive').removeClass('pressLinkActive').addClass('pressLink');
				element.removeClass();
				element.addClass('pressLinkActive');
				$('h1.pressHead').find('.left').text(element.find('.title').text());
				
				$("a.press_image").fancybox({
					'transitionIn'	:	'fade',
					'transitionOut'	:	'fade',
					'speedIn'		:	600, 
					'speedOut'		:	200,
					'padding'		: 	0,
					'cyclic'		: 	true
				});
			});
		});
					
		$('.pressLink:first').trigger('click');
	}
	
	if (getModule() == 'news' && $('.pressLink').length > 0) 
	{		
		$('.pressLink').click (function () {
			var element = $(this);
			
			$('#pressLeft').find('h2').text(element.find('.title').text());
			$('#pressLeft').find('div').html('');
			$('#pressLeft').find('div').load(baseUrl + getModule() + '/fetchNewsImages/' + element.find('input[type=hidden]').val(), {}, function(result) {
				$('.pressLinkActive').removeClass('pressLinkActive').addClass('pressLink');
				element.removeClass();
				element.addClass('pressLinkActive');
				$('h1.pressHead').find('.left').text(element.find('.title').text());
			});
		});
		
		$('.pressLink:first').trigger('click');
	}
	
	//if (getModule() == 'about' && $('.mp3Link').length > 0) 
	if (getModule() == 'about' && $('#jPlayer').length > 0) 
	{				
		var currentTrack = 0;
		var playList = [];
		$.each ($('.mp3Link'), function (k, v) {
			playList.push({
				title: $(v).text(),
				artist: 'József Vályi-Tóth',
				file: $(v).attr('href')
			});			
		});		

		// Switch track
		function playListChange(index, play) {
			//console.log('E');
			if (play == null) 
			{
				play = true;
			}				
		 
			currentTrack = index;
			$("#playerSongInfo").html(playList[currentTrack].artist + ' - <em>' + playList[currentTrack].title + '</em>');
			$("#jPlayer").jPlayer('setFile', playList[currentTrack].file);
		 
			if (play == true) 
			{
				$("#jPlayer").jPlayer('play');
			}
		}
	 
		// Play next track. If already on last track, start back at the begining
		function playListNext() {
			var index = (currentTrack + 1 < playList.length) ? currentTrack + 1 : 0;
			playListChange(index);
		}
	 
		// Play previous track. If already on first track, start back at the end
		function playListPrev() {
			var index = (currentTrack - 1 >= 0) ? currentTrack - 1 : playList.length-1;
			playListChange(index);
		}
	 
		$("#jPlayer").jPlayer({
			ready: function() {					
				playListChange(0); // Play first song
				$(".playSong").removeClass('selected');
				$($(".playSong")[0]).addClass('selected');
			},
			swfPath: baseUrl + "system/resources/js/",
			//errorAlerts: true,
            //warningAlerts: true,
			oggSupport: false
		})
		.jPlayer('onSoundComplete', playListNext);	 		
		
		$("#jplayer_prev").click(function() { playListPrev(); }); // Listen for Previous Track button click
		$("#jplayer_next").click(function() { playListNext(); }); // Listen for Next Track button click
		$(".playSong").click( function() {
//		$("#jplayer_play").click( function() {	
			if (!$(this).hasClass('selected')) 
			{
				$(".playSong").removeClass('selected');
				$(this).addClass('selected');
				index = parseInt($(this).attr('rel'));
				playListChange(index);
			}			
			return false;
		}); // Change to track defined by rel of link with playSong class
	}
	
	$('.adminListTable').find('.deleteButton').click(function () {
		var element = $(this);
		
		$('#deleteConfirmBox').remove();
		var box = $('<div id="deleteConfirmBox"></div>');
		$('body').append(box);
		
		var dialogButtons = new Object();
		dialogButtons['Yes'] = function () {
			location.href = element.attr('href');
			box.dialog("close");
		}
		
		dialogButtons['No'] = function () {
			box.dialog("close");
		}
		
		box.dialog({
			title: 'Are you sure to delete the selected item?',
			buttons: dialogButtons
		});
				
		return false;
	});	
	
	$('.adminListTable').find('.deleteImageButton').click(function () {
		var element = $(this);
		
		$('#deleteConfirmBox').remove();
		var box = $('<div id="deleteConfirmBox"></div>');
		$('body').append(box);
		
		var dialogButtons = new Object();
		dialogButtons['Yes'] = function () {
			location.href = element.attr('href');
			box.dialog("close");
		}
		
		dialogButtons['No'] = function () {
			box.dialog("close");
		}
		
		box.dialog({
			title: 'Are you sure to remove the selected image?',
			buttons: dialogButtons
		});
		
		return false;
	});	
	
	$('#projectsDropdownTrigger').click (function () {
		return false;
	});
	
	$('#newsHref').click (function () {
		return false;
	});
	
	$('#archiveHref').click (function () {
		return false;
	});
});
