/***************************************************************
*  Copyright notice
*
*  (c) 2011 Peter Klein <pmk@io.dk>
*  All rights reserved
*
*  This script is free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/

(function($){

	$.fn.extend({

		//pass the options variable to the function
		accesspopup: function(options) {

			//Set the default values, use comma to separate the settings:
			var defaults = {
				loginPageUid		:	1,
				accessGrantedText	:	'Access granted',
				overlayOpacity		:	'0.7',
				afterLoad			:	null
			}

			var options =  $.extend(defaults, options);

			// Get the baseUrl in case the url is relative.
			var baseUrl = window.location.protocol+'//'+window.location.host+'/';
			var url = baseUrl + 'index.php?id=' + options.loginPageUid + '&ts=' + new Date().getTime();

			return $("a[href*='return_url=']",this).each(function() {

                // Display padlock icon in front of link (Or in the bottom right corner if the link is an image)
				if ($('img',this).length) {
					// If image then add a span inside the A tag.
					$(this).css({position : 'relative'}).append('<span class="lockedlinkimage"></span>')
				}
				else {
					// Add class to the A tag
					//$(this).addClass('lockedlink lockedlink-'+$(this).height());
					$(this).addClass('lockedlink lockedlink-'+Math.ceil($(this).css('font-size').replace(/px/ig, "")));
				}
				var linkTitle = $(this).attr('title');
				linkTitle = (linkTitle ? linkTitle + ' - ' : '') + options.linkTitle;
				$(this).attr('title',linkTitle).click(function(event) {
					event.preventDefault();

					var link = unescape($(this).attr('href')), ref = link.replace(/.*?return_url=([^&\s]*).*/g, "$1"), pageId = link.replace(/.*?pageId=([^&\s]*).*/g, "$1");

					// Create popup and overlay elements
					$('body').append(
						'<div id="tx-pmkaccesspopup-popup" style="display:none;"><div id="tx-pmkaccesspopup-outerpopup"><div id="tx-pmkaccesspopup-innerpopup"><div id="tx-pmkaccesspopup-close"></div><div id="tx-pmkaccesspopup-content"><div id="tx-pmkaccesspopup-preload"></div></div></div><div style="clear:left;"></div></div></div><div id="tx-pmkaccesspopup-overlay"></div>'
					);

					// Save current BODY overflow state.
					var bodyOverflow = $('body').css('overflow');
					//$('body').css('overflow','hidden'); // Prevent background scrolling
					
					// Add click event to closebutton
					$('#tx-pmkaccesspopup-close').attr('title',options.closeTitle).css({
					}).click(function(event) {
						var reload = $('.tx-felogin-pi1','#tx-pmkaccesspopup-content').length==0;
						$(this).unbind('click').remove();
						$('#tx-pmkaccesspopup-popup').remove();
						$('#tx-pmkaccesspopup-overlay').remove();
	
						// Restore BODY overflow state.
						$('body').css('overflow',bodyOverflow);					

						// Popup does not contain felogin plugin when closed, so reload main page
						if (reload) {
							window.location.href = window.location.href;
							return false;
						}
					});

					// Add click event to overlay and fade it into view.
					$('#tx-pmkaccesspopup-overlay').attr('title',options.closeTitle).click(function() {
						var reload = $('.tx-felogin-pi1','#tx-pmkaccesspopup-content').length==0;
						$(this).unbind('click').remove();
						$('#tx-pmkaccesspopup-popup').remove();

						// Restore BODY overflow state.
						$('body').css('overflow',bodyOverflow);					

						// Popup does not contain felogin plugin when closed, so reload main page
						if (reload) {
							window.location.href = window.location.href;
							return false;
						}
					}).css({
						opacity: '0'
					}).animate({
						opacity: options.overlayOpacity
					},500,function() {

	  					var h = $(window).height(), w = $(window).width(), st = $(window).scrollTop(), sl = $(window).scrollLeft();
						// Display the popup box in the center of the screen
/*
						$('#tx-pmkaccesspopup-popup').css({
							display: 'block',
							position: 'absolute',
							top: (((h-$('#tx-pmkaccesspopup-popup').height())/2) + st)+'px',
							left: (((w-$('#tx-pmkaccesspopup-popup').width())/2) + sl)+'px'
						});
*/
						$('#tx-pmkaccesspopup-popup').css({
							display: 'block',
							position: 'absolute',
							top: (((h-$('#tx-pmkaccesspopup-popup').height())/4) + st)+'px'
						});

						var loadForm = function() {
	 						//$("#tx-pmkaccesspopup-content input[name=redirect_url]").val(ref);
	 						$("#tx-pmkaccesspopup-content input[name=redirect_url]").val('');
							$("#tx-pmkaccesspopup-content input[name=tx_felogin_pi1\\[noredirect\\]]").val(1);
							$("#tx-pmkaccesspopup-content form#loginform-popup").attr('action',url+'&pageId='+pageId+'&return_url='+ref);
							if ($.trim($('#tx-pmkaccesspopup-content').text())==options.accessGrantedText) {
								//alert('redirect to: '+ baseUrl + ref);
								document.location.href = baseUrl + ref;
								return false;
							}
							else if (typeof options.afterLoad == 'function'){
								options.afterLoad.call(this);
							}
						}

						// Add live event to the felogin form in the popup
						$('#tx-pmkaccesspopup-content form#loginform-popup').live('submit',function(event) {
							event.preventDefault();
							$('#tx-pmkaccesspopup-content').load(url+'&pageId='+pageId+'&return_url='+ref+' .csc-default:first', $(this).serialize(),function() {
		 						loadForm();
							});
						});

						// Load initial AJAX content into popupbox
						$('#tx-pmkaccesspopup-content').load(url+'&pageId='+pageId+'&return_url='+ref+' .csc-default:first',function() {
							loadForm();
						});
					});
				});
			});
		}
	});
})(jQuery);

