/* Modal Authentication */
$(function() {
	//Polyfill to make trim available in all browsers before IE9
    if (!String.prototype.trim) {
		  String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
    }
    
	$.ajaxSetup({
		cache: false,
		timeout: 8000
	});
});

function trimInput(elem) {    
  //trim() is only built in for IE9+ but rp.js now includes a polyfill above
  elem.value = elem.value.trim();
}


function log(s) {
    if(window.console)
        console.log(s);
}

function isLoginRequest(url) {
    return url.indexOf('/j_spring_security_check')>=0;
}

var htmlCache={};
function loadHtml(template, fn) {
    var split = template.split(' ', 2);
    if(htmlCache[split[0]])
        fn(htmlCacheAsJQuery(split));
    else
        $.get(split[0], function(response, status, xhr) {
            htmlCache[split[0]] = response;
            fn(htmlCacheAsJQuery(split));
        });
}
function htmlCacheAsJQuery(split) {
    var $elm = $(htmlCache[split[0]]);
    if(split.length==2) {
        var $elm = $('<div/>').append($elm).find(split[1]);
    }
    return $elm;
}

function SimpleSuccessModal(title, message, onClose, opts) {
	return new ModalDialogue($.extend(true, {}, opts, {
		template: '/sso/html/common-dialogues.html #simple-success-modal',
		init: function($modal) {
			$modal.find("h4").text(title);
			$modal.find("p").text(message);
		},
		close: function() {
			if(onClose) onClose();

		},
		title: title
	}));
}

/**
 * required options
 *  template: name of template,
 *  init(modalElement): function to be run after modal is created
 *
 */
function ModalDialogue() {
    var self = (this);
    var opts = arguments[0];
    var init=opts["init"];
    if(!init) alert("must provide init function");

    var template=opts["template"];
    if(!template) alert("must provide template name");

    this.create = function() {

        if(opts["validator"])
            if(!opts.validator(opts)) return;

        loadHtml(template, function($modal) {
            self.modal=$modal;

            var dOpts={
                    modal:true,
                    resizable: false,
                    width: 400,
                    maxHeight: 400,
                    minHeight: 80
            };

            $modal.dialog(dOpts);

            // set up cancel button
            $modal.find("button.cancel").click(self.close);
            $modal.find("button.close").click(function(){
                self.close();
                if( opts["close"] )
                    opts["close"]();
            });

            // -- could do a generic button handler e.g.
            // $modal.find('button').click(function() {
            //      opts[ $(this).attr('id') ]($modal);
            // });

            init($modal);
        });
    };
    this.baseUrl = function() {
        return opts['baseUrl'];
    };
    this.messages = opts['messages'];

    this.close = function() {
        self.modal.dialog('destroy');
        self.modal.remove();
    };

}

function SelfRegisterModal(opts, guestUser) {
    var self = new ModalDialogue($.extend(true, {}, opts, {
        template: '/sso/html/common-dialogues.html #self-register-modal',
        init: function($modal) {
            $modal.find('.ok').click(function() {
                $.ajax({
                    type: 'POST',
                    url: 'account/selfRegister.html',
                    data: $modal.find('form').serialize() + "&guestUser=" + guestUser,
                    success: function(response) {
                    	if( response.status.error ) {
                    		var errMsg = $modal.find('div.error p');
                    		errMsg.append(response.status.message);

                            var errors=$modal.find('div.error ul');
                            errors.parent().show();
                            errors.empty();

                            $(response.payload).each(function(index, item) {
                                errors.append($('<li>').text(item));
                            });
                        } else {
                            var success=new SimpleSuccessModal("Register",
                                    response.status.message ? response.status.message : "Registration was successful",
                                    function() {
                                    	// Need to remove force and renew parameters
                                    	$('#login-loader').dialog('destroy');
                                    	var oldURL = document.URL;
                                    	var newURL = oldURL.replace(/&?((force)|(renew))=([^&]$|[^&]*)/gi, "").replace("?&", "?");
                                    	window.location.replace(newURL);
                                    });
                                    
                            self.close();
                            success.create();
                        }
                    },
                    dataType: 'json'
                });
            });
        }
    }));
    
    return self;
}

function ResetPasswordModal(opts) {
    var self = new ModalDialogue($.extend(true, {}, opts, {
        template: '/sso/html/common-dialogues.html #reset-password-modal',
        init: function($modal) {
        	function doReset() {
                $.ajax({
                    type: 'POST',
                    url: 'account/resetPassword.html',
                    data: $modal.find('form').serialize(),
                    success: function(response) {
                        if( response.status.error ) {
                        	var errMsg = $modal.find('div.error p');
                    		errMsg.append(response.status.message);

                            var errors=$modal.find('div.error ul');
                            errors.parent().show();
                            errors.empty();
                            $(response.payload).each(function(index, item) {
                                errors.append($('<li>').text(item));
                            });
                        } else {
                            var success=new SimpleSuccessModal("Password reset",
                                    response.status.message ? response.status.message : "We have sent you a new password.");
                            self.close();
                            success.create();
                        }
                    },
                    dataType: 'json'
                });
            }
        	$modal.find('form').submit(function(e) {
	    		e.preventDefault();
	    		e.stopPropagation();
	    		doReset();
	    	});
            $modal.find('.ok').click(doReset);
        }
    }));
    return self;
}

