/*
	Concept Studio's Ajax Plugin Engine
	Author: Hemmert Ferenc
	Copyright: Concept Studio 2009  All rights reserved.
	Duplication, or any use, or reuse in the whole or any part of this file without prior written permission is prohibited.
*/

var uniqueID = 0;

function InitAPE()
{
	/*
	 * Urlap plugin
	 */
	
	$('form.plugin-urlap').each(function(){
		var form = this;
		var cikk = $(this).attr('id');
		if (!cikk || cikk == "")
		{
			cikk = $(this).attr('name');
			if (!cikk || cikk == "")
				return;
		}
		var cikk = cikk.replace(/^form_(\d+)$/i, '$1');
		
		var params = ""; var first = true;
		$(this).find('input').each(function(){ params = params + (first?"":",") + $(this).attr('name'); first = false; })
		$(this).find('select').each(function(){ params = params + (first?"":",") + $(this).attr('name'); first = false; })
		$(this).find('textarea').each(function(){ params = params + (first?"":",") + $(this).attr('name'); first = false; })
		$(this)
			.append( $('<input type="hidden" name="op" value="SendCikkForm" />'))
			.append( $('<input type="hidden" name="Cikk" value="' + cikk + '" />'))
			.append( $('<input type="hidden" name="Params" value="' + params + '" />'))
			.attr('method', 'post')
			.attr('action', '/index.php');
		$(form).submit(function(e){
			var valid = true;
			$(this).find('input[name="Email"]').each(function()
			{
				if (!$(this).attr('value').match(/^([a-zA-Z0-9\_\+\-%\.]+)\@([a-zA-Z0-9\_\+\-%\.]+)\.([A-Za-z]{2,4})$/))
				{
					valid = false;
					alert("KÃ©rem valÃ³s email cÃ­met adjon meg!");
				}
			});
			if (valid)
			{
				$.post(
					'/index.php',
					$(form).serialize(),
					function(data) {
						$(form).hide();
						$(form).after(data);
						$(form).trigger('aftersubmit');
						}
				);
			}else{
				e.stopPropagation();
			}
			return false;
			});
		/*$(this).find('input[type=submit]').click(function(){
			
			return false;
		})*/
	});
	
	/*
	 * Google Docs
	 */
	
	$('a.plugin-googledocs').each(function(){
		var href = $(this).attr('href');
		if (href.match(/^http:\/\//))
		{
			$(this).attr('href', 'http://docs.google.com/viewer?url=' + escape($(this).attr('href')));
		}else{
			href = href.replace(/^\/?(.*)$/, '$1');
			href = $('base').attr('href') + href;
			href = href.replace(/\//g, '%2F');
			$(this).attr('href', 'http://docs.google.com/viewer?url=' + escape(href));
		}
	});
	
	
	/*
	 * Anchor fix plugin
	 */
	var anchorRe = /^\#(\w+)$/;
	$('a').each(function(){
		var aName = $(this).attr('href');
		if (aName && aName.match(anchorRe))
		{
			aName = aName.replace(anchorRe, '$1');
			$(this).attr('anchorLocation', aName);
			$(this).click(function(e){
				location.hash = $(this).attr('anchorLocation');
				return false;
			});
		}
		});
	
	/**
		Common preprocessors
	*/
	
	//img.plugin-rollover
	$('img.plugin-rollover').each(function(){
		var el = $(this);
		el.initImage = el.attr('src');
		el.rollOverImage = el.attr('alt');
		el.attr('alt', "");
		var imPath = el.attr('src').substr(0, el.attr('src').lastIndexOf("/"));
	
		el.mouseover(function(){el.attr('src', imPath + "/" + el.rollOverImage);});
		el.mouseout (function(){el.attr('src',  el.initImage);});
		});
	
	//img.plugin-imagelist
	$('img.plugin-imagelist').each(function(){
		var initialImage = $(this);
		var listRoot = $(this).parents('ul:eq(0)');
		//listRoot = (listRoot && (listRoot.length > 0)) ? listRoot[0] : null;
		if (listRoot.length === 0)
		{
			var p = $(this).parent();
			if (!p || !p.is('a'))
			{
				//p = $(this);
				$(this).wrap('<a></a>');
				$(this).parent().attr('href', $(this).attr('src'));
			}
			p = $(this).parent().parent();
			if (!p || !p.is('li'))
			{
				$(this).parent().wrap('<ul><li></li></ul>');
			}
			listRoot = $(this).parents('ul:eq(0)');
			//listRoot = (listRoot && (listRoot.length > 0)) ? listRoot[0] : null;
		}
		if (!listRoot) return false;
		if(!listRoot.hasClass('plugin-imagelist'))
			listRoot.addClass('plugin-imagelist').find('li').css('list-type', 'none');
		var imID = null;
		var reg = /file.php\?.*id=([0-9]*)&?.*$/;
		var fullURIScheme = true;
		if (!reg.test($(this).attr('src')))
		{
			reg = /\/([0-9]*)$/;
			fullURIScheme = false;
		}
		var ext = reg.exec($(this).attr('src'));
		if (ext)
			imID = ext[1];
		if (!imID)	return false;
		var imCat = CallIndexFunctionSync('GetFileCategory', {'Id' : imID, 'fmt' : 'JSON'}, 'json');
		if (!imCat)	return false;
		var imList = CallIndexFunctionSync('GetFileokFromCategory', {'Category' : imCat.id, 'fmt' : 'JSON'}, 'json');
		var thumbSize = GetImageWidth(this);
		listRoot.attr('thumbsize', thumbSize);
		var oldDisplay = listRoot.css('display');
		listRoot.css('display', 'none');
		var filteredCss = $(this).attr('class');
		if (filteredCss)
			filteredCss = filteredCss.replace(/plugin-imagelist/g, '');
		
		$.each(imList, function(){
			var im = this;//imList[i];
			var imgLink = fullURIScheme ?
					$('<a>').attr('href', '/file.php?id=' + im.id).append(
							$('<img>').attr('src', '/file.php?id=' + im.id + (thumbSize ? '&width='+thumbSize+'f' : ''))
							)
					:
					$('<a>').attr('href', '/image/' + im.id).append(
						$('<img>').attr('src', '/image/' + (thumbSize ? thumbSize + 'f/' : '')  + im.id)
						);
			if (filteredCss)
				imgLink.attr('class', filteredCss);
			
			if (im.id !== imID)
			{
				listRoot.append( $('<li>').append( imgLink ) );
			}else{
				imgLink.attr('class', $(initialImage).parent().attr('class'));
				imgLink.find('img').attr('class', $(initialImage).attr('class'));
				$(initialImage).parent().replaceWith( imgLink );
			}
			
			return true;
			});
		
		listRoot.css('display', oldDisplay);
		
		});
	
	/**
		JQuery LightBox integration
		Note: Licensed under a Creative Commons Attribution-Share Alike 2.5 Brazil License. 
	*/
	$('img.plugin-lightbox, img.plugin-lightbox-img').each(function()
	{
		var parent = $(this).parent();
		if (parent && !parent.hasClass('.plugin-lightbox') && !parent.is('a'))
		{
			$(this).wrap('<a></a>');
			$(this).parent().attr('href', $(this).attr('src')).addClass('plugin-lightbox');
		}
		if (parent && (!parent.hasClass('.plugin-lightbox') || !parent.hasClass('.plugin-lightbox-link')) && parent.is('a'))
		{
			parent.addClass('plugin-lightbox');
		}
	});
	
	if ($('a.plugin-lightbox, a.plugin-lightbox-link').length > 0)
	{
		Synchronized('plugin-lightbox', ['load'] , function(){ LoadLightbox(); });
		LoadCSS('/scripts/lightbox/css/jquery.lightbox-0.5.css');
		LoadScript('/scripts/lightbox/js/jquery.lightbox-0.5.pack.js', function()
		{
			/*setTimeout("$('a.plugin-lightbox').lightBox({fixedNavigation:true "
						+ ", imageLoading:'/scripts/lightbox/images/lightbox-ico-loading.gif'"
						+ ", imageBtnClose:'/scripts/lightbox/images/lightbox-btn-close.gif'"
						+ ", imageBtnPrev:'/scripts/lightbox/images/lightbox-btn-prev.gif'"
						+ ", imageBtnNext:'/scripts/lightbox/images/lightbox-btn-next.gif'"
						+ ", imageBlank:'/scripts/lightbox/images/lightbox-blank.gif'"
						+ ", overlayOpacity: 0.6"
						+ "});", 250);*/
			//setTimeout("LoadLightbox();", 250);
			SyncRelease('plugin-lightbox', 'load');
		});
	}
	
	
	/**
		Pyrobox integration
		License: CC-BY-SA http://creativecommons.org/licenses/by-sa/2.5/it/
	*/
	
	
	/**
		Galleriffic integration
		License: MIT License 
	*/
	if ($('img.plugin-galleriffic').length > 0)
	{
		//LoadCss('/scripts/galleriffic/galleriffic-common.css');
		LoadScript('/scripts/galleriffic/jquery.galleriffic.js', function()
		{
			$('img.plugin-galleriffic').each(function()
			{
				var list = $(this).closest('ul');
				if (list && (list.length > 0))
				{
					list.hide();
					//wrap ul in thumbs div
					list.addClass('thumbs');
					//list.addClass('noscript');
					list.find('a').addClass('thumb');
					list.find('a').after('<div class="caption"></div>');
					list.wrap('<div class="thumbs"></div>');
					
					var thumbs = list.closest('div.thumbs');
					if (thumbs && (thumbs.length > 0))
					{
						thumbs.addClass('navigation');
						
						//create master plugin container
						thumbs.wrap('<div class="plugin-galleriffic"></div>');
						thumbs.wrap('<div class="navigation-container"></div>');
						//create galleriffic containers
						/*thumbs.after('<div class="caption"></div>');
						thumbs.after('<div class="slideshow"></div>');
						thumbs.after('<div class="loading"></div>');
						thumbs.after('<div class="controls"></div>');*/
						
						//create pagination links
						thumbs.prepend(
							$('<a>').addClass('pageLink').addClass('prev').css('visibility', 'hidden').attr('title', 'Previous Page')
							);
						thumbs.append(
							$('<a>').addClass('pageLink').addClass('next').css('visibility', 'hidden').attr('title', 'Next Page')
							);
						//create main container
						thumbs.closest('div.navigation-container').after(
							$('<div>').addClass('content').append(
									$('<div>').addClass('slideshow-container').append(
										$('<div>').addClass('controls').css('display', 'none')
									).append(
										$('<div>').addClass('loader')
									).append(
										$('<div>').addClass('slideshow')
									)
								).append(
									$('<div>').addClass('caption-container').append(
										$('<div>').addClass('photo-index')
									)
								)
							);
						
						
						//set up layout
						var gallery = thumbs.closest('div.plugin-galleriffic');
						LoadCSS('/scripts/galleriffic/galleriffic-layout-basic.css');
						gallery.addClass('plugin-galleriffic-layout-basic');
						
						//add all galleriffic styles from image to list
						var galReg = /^plugin-galleriffic-height(\d+)$/;
						$.each($(this).attr('class').split(' '), function()
						{
							var res = galReg.exec(this);
							if (res && res[1])
							{
								gallery.css('height', res[1] + 'px');
							}
						});
					}
				}
			});
			LoadScript('/scripts/galleriffic/jquery.opacityrollover.js', function()
			{
				setTimeout("LoadGalleriffic();", 550);
			});
			//LoadGalleriffic();
		});
	}
	
	if ($('a.plugin-flowplayer').length > 0)
	{
		Synchronized('plugin-flowplayer', ['load', 'jquerytools'], function(){
			$('a.plugin-flowplayer').each(function(){
				
				var playerLink = $(this);
				var isLightbox = $(this).hasClass('plugin-video-lightbox');
				var isAutoplay = $(this).hasClass('plugin-video-autoplay');
				var isRepeat = $(this).hasClass('plugin-video-repeat');
				var isControlHidden = $(this).hasClass('plugin-video-hiddencontrols')
				var isSizeSet = false;
				var scaleReg = /^plugin-video-(\d+)x(\d+)$/;
				var scaleWidth = null;
				var scaleHeight = null;
				
				
				$.each($(this).attr('class').split(' '), function()
				{
					var res = scaleReg.exec(this);
					if (res && res[1] && res[2])
					{
						scaleWidth = res[1];
						scaleHeight = res[2];
						isSizeSet = true;
					}
				});
				
				if (!isSizeSet && !isLightbox)
				{
					var linkImage = $(this).find('img');
					if (linkImage.length > 0)
					{
						$(this)
							.css('display', 'block')
							.css('width', linkImage.width() + 'px')
							.css('height', linkImage.height() + 'px');
					}
				}
				
				if (isSizeSet && !isLightbox)
				{
					$(this)
						.css('display', 'block')
						.css('width', scaleWidth + 'px')
						.css('height', scaleHeight + 'px');
				}
				
				if ($(this).attr('href').match(/^\w*\//))
					$(this).attr('href', $('base').attr('href') + $(this).attr('href'));
				if (!isLightbox)
				{
					$(this).flowplayer({
							src: '/scripts/flowplayer/flowplayer-3.2.2.swf', 
							wmode: 'transparent'
							},
							{
							clip: {
									autoPlay : isAutoplay,
									onBeforeFinish: function(clip) {
										if(isRepeat)
										{
											playerLink.flowplayer(0).seek(0);
											playerLink.flowplayer(0).play();
										}
										}
							},
							onLoad: function(player) {
								playerLink.find('img').dispose();
								},
							plugins: {
									controls: isControlHidden ? null : {}
								}
							});
					if (isAutoplay)
					{
						if (!$(this).flowplayer(0).isLoaded())
							$(this).flowplayer(0).load();
						$(this).flowplayer(0).play();
					}
				}else{
					LoadCSS('/scripts/jquery/tools/overlay/overlay.css');
					var overlayDiv = $('<div class="overlay-div" id="flowplayer-overlay-' + uniqueID + '"></div>')
										.css('width', isSizeSet? scaleWidth + 'px' : $(this).css('width'))
										.css('height', isSizeSet? scaleHeight + 'px' :  $(this).css('height'))
										;
					var playerLink = $('<a id="flowplayer-link-' + uniqueID + '" class="flowplayer-link" href="' + $(this).attr('href') + '" ></a>')
										.css('display', 'block')
										.css('width', isSizeSet? scaleWidth + 'px' : $(this).css('width'))
										.css('height', isSizeSet? scaleHeight + 'px' :  $(this).css('height'));
					overlayDiv.append(playerLink);
					overlayDiv.appendTo($('body'));
					
					var player =  playerLink.flowplayer('/scripts/flowplayer/flowplayer-3.2.2.swf', {
						clip: {
							autoPlay: isAutoplay,
							onMetaData : function(clip) {
											/*overlayDiv.width(clip.width);
											overlayDiv.height(clip.height);
											playerLink.width(clip.width);
											playerLink.height(clip.height);*/
											}
							},
							onFinish: function(clip) {
											if(isRepeat)
												player.play();
											}
						});
					
					$(this).attr('rel', '#flowplayer-overlay-' + uniqueID).overlay({
						mask : 'lightgrey',
						oneInstance: false,
						onLoad: function(data){ this.getOverlay().find('a.flowplayer-link').flowplayer(0).load(); }
						});
					uniqueID++;
				}
				});
			});
		LoadScript('/scripts/flowplayer/flowplayer-3.2.2.min.js', function(){
			SyncRelease('plugin-flowplayer', 'load');
			});
		LoadScript('/scripts/jquery/tools/jquery.tools.min.js', function(){
			SyncRelease('plugin-flowplayer', 'jquerytools');
			});
	}
	
	/**
	 * Registration and email confirmation
	 */
	
	$('.plugin-registration').each(function(){
		var form = this;
		$(this).submit(function(e){
			var res = CallIndexFunctionSync("RegisterUser", 
					{
				"Email" : $(form).find('input[name="Email"]').attr('value'),
				"Nev" : $(form).find('input[name="Nev"]').attr('value')
				});
			$(form).hide();
			$(form).after(res);
			e.stopPropagation();
			return false;
		});
	});
	
	$('.plugin-confirmation').each(function(){
		var form = this;
		$(form).find('input[name="Token"]').attr('value', $(form).find('input[name="URLConfirm"]').attr('value'));
		$(this).submit(function(e){
			var p1 = $(form).find('input[name="Pass"]').attr('value');
			var p2 = $(form).find('input[name="Pass2"]').attr('value');
			if (p1 != p2)
			{
				alert('Figyelem: A jelszó és a megerõsítése nem egyezik!');
				e.stopPropagation();
				return false;
			}
			var res = CallIndexFunctionSync("ConfirmRegistration", 
					{
				"Token" : $(form).find('input[name="Token"]').attr('value'),
				"Password" : p1
				});
			$(form).hide();
			$(form).after(res);
			e.stopPropagation();
			return false;
		});
	});
	
}

function LoadCSS(cssFile)
{
	$('head').append('<link>');
	$('head').find(':last').attr({
				rel : 'stylesheet',
				type : 'text/css',
				href : cssFile
				});

}
var loadedScripts = [];
function LoadScript(jsFile, onLoadCallback)
{
	if ($('script[src="' + jsFile + '"]').length <= 0)
	{
		$.getScript(jsFile, onLoadCallback);
	}else{
		onLoadCallback();
	}
}

function LoadLightbox()
{
	$('a.plugin-lightbox, a.plugin-lightbox-link').lightBox({
		fixedNavigation:true,
		imageLoading:'/scripts/lightbox/images/lightbox-ico-loading.gif',
		imageBtnClose:'/scripts/lightbox/images/lightbox-btn-close.gif',
		imageBtnPrev:'/scripts/lightbox/images/lightbox-btn-prev.gif',
		imageBtnNext:'/scripts/lightbox/images/lightbox-btn-next.gif',
		imageBlank:'/scripts/lightbox/images/lightbox-blank.gif',
		overlayOpacity: 0.6
		});
}

function LoadGalleriffic()
{
	var onMouseOutOpacity = 0.67;
	$('div.plugin-galleriffic ul.thumbs li, div.plugin-galleriffic div.navigation-container a.pageLink').opacityrollover({
		mouseOutOpacity:   onMouseOutOpacity,
		mouseOverOpacity:  1.0,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'
	});
	
	$('div.plugin-galleriffic div.thumbs').each(function(){
		var list = $(this).find('ul.thumbs');
		list.show();
		var thumbSize = list.attr('thumbsize');
		var galWidth = $(this).width();
		var thumbNumber = Math.round(galWidth / thumbSize);
		galWidth = galWidth - ((thumbNumber + 2) * 2); 
		
		var gallery = $(this).galleriffic({
        delay:                     1500, 
        numThumbs:                 Math.round(galWidth / thumbSize) - 2,
        preloadAhead:              1,
        enableTopPager:            false,
        enableBottomPager:         true,
        maxPagesToShow:            Math.round((galWidth - 100) / 30) - 5,
        imageContainerSel:         'div.slideshow', 
        controlsContainerSel:      'div.controls',
        captionContainerSel:       'div.caption', 
        loadingContainerSel:       'div.loader', 
        renderSSControls:          false, 
        renderNavControls:         false, 
        playLinkText:              'Play',
        pauseLinkText:             'Pause',
        prevLinkText:              'Previous',
        nextLinkText:              'Next',
        nextPageLinkText:          'Next &rsaquo;',
        prevPageLinkText:          '&lsaquo; Prev',
        enableHistory:             false, 
        enableKeyboardNavigation:  true, 
        autoStart:                 false, 
        syncTransitions:           true, 
        defaultTransitionDuration: 1000, 
        onSlideChange:             function(prevIndex, nextIndex) {
						this.find('ul.thumbs').children()
							.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
							.eq(nextIndex).fadeTo('fast', 1.0);

						// Update the photo index display
						/*this.$captionContainer.find('div.photo-index')
							.html('Photo '+ (nextIndex+1) +' of '+ this.data.length);*/
					}, 
        onPageTransitionOut:           function(callback) {
						this.fadeTo('fast', 0.0, callback);
					}, 
        onPageTransitionIn:            function() {
						var prevPageLink = this.closest('div.navigation-container').find('a.prev').css('visibility', 'hidden');
						var nextPageLink = this.closest('div.navigation-container').find('a.next').css('visibility', 'hidden');
						
						// Show appropriate next / prev page links
						if (this.displayedPage > 0)
							prevPageLink.css('visibility', 'visible');

						var lastPage = this.getNumPages() - 1;
						if (this.displayedPage < lastPage)
							nextPageLink.css('visibility', 'visible');

						this.fadeTo('fast', 1.0);
						},
        onTransitionOut:       undefined, 
        onTransitionIn:        undefined, 
        onImageAdded:              undefined, 
        onImageRemoved:            undefined  
    	});
    
    $(this).closest('div.navigation-container').find('a.prev').click(function(e) {
		gallery.previousPage();
		e.preventDefault();
	});
	
	$(this).closest('div.navigation-container').find('a.next').click(function(e) {
		gallery.nextPage();
		e.preventDefault();
	});
    
    $(this).closest('div.navigation-container').find('a.next, a.prev, ul.thumbs').wrapAll(
    	$('<div class="thumb-container"></div>')
    	);
    
    
    if (thumbSize)
    {
    	$(this).find('li').css('display', 'block').css('width', thumbSize + 'px').css('text-align', 'center');
    	$(this).find('li a').css('display', 'block')
    		.css('width', thumbSize + 'px').css('height', thumbSize + 'px')
    		.css('text-align', 'center').css('vertical-align', 'center');
    	$(this).find('li a img').css('display', 'block')
    		.css('margin', 'auto')
    		.each(function(){
    			$(this).css('margin-top', Math.round((thumbSize / 2) - ($(this).height() / 2)));
    		});
    }
    
    
    });
    
}

