var FarskapRegContainer = Class.create({
    initialize: function(extId) {
        this.extId = extId;
        this.personIndex = 0;
    },

    addPerson: function(personObj, afterFinish) { //,parentId
        var extId = this.extId;
        new Ajax.Request('/index.php', {
            method: 'POST',
            parameters: {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'addPerson',
                'regPerson' : 'sure',
                'tittel' : personObj.tittel,
                'fornavn' : personObj.fornavn,
                'etternavn' : personObj.etternavn,
                'born1' : personObj.born1,
                'born2' : personObj.born2,
                'ansvar' : personObj.ansvar
            },
            onSuccess: afterFinish
        });
        this.personIndex += 1;
    },

    editPerson: function(index, afterFinish) {
        var extId = this.extId;
        new Ajax.Request('/index.php', {
            method: 'GET',
            parameters: {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'editPerson',
                'regPerson' : 'sure',
                'pIndex' : index
            },
            onSuccess: afterFinish
        });
    },

    getPersonObject: function(index, afterFinish) {
        var extId = this.extId;
        new Ajax.Request('/index.php', {
            method: 'GET',
            parameters:  {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'getObject',
                'regPerson' : 'sure',
                'pIndex' : index
            },
            onSuccess: afterFinish
        });
    },

    getPersonList: function(index, afterFinish) {
        var extId = this.extId;
        new Ajax.Request('/index.php', {
            method: 'GET',
            parameters: {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'getPersonList',
                'regPerson' : 'sure',
                'pIndex' : index,
                'languageCode' : $('langCode').value
            },
            onSuccess: afterFinish
        });
    },

    removePerson: function(index, afterFinish) {
        var extId = this.extId;
        new Ajax.Request('/index.php', {
            method: 'GET',
            parameters: {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'removePerson',
                'regPerson' : 'sure',
                'pIndex' : index
            },
            onSuccess: afterFinish
        });
        this.personIndex -= 1;
    },

    addContant: function(contantObj, afterFinish) {
        var extId = this.extId;
        var Aksunders="Nei";
        if($('aksunders').checked == true)
           Aksunders="Ja";
        new Ajax.Request('/index.php', {
            method: 'POST',
            parameters: {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'addContact',
                'regPerson' : 'sure',
                'navn': contantObj.navn,
                'epost': contantObj.epost,
                'adresse': contantObj.adresse,
                'telefon': contantObj.telefon,
                'postnr' : contantObj.postnr,
                'sted' : contantObj.sted,
                'kommentar': contantObj.kommentar,
                'aksunders': Aksunders
            },
            onSuccess: afterFinish
        });
    },

    addContant2: function(contantObj, afterFinish) {
        var extId = this.extId;
        new Ajax.Request('/index.php', {
            method: 'POST',
            parameters: {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'addContact2',
                'regPerson' : 'sure',
                'navn': contantObj.navn,
                'epost': contantObj.epost,
                'adresse': contantObj.adresse,
                'telefon': contantObj.telefon,
                'postnr' : contantObj.postnr,
                'sted' : contantObj.sted
            },
            onSuccess: afterFinish
        });
    },

    removeContact: function() {
        var extId = this.extId;
        new Ajax.Request('/index.php', {
            method: 'POST',
            parameters: {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'removeContact',
                'regPerson' : 'sure'
            },
            onSuccess: afterFinish
        });
    },

    removeContact2: function() {
        var extId = this.extId;
        new Ajax.Request('/index.php', {
            method: 'POST',
            parameters: {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'removeContact2',
                'regPerson' : 'sure'
            },
            onSuccess: function() {

            }
        });
    },

    getContactObject: function(afterFinish) {
        var extId = this.extId;
        new Ajax.Request('/index.php', {
            method: 'GET',
            parameters:
            {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'getContactObject',
                'regPerson' : 'sure'
            },
            onSuccess: afterFinish
        });
    },

    getContactObject2: function(afterFinish) {
        var extId = this.extId;
        new Ajax.Request('/index.php', {
            method: 'GET',
            parameters: {
                'c_' : 'FarskapRegSkjema2',
                'm_' : 'modifyForm',
                'extid' : extId,
                'method' : 'getContactObject2',
                'regPerson' : 'sure'
            },
            onSuccess: afterFinish
        });
    },

    confirmForm: function(afterFinish, elemId) {
        var extId = this.extId;
        
        document.location.href = "/index.php?c_=FarskapRegSkjema2&m_=modifyForm&extid=" +
            extId + "&method=confirmForm&regPerson=sure&paymenthod=" + elemId;
        
//        new Ajax.Request('/index.php', {
//            method: 'GET',
//            parameters: {
//                'c_' : 'FarskapRegSkjema2',
//                'm_' : 'modifyForm',
//                'extid' : extId,
//                'method' : 'confirmForm',
//                'regPerson' : 'sure',
//                'paymethod' : elemId
//            },
//            onSuccess: afterFinish
//        });
    }
});

var FarskapReg = Class.create({
    initialize: function(extId) {
        var self = this;
        this.contact2isActive = false;
        this.registeredPersons = 0;
        this.currentForm = new FarskapRegContainer(extId);
        this.preLoadEvents();
        this.ansvarElem = false;
        this.updateList();
        this.getContantInfo();
    },
	
    getContantInfo: function() {
        if($('btnSaveContact')) {
            var Aksunders="Nei";
            if($('aksunders').checked == true)
                Aksunders="Ja";
            this.currentForm.getContactObject(
                function(transport) {
                    var object = transport.responseText.evalJSON();
                    $('knavn').value = object.navn,
                    $('email').value = object.epost,
                    $('adr').value = object.adresse,
                    $('tlf').value = object.telefon,
                    $('postnr').value = object.postnr,
                    $('sted').value = object.sted,
                    $('kommentar').value = object.kommentar,
                    $('aksunders').value = aksunders
				
                });
            this.currentForm.getContactObject2(
                function(transport) {
                    var object = transport.responseText.evalJSON();
                    $('knavn2').value = object.navn,
                    $('email2').value = object.epost,
                    $('adr2').value = object.adresse,
                    $('tlf2').value = object.telefon,
                    $('postnr2').value = object.postnr,
                    $('sted2').value = object.sted
                    if($('knavn2').value != '') {
                        $('contact2').setStyle({
                            display:'block'
                        });
                        self.contact2isActive = true;
                    }
                }
            );
        }
    },
	
    preLoadEvents: function() {
        var self = this;
        $$('#personType .type').each(function(element) {
            $(element).observe('click', function() {
                if($$('#personType .active').length > 0) {
                    $$('#personType .active')[0].removeClassName('active');
                }
                $(this).addClassName('active')
                $('titleHeader').innerHTML = this.id;
            });
        });
        $$('#betalingType .type').each(function(element) {
            $(element).observe('click', function() {
                self.currentForm.confirmForm(
                    function(transport) {
                        $('regFormFarskap').innerHTML = transport.responseText;
                    }, 
                    $(element).id
                );
            });
        });
        ['ansvarTrue', 'ansvarFalse'].each(function(aElem) {
            if($(aElem)) {
                $(aElem).observe('click', function() {
                    self.ansvarElem = this.value;
                });
            }
        });
        if($('nextStep2')) {
            $('nextStep2').observe('click', function() {
                if(self.registeredPersons > 0) {
                    window.location = $(this).href
                }
                else {
                    if($('langCode').value == 'EN') 
                        alert('You must register participants first!'); 
                    else 
                        alert('Du må registrere personer først!');
                }
            });
        }
        if($('showContact2')) {
            $('showContact2').observe('click', function() {
                if(self.contact2isActive == true) {
                    self.contact2isActive = false;
                    $('contact2').setStyle({
                        display: 'none'
                    });
                }
                else {
                    self.contact2isActive = true;
                    $('contact2').setStyle({
                        display: 'block'
                    });
                }
            });
        }
		
        if($('btnAddPerson')) {
            $('btnAddPerson').observe('click', function() {
                if(!$$('#personType .active')[0]) {
                    if($('langCode').value == 'NO') alert('Type person er ikke valgt!'); else alert('You must select right type');
                    return false;
                }
                if($('fornavn').value == '') {
                    if($('langCode').value == 'EN') alert('You need to fill in firstname'); else alert('Du må fylle inn fornavn');
                    return false;
                }
                if($('etternavn').value == '') {
                    if($('langCode').value == 'EN') alert('You need to fill in surename'); else alert('Du må fylle inn etternavn');
                    return false;
                }
                if($('born1').value == '') {
                    if($('langCode').value == 'EN') alert('You need to fill in birthdate'); else alert('Du må fylle inn fødselsdato');
                    return false;
                }
                if($$('#personType .active')[0].id == 'Mor' || $$('#personType .active')[0].id == 'Mann') {
                    if($('ansvarTrue').checked == false && $('ansvarFalse').checked == false) {
                        if($('langCode').value == 'EN') alert('You need to select responsebility or not'); else alert('Du må velge foreldreansvar');
                        return false;
                    }
                }
				
                if(self.validateBirth($('born1').value))  {
                    if($('born2').value == '') {				
                        self.currentForm.addPerson({
                            tittel:	$$('#personType .active')[0].id,
                            fornavn: $('fornavn').value,
                            etternavn: $('etternavn').value,
                            born1: $('born1').value,
                            born2: $('born2').value,
                            ansvar: self.ansvarElem 
                        },
                        function(transport) {
                            self.resetForms();
                            self.updateList();
                            self.registeredPersons++;
                        });
                    } 
                    else {
                        if($('born2').value.length < 4 || $('born2').value.length > 5) {
                            if($('langCode').value == 'NO') 
                                alert('Personnummeret er feil skrevet.'); 
                            else 
                                alert('Your social securitynumber is wrong.'); 
							
                            return false;
                        }
                        else {
                            if(self.isInteger($('born2').value)) {
                                self.currentForm.addPerson({
                                    tittel:	$$('#personType .active')[0].id,
                                    fornavn: $('fornavn').value,
                                    etternavn: $('etternavn').value,
                                    born1: $('born1').value,
                                    born2: $('born2').value,
                                    ansvar: self.ansvarElem 
                                },
                                function(transport) {
                                    self.resetForms();
                                    self.updateList();
                                    self.registeredPersons++;
                                });
                            }
                            else {
                                if($('langCode').value == 'NO') 
                                    alert('Personnummeret kan bare bestå av tall.'); 
                                else 
                                    alert('Your social securitynumber can only contain numbers.'); 
								
                                return false;
                            }								
                        }
                    }
                }
            });
        }
		
        if($('btnSaveContact')) {
            $('btnSaveContact').observe('click', function(event) {
                Event.stop(event);
                if(self.validateContact()) {
                    if (self.validateContact2()) {
                        if ($('knavn2').value != '') {
                            self.currentForm.addContant2({
                                navn: $('knavn2').value,
                                epost: $('email2').value,
                                adresse: $('adr2').value,
                                telefon: $('tlf2').value,
                                postnr: $('postnr2').value,
                                sted: $('sted2').value
                            }, function(transport) {
                                if ($('knavn2').value != '') {
                                    $('contact2').setStyle({
                                        display: 'block'
                                    });
                                }
                            });
                        }
                        else {
                            self.currentForm.removeContact2();
                        }
						
                        self.currentForm.addContant({
                            navn: $('knavn').value,
                            epost: $('email').value,
                            adresse: $('adr').value,
                            telefon: $('tlf').value,
                            postnr: $('postnr').value,
                            sted: $('sted').value,
                            kommentar: $('kommentar').value,
                            aksunders: $('aksunders').value
                        }, function(transport) {
                            window.location = $('btnSaveContact').href;
                        });
                    }
                }
            });
        }
    },
	
    validateContact: function()
    {
        var self = this;
        if($('knavn').value != '')
        {
            if(self.checkEmail($('email').value) == true)
            {
                if($('adr').value != '')
                {
                    if($('tlf').value != '')
                    {
                        if($('tlf').value.length == 8)
                        {
                            if(self.isInteger($('tlf').value))
                            {
                                if($('postnr').value.length == 4)
                                {
                                    if($('postnr').value != '')
                                    {
                                        if(self.isInteger($('postnr').value))
                                        {
                                            if($('sted').value != '')
                                            {
                                                if($('problemmatter'))
                                                {
                                                    if($('kommentar').value == '')
                                                    {
                                                        if($('langCode').value == 'EN') alert('You must write what the problem is'); else alert('Du må skrive inn problemstillingen!');
                                                        return false;
                                                    }
                                                }
                                                return true;
                                            }
                                            else
                                            {
                                                if($('langCode').value == 'EN') alert('You must write city!'); else alert('Du må skrive inn sted!');
                                                return false;
                                            }
                                        }
                                        else
                                        {
                                            if($('langCode').value == 'EN') alert('You must fill inn a valid zip!'); else alert('Du må skrive inn gyldig postnummer!');
                                            return false;
                                        }
                                    }
                                    else
                                    {
                                        if($('langCode').value == 'EN') alert('You must fill in a zip!'); else alert('Du må skrive inn postnr!');
                                        return false;
                                    }
                                }
                                else
                                {
                                    if($('langCode').value == 'EN') alert('The length of your zip is wrong'); else alert('Lengden på postnummeret er feil');
                                    return false;
                                }
                            }
                            else
                            {
                                if($('langCode').value == 'EN') alert('You must fill in a valid phonenumber!'); else alert('Du må skrive inn et gyldig telefonnummer!');
                                return false;
                            }
                        }
                        else
                        {
                            if($('langCode').value == 'EN') alert('The length of your phonenumber is wrong'); else alert('Lengden på telefonnummeret er feil');
                            return false;
                        }
                    }
                    else
                    {
                        if($('langCode').value == 'EN') alert('You must fill in a phonenumber!'); else alert('Du må skrive inn telefonnummer!');
                        return false;
                    }
                }
                else
                {
                    if($('langCode').value == 'EN') alert('You must fill in an address!'); else alert('Du må skrive inn adresse!');
                    return false;
                }
            }
            else
            {
                if($('langCode').value == 'EN') alert('You must fill in an email address'); else alert('Du må skrive inn epostadresse!');
                return false;
            }
        }
        else
        {
            if($('langCode').value == 'EN') alert('You must fill in a name!'); else alert('Du må skrive inn navn!');
            return false;
        }
    },
	
    validateContact2: function() {
        var self = this;
        if ($('email2').value != '') {
            if (self.checkEmail($('email2').value) != true) {
                if ($('langCode').value == 'EN') 
                    alert('You must fill in an email address');
                else 
                    alert('Du må skrive inn epostadresse!');
                return false;
            }
				
        }
        if ($('tlf2').value != '') {
            if ($('tlf2').value.length != 8) {
                if ($('langCode').value == 'EN') 
                    alert('The length of your phonenumber is wrong');
                else 
                    alert('Lengden på telefonnummeret er feil');
                return false;
            }
            if (!self.isInteger($('tlf2').value)) {
                if ($('langCode').value == 'EN') 
                    alert('You must fill in a valid phonenumber!');
                else 
                    alert('Du må skrive inn et gyldig telefonnummer!');
                return false;
            }
        }
        if ($('postnr2').value != '') {
            if ($('postnr2').value.length != 4) {
                if ($('langCode').value == 'EN') 
                    alert('The length of your zip is wrong');
                else 
                    alert('Lengden på postnummeret er feil');
                return false;
            }
            if (!self.isInteger($('postnr2').value))  {
                if ($('langCode').value == 'EN') 
                    alert('You must fill inn a valid zip!');
                else 
                    alert('Du må skrive inn gyldig postnummer!');
                return false;
            }
        }
		
        return true;
    /*
		if($('knavn2').value != '' || $('email2').value != '' || $('adr2').value != '')
		{
			if ($('knavn2').value != '') {
				if (self.checkEmail($('email2').value) == true) {
					if ($('adr2').value != '') {
						if ($('tlf2').value != '') {
							if ($('tlf2').value.length == 8) {
								if (self.isInteger($('tlf2').value)) {
									if ($('postnr2').value.length == 4) {
										if ($('postnr2').value != '') {
											if (self.isInteger($('postnr2').value)) {
												if ($('sted2').value != '') {
													return true;
												}
												else {
													if ($('langCode').value == 'EN') 
														alert('You must write city!');
													else 
														alert('Du må skrive inn sted!');
													return false;
												}
											}
											else {
												if ($('langCode').value == 'EN') 
													alert('You must fill inn a valid zip!');
												else 
													alert('Du må skrive inn gyldig postnummer!');
												return false;
											}
										}
										else {
											if ($('langCode').value == 'EN') 
												alert('You must fill in a zip!');
											else 
												alert('Du må skrive inn postnr!');
											return false;
										}
									}
									else {
										if ($('langCode').value == 'EN') 
											alert('The length of your zip is wrong');
										else 
											alert('Lengden på postnummeret er feil');
										return false;
									}
								}
								else {
									
								}
							}
							else {
								
							}
						}
						else {
							if ($('langCode').value == 'EN') 
								alert('You must fill in a phonenumber!');
							else 
								alert('Du må skrive inn telefonnummer!');
							return false;
						}
					}
					else {
						if ($('langCode').value == 'EN') 
							alert('You must fill in an address!');
						else 
							alert('Du må skrive inn adresse!');
						return false;
					}
				}
				else {
					if ($('langCode').value == 'EN') 
						alert('You must fill in an email address');
					else 
						alert('Du må skrive inn epostadresse!');
					return false;
				}
			}
			else {
				if ($('langCode').value == 'EN') 
					alert('You must fill in a name!');
				else 
					alert('Du må skrive inn navn!');
				return false;
			}
		}
		else
			return true;*/
    },
	
    validateBirth: function(birthval) {

        var datePat = /^(\d{1,2})(\/|-|.)(\d{1,2})\2(\d{4})$/;
        var matchArray = birthval.match(datePat);
        if (matchArray == null) {
            if($('langCode').value == 'EN') alert('The date is wrong formatted'); else alert('Datoen er feil formatert');
            return false;
        }
        var month = matchArray[3];
        var day = matchArray[1];
        var year = matchArray[4];
        var authDate = birthval.split('.');
        if (authDate[1] == undefined) {
            if($('langCode').value == 'EN') alert('The date is wrong formatted'); else alert('Datoen er feil formatert');
            return false;
        }
        if (month < 1 || month > 12) {
            if($('langCode').value == 'EN') alert('Month must be between 01 and 12'); else alert('Måned må være mellom 01 og 12.');
            return false;
        }
        if (day < 1 || day > 31) {
            alert('Day must be between 1 and 31.');
            return false;
        }
        if ((month==4 || month==6 || month==9 || month==11) && day==31) {
            if($('langCode').value == 'EN') alert('Month '+month+' don\'t have 31 days!'); else alert('Måned '+month+' har ikke 31 dager!');
            return false
        }
        if ($('born1').value.length < 9) {
            if($('langCode').value == 'EN') alert('The length of the birthdate is wrong, try to correct it'); else alert('Lengden på fødselsdatoen stemmer ikke, prøv igjen.');
            return false;
        }
        if (month == 2) {
            var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
            if (day>29 || (day==29 && !isleap)) {
                if($('langCode').value == 'EN') alert('February ' + year + ' don\'t have ' + day + ' days!'); else alert('Februar ' + year + ' har ikke ' + day + ' dager!');
                return false;
            }
        }
        return true;
    },
	
    updateList: function() {
        var self = this;
        this.currentForm.getPersonList('',
            function(transport) {
                $('regPersons').innerHTML = '';
                $('regPersons').insert(transport.responseText);
                self.addQuickEvent();
            });
        if($('regPersNum')) {
            this.registeredPersons = eval($('regPersNum').value);
        }
    //	console.log(this.registeredPersons);
    },
	
    addQuickEvent: function() {
        var self = this;
        var delArr = $$('.delPersonBtn');
        var editArr = $$('.editPersonBtn');
        delArr.each(function(elems) {
            Event.observe(elems, 'click', function() {
                var parentElem = $($(this.parentNode.id).parentNode.id);
                parentElem.remove();
                self.currentForm.removePerson($(this.parentNode).id.replace('rowIndex', ''),
                    function() {
                        $($(Deelem).parentNode.id).parentNode.remove();
                        alert('removed');
                    });
                self.registeredPersons--;
            });
        });
        editArr.each(function(edElem) {
            Event.observe(edElem, 'click', function() {
                var currentPerson = self.currentForm.getPersonObject(
                    eval(edElem.id.replace('editIndex','')),
                    function(transport) {
                        var personObject = transport.responseText.evalJSON();
                        $(personObject.tittel).addClassName('active');
                        $('fornavn').value = personObject.fornavn;
                        $('etternavn').value = personObject.etternavn; 
                        $('born1').value = personObject.born1;
                        $('born2').value = personObject.born2;
                        if($('ansvarFalse')) {
                            if(personObject.ansvar == 'false') {
                                $('ansvarFalse').checked = true;
                            }
                            else if(personObject.ansvar == 'true') {
                                $('ansvarTrue').checked = true;
                            }
                            else {}
                        }
                        self.currentForm.removePerson(eval(edElem.id.replace('editIndex','')),function(){});
                        var parentElem = $($(edElem.parentNode).parentNode.id);
                        parentElem.remove();
                    }
                );
            });
        });
    },
	
    resetForms: function() {
        $('orderForm').reset();
        $$('#personType .active')[0].removeClassName('active');
        $('titleHeader').innerHTML = 'RELASJON';
    },
	
    isInteger: function(s) {
        var i;
        var self = this;
        if (self.isEmpty(s))
            if (isInteger.arguments.length == 1) return 0;
            else return (isInteger.arguments[1] == true);
        for (i = 0; i < s.length; i++) {
            var c = s.charAt(i);
            if (!self.isDigit(c)) return false;
        }
        return true;
    },
	
    isEmpty: function(s) {
        return ((s == null) || (s.length == 0))
    },

    isDigit: function(c) {
        return ((c >= "0") && (c <= "9"))
    },
   
    checkEmail: function(value) {
        var apos = value.indexOf("@");
        var dotpos = value.lastIndexOf(".");
        if(value == '' || apos < 1 || dotpos-apos < 2) {
            return false;
        }
        return true;
    }
});

Event.observe(window, 'load', function() {
    if($('currentExtId')) {
        var FarskapSkjema = new FarskapReg($('currentExtId').value);
    }
});

