/*--------------------------
 *- Generic User Functions -
 *--------------------------
 */
$(document).ready(function($) {
	
	/*----------------------------
	 *- Generic base64 functions -
	 *----------------------------
	 */
	$.fn.base64 = {
		// private property
		_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",
		// public method for decoding
		decode : function (input) {
			var output = "";
			var chr1, chr2, chr3;
			var enc1, enc2, enc3, enc4;
			var i = 0;
			input = input.replace(/[^A-Za-z0-9\-\_\=]/g, "");
			while (i < input.length) {
				enc1 = this._keyStr.indexOf(input.charAt(i++));
				enc2 = this._keyStr.indexOf(input.charAt(i++));
				enc3 = this._keyStr.indexOf(input.charAt(i++));
				enc4 = this._keyStr.indexOf(input.charAt(i++));
				chr1 = (enc1 << 2) | (enc2 >> 4);
				chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
				chr3 = ((enc3 & 3) << 6) | enc4;
				output = output + String.fromCharCode(chr1);
				if (enc3 != 64) {
					output = output + String.fromCharCode(chr2);
				}
				if (enc4 != 64) {
					output = output + String.fromCharCode(chr3);
				}
			}
			output = $.fn.base64._utf8_decode(output);
			return output;
		},
		// private method for UTF-8 decoding
		_utf8_decode : function (utftext) {
			var string = "";
			var i = 0;
			var c = c1 = c2 = 0;
			while ( i < utftext.length ) {
				c = utftext.charCodeAt(i);
				if (c < 128) {
					string += String.fromCharCode(c);
					i++;
				}
				else if((c > 191) && (c < 224)) {
					c2 = utftext.charCodeAt(i+1);
					string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
					i += 2;
				}
				else {
					c2 = utftext.charCodeAt(i+1);
					c3 = utftext.charCodeAt(i+2);
					string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
					i += 3;
				}
			}
			return string;
		}
	};
	
	/*-------------------------------
	 *- Generic authorize functions -
	 *-------------------------------
	 */
	$.fn.authorize = {
		_KEY : "fgkdflfdsEKWRFIOFOSlckdfkjd67765",
		_decodedLoginCookie: null,
		fancyBoxCfg : {
			padding : 0,
			overlayShow: true,
			hideOnOverlayClick: false,
			hideOnContentClick: false,
			enableEscapeButton: true,
			showCloseButton: false,
			onComplete : function() {
				$('form[name="login"] input[name="email"]').focus();
			},
			onClosed : function() {
				$.fn.authorize.resetLoginForm();
			}
		},
		autoLogon: function() {
			if (!this.isLoggedOn()) {
				var rememberMeCookie = $.fn.authorize.getDecodedCookie("fdmgRememberMe");
				if (rememberMeCookie) {
					$.fn.authorize.logon(rememberMeCookie[1], rememberMeCookie[2], 'yes', true);
				} else {
					$.fn.authorize.setState();
				}
			} else {
				$.fn.authorize.setState();
			}
		},
		resetLoginForm: function() {
	     	$('div#loginError').html('');
	     	$('form[name="login"] input[name="email"]').val('');
	     	$('form[name="login"] input[name="password"]').val('');
	     	$('form[name="login"] input[name="remember_me"]').val('');
		},
		init: function() {
			// login button in overlay
			$('form[name="login"] input').each(function() {
				var ua = $.browser;
				if ( ua.msie && ua.version.slice(0,3) == "6.0" ) {
					$(this).keyup(function(e) {
						if (e.keyCode == 13) {
							$(this).parents('form').submit();
							return false;
						}

						return true;
					});
				} else {
					$(this).keydown(function(e) {
						if (e.keyCode == 13) {
							$(this).parents('form').submit();
							return false;
						}
				
						return true;
					});
				}	
			});
			
			$('form[name="login"]').submit(function(e) {
				if ($.fn.authorize.logon($('form[name="login"] input[name="email"]').val(),
					  $('form[name="login"] input[name="password"]').val(),
					  $('form[name="login"] input[name="remember_me"]').val(), false)) {
					$.fancybox.close();
				} else {
					$('div#loginError').html('Verkeerde gebruiksnaam en wachtwoord combinatie');
					$('form[name="login"] input[name="email"]').focus();
				}
				return false;
			});
			
			$('a#closeFancybox').click(function(e) {
				$.fancybox.close();
				return true;
			});

			$('a[href="#login"]').click(function(e) {
				$('form[name="login"]').submit();
				e.preventDefault();
			});

			$('a.jqClickLogin').each(function() {
				$(this).attr("href", "#loginPopup");
				$(this).fancybox($.fn.authorize.fancyBoxCfg);
			});
		},
		isLoggedOn: function() {
			if (this._decodedLoginCookie == null) {
				this._decodedLoginCookie = $.fn.authorize.getDecodedCookie("fdmgLogon");
			}
			return this._decodedLoginCookie != null;
		},
		handleLogonReponse: function(data, textStatus, xmlHttpRequest) {
			$.fn.authorize.setState();
		},
		getDecodedCookie: function(cookieName) {
			var encoded64Cookie = $.cookie(cookieName);
			if (encoded64Cookie) {
				var encodedCookie = $.fn.base64.decode(encoded64Cookie);
			}
			if (encodedCookie) {
				var decodedCookie = "";
		    	for (var index = 0; index<encodedCookie.length; index++) {
		    		decodedCookie+=String.fromCharCode(encodedCookie.charCodeAt(index)^this._KEY.charCodeAt(index%this._KEY.length));
		    	}
		    	var shortDC = decodedCookie.substring(0, decodedCookie.lastIndexOf(','));
		    	return eval( "["+shortDC+"]");
		    } else { 
		    	return null;
		    }
		},
		logon: function(email, password, remember_me, async) {
			$.ajax({
				  type: 'POST',
				  url: publicationUrl+"handle_login",
				  data: {'email':email, 
						 'password': password,
						 'remember_me': remember_me,
						 'target': ''},
				  success: $.fn.authorize.handleLogonReponse,
				  dataType: 'json',
				  async: async
				});
			this.setState();
			return this.isLoggedOn();
		},
		setState: function() {

			// loginMenu
			if ($.fn.authorize.isLoggedOn()) {
				$('a#login').attr("href", "#logout");
				$('a#login').text("Uitloggen");
				$("a#login").unbind('click.fb');
				$("a#login").click(function() {
					$.cookie('fdmgLogon', null, {'path':'/'});
					$.cookie('fdmgRememberMe', null, {'path':'/'});
					$.fn.authorize._decodedLoginCookie = null;
					$.fn.authorize.setState();
				});
			} else {
				$('a#login').attr("href", "#loginPopup");
				$('a#login').text("Login");
				$("a#login").fancybox($.fn.authorize.fancyBoxCfg);
			}

			// commentBox
			if ($.fn.authorize.isLoggedOn()) {
		    	$('div#comment_login input[name="email"]').val($.fn.authorize._decodedLoginCookie[1]); 
		    	$('div#comment_login input[name="field(byline)"]').val($.fn.authorize._decodedLoginCookie[4]);
				$('div#comment_login').show();
				$('div#comment_nologin').hide();
		    } else {
		    	$('div#comment_login input[name="email"]').val(''); 
		    	$('div#comment_login input[name="field(byline)"]').val(''); 
				$('div#comment_login').hide();
				$('div#comment_nologin').show();
				
			}
		}
	};
	
	/*---------------------------------
	 *- Generic search form functions -
	 *---------------------------------
	 */
	$.fn.search = {
		init : function(formId, submitId, errorAdvancedSearch) {
			$('form[id="' + formId + '"] input, form[id="' + formId + '"] select').each(function() {
				$(this).keydown(function(e) {
			        if (e.keyCode == 13) {
			        	$('a[id="' + submitId + '"]').click();
			            return false;
			        }
			        return true;
			    });
			});
			$('a[id="' + submitId + '"]').click(function(e) {
				parseDateAndFormSubmit($('form[id="' + formId + '"]').get(0), errorAdvancedSearch);
				e.preventDefault();
			});
		}
	};
	
});

