<!-- RCSid: $Header: /opt1/utm/dump101119/src/app/ebrevweb/war/src/main/webapp/js/ebrevwebb.js,v 1.1.4.3.4.17.2.2.60.10 2010-02-17 09:09:46 laed010 Exp $ -->

/*	#####################################################################################
 Funktion för att hantera sökning via organisationsnummer
Inparametrar:	theForm
##################################################################################### */
function SearchByOrgNo (theForm) {

    var va = new Validator();
    var er = new ErrorRenderer();
    var fm = new Formatter();

    copyParameters(theForm);
    fm.trimAllFields(theForm);

    if (va.isEmpty(theForm.orgno)) {
        va.addError(new Error(theForm.orgno,'Här ska du ange ett organisationsnummer'));
    } else if (!va.checkOrgno(theForm.orgno.value)) {
        va.addError(new Error(theForm.orgno,'Kontrollera organisationsnumret'));
    }
    return er.displayErrors(theForm,va.getErrors());
}


/*	#####################################################################################
 Funktion för att hantera sökning via företagsnamn
Inparametrar:	theForm
##################################################################################### */
function SearchCompanyName (theForm) {

    var va = new Validator();
    var er = new ErrorRenderer();
    var fm = new Formatter();

    copyParameters(theForm);
    fm.trimAllFields(theForm);

    if (va.isEmpty(theForm.companyname)) {
        va.addError(new Error(theForm.companyname,'Här ska du fylla i företagsnamn'));
    }
    return er.displayErrors(theForm,va.getErrors());
}

   /* #####################################################################################
  Funktion för att kopiera över ifyllda parametrear från ett formulär till ett annat
  Inparametrar:	theForm
##################################################################################### */
function copyParameters(theForm) {
    var CompanyInformationForm  = new getForm("CompanyInformationFormId");
    theForm.firstname.value      = CompanyInformationForm.firstname.value;
    theForm.lastname.value       = CompanyInformationForm.lastname.value;
    theForm.title.value          = CompanyInformationForm.title.value;
    theForm.department.value     = CompanyInformationForm.department.value;
    theForm.postalcode.value     = CompanyInformationForm.postalcode.value;
    theForm.city.value           = CompanyInformationForm.city.value;
    theForm.email.value          = CompanyInformationForm.email.value;
    theForm.phone.value          = CompanyInformationForm.phone.value;
    theForm.firmatecknare.value  = CompanyInformationForm.firmatecknare.value;
    theForm.firmatecknareEmail.value  = CompanyInformationForm.firmatecknareEmail.value;

    if (CompanyInformationForm.ebrevwebservices.checked) {
        theForm.ebrevwebservices.value  = CompanyInformationForm.ebrevwebservices.value;
    }
}


/*	#####################################################################################
  Funktion för att hantera registrering av uppgifter
 Inparametrar:	theForm
 ##################################################################################### */
function RegisterCompanyInformation (theForm) {

    var va = new Validator();
    var er = new ErrorRenderer();
    var fm = new Formatter();

    fm.trimAllFields(theForm);

    if (va.isEmpty(theForm.firstname)) {
        va.addError(new Error(theForm.firstname,'Här måste du fylla i ditt förnamn'));
    }
    if (va.isEmpty(theForm.lastname)) {
        va.addError(new Error(theForm.lastname,'Här måste du fylla i ditt efternamn'));
    }
    if (va.isEmpty(theForm.title)) {
        va.addError(new Error(theForm.title,'Här måste du fylla i din titel'));
    }
    if (va.isEmpty(theForm.email)) {
        va.addError(new Error(theForm.email,'Här måste du fylla i din e-postadress'));
    } else if (!va.checkEmail(theForm.email.value)) {
        va.addError(new Error(theForm.email,'Kontrollera e-postadressen'));
    }
    if (va.isEmpty(theForm.phone)) {
        va.addError( new Error(theForm.phone,'Här måste du fylla i ditt telefonnummer'));
    } else if (!va.checkPhone(theForm.phone.value)){
        va.addError(new Error(theForm.phone,'Kontrollera telefonnumret'));
    }
    if (va.isEmpty(theForm.firmatecknare)) {
        va.addError(new Error(theForm.firmatecknare,'Här måste du fylla i minst firmatecknare'));
    }
    if (va.isEmpty(theForm.firmatecknareEmail)) {
        va.addError(new Error(theForm.firmatecknareEmail,'Här måste du fylla i din e-postadress'));
    } else if (!va.checkEmail(theForm.firmatecknareEmail.value)) {
        va.addError(new Error(theForm.firmatecknareEmail,'Kontrollera e-postadressen'));
    }
    return er.displayErrors(theForm,va.getErrors());
}

/*	#####################################################################################
 Funktion för att rensa formuläret med företagsuppgifter
Inparametrar:   theForm
##################################################################################### */
function clearCompany(theForm) {
    theForm.companyname.value    = '';
    theForm.orgno.value          = '';
    theForm.firstname.value      = '';
    theForm.lastname.value       = '';
    theForm.title.value          = '';
    theForm.department.value     = '';
    theForm.postalcode.value     = '';
    theForm.city.value           = '';
    theForm.email.value          = '';
    theForm.phone.value          = '';
    theForm.firmatecknare.value  = '';
    theForm.firmatecknareEmail.value  = '';
}

/*	#####################################################################################
 Funktion för att hantera val av profil
Inparametrar:	theForm
##################################################################################### */
function ChooseProfile (theForm) {

    var va = new Validator();
    var er = new ErrorRenderer();

    if (!va.isRadioSelected(theForm.profileID)) {
        va.addError(new Error(theForm.profileID,'Här ska du välja profil'));
    }
    return er.displayErrors(theForm,va.getErrors());
}

/*	#####################################################################################
 Funktion för validering av 'Gör beställning'
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function validatePlaceOrder (theForm) {

    var va = new Validator();
    var er = new ErrorRenderer();
    var fm = new Formatter();

    fm.trimAllFields(theForm);

    var letterfilerexexp = /(\.doc)|(\.pdf)$/;      //  Regexp-mask för brevfiltyp
    var addressfilerexexp = /(\.txt)|(\.xls)|(\.xlsx)$/;     //  Regexp-mask för adressfiltyp

    if (va.isEmpty(theForm.letterfile)) {
        va.addError(new Error(theForm.letterfile,'Här ska du Hämta brevet från din dator'));
     } else if (!letterfilerexexp.test(theForm.letterfile.value)) {
        va.addError(new Error(theForm.letterfile,'Brevdokumentet måste vara sparat som *.doc eller *.pdf för att kunna hanteras'));
    }
    if (!va.isRadioSelected(theForm.howtoaddrecipient)) {
        va.addError(new Error(theForm.howtoaddrecipient,'Här måste du välja ett alternativ'));
    } else if (theForm.howtoaddrecipient[1].checked && !theForm.addressfile.value) {
        va.addError(new Error(theForm.addressfile,'Hämta adressfilen från din dator'));
    } else if (theForm.howtoaddrecipient[1].checked && !addressfilerexexp.test(theForm.addressfile.value.toLowerCase())) {
        va.addError(new Error(theForm.addressfile,'Adressfilen måste vara sparad som *.txt, *.xls eller *.xlsx för att kunna hanteras'));
    }

    if (va.isEmpty(theForm.senderCompanyName)) {
        va.addError(new Error(theForm.senderCompanyName,'Här ska du fylla i avsändarens företagsnamn'));
    } else if (theForm.senderCompanyName.value.length > 41){
        va.addError(new Error(theForm.senderCompanyName,'Företagsnamnet får max vara 41 tecken långt'));
    }
    if (va.isEmpty(theForm.senderZipcode)) {
        va.addError(new Error(theForm.senderZipcode,'Här ska du fylla i avsändarens postnummer'));
    } else if (!va.checkZipcode(theForm.senderZipcode.value)) {
        va.addError(new Error(theForm.senderZipcode,'Ange postnumret med fem siffror'));
    }
    if (va.isEmpty(theForm.senderCity)) {
        va.addError(new Error(theForm.senderCity,'Här ska du fylla i avsändarens postort'));
    } else if (theForm.senderCity.value.length > 41) {
        va.addError(new Error(theForm.senderCity,'Postorten får max vara 41 tecken långt'));
    }
    if (va.isEmpty(theForm.serviceId)) {
        va.addError(new Error(theForm.serviceId,'Här ska du välja när brevet ska delas ut och/eller det tryck du önskar'));
    }

    if (va.isEmpty(theForm.userEmail)) {
        va.addError(new Error(theForm.userEmail,'Här måste du fylla i din e-postadress'));
    } else if (!va.checkEmail(theForm.userEmail.value)) {
        va.addError(new Error(theForm.userEmail,'Kontrollera e-postadressen'));
    }

/*    if (va.isEmpty(theForm.userMobil)) {
        va.addError(new Error(theForm.userMobil,'Här måste du fylla i ditt mobilnummer'));
    } else if (theForm.userMobil.value.length > 15) {
        va.addError(new Error(theForm.userMobil,'Mobilnummret får max vara 15 tecken långt'));
    }
*/

    if (!va.isCheckBoxSelected(theForm.contactcheck)){
        va.addError(new Error(theForm.contactcheck,'Du måste godkänna dina kontaktuppgifter.'));
    }


    return er.displayErrors(theForm,va.getErrors());
}

/*	#####################################################################################
 Funktion för att att skicka formuläret för 'Gör beställning'
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function placeOrder(theForm) {
   if (validatePlaceOrder(theForm)) {
        theForm.letterfilename.value = theForm.letterfile.value;
        theForm.addressfilename.value = theForm.addressfile.value;
        if (theForm.serviceId.options[theForm.serviceId.selectedIndex].index != 0) {
            theForm.servicename.value = theForm.serviceId.options[theForm.serviceId.selectedIndex].text;
        } else {
            theForm.servicename.value = '';
        }
        //Submit the form.
        submitFormAndShowProgress(theForm);
        //return true;
    }
    //return false;
}

/*	#####################################################################################
 Funktion för att att skicka formuläret för 'Gör beställning'
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function comfirmbankgiro(theForm) {
    //Submit the form.
    submitFormAndShowProgress(theForm);    
}

/*	#####################################################################################
 Funktion för att hantering av 'Mottagaradresser' vid 'Gör beställning'
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function handlePlaceOrderReciptient (theForm) {
    if (theForm.howtoaddrecipient[0].checked) {
        document.getElementById("addressfiletd").innerHTML = '<input class="xl" type="file" name="addressfile" id="addressfileId" title="Välj fil"/>';
        theForm.addressfile.disabled = true
    } else {
        theForm.addressfile.disabled = false
    }
}

/*	#####################################################################################
 Funktion för att hantering av 'Brevet' vid 'Gör beställning'
Inparametrar:	theForm	- Formuläret
                theField - Checkboxen
##################################################################################### */
function handlePlaceOrderLetter (theForm,theField) {

    theForm.flyleaf.value = "false";
    theForm.girocard.value = "false";

    if (theField.checked) {
        theForm.girocardcheck.checked = false;
        theForm.girocardcheck.disabled = true;
        theForm.flyleafcheck.checked = false;
        theForm.flyleafcheck.disabled = true;

        theField.checked = true;
        theField.disabled = false;

        if (theForm.girocardcheck.checked) {
           theForm.girocard.value = "true";
        }
        if (theForm.flyleafcheck.checked) {
           theForm.flyleaf.value = "true";
        }
    } else {
        theForm.flyleafcheck.disabled = false;
        theForm.girocardcheck.disabled = false;
    }
}

/*	#####################################################################################
 Funktion för att hantering av 'adressfil' vid 'Gör beställning'
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function handlePlaceOrderAddressFile (theForm) {
    if (theForm.addressfile.value) {
        theForm.howtoaddrecipient[1].checked = true;
    }
}


/*	#####################################################################################
 Funktion för att initiera validering och göra submit vid 'Gör beställning'.
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function confirmAndSubmitOrder(theForm) {
    if (validateOrder(theForm)) {
        //Submit the form.
        submitFormAndShowProgress(theForm);
    }
}
/*	#####################################################################################
 Funktion för validering av bekräfta order vid 'Gör beställning'
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function validateOrder(theForm){
    var va = new Validator();
    var er = new ErrorRenderer();
    var fm = new Formatter();

    fm.trimAllFields(theForm);

    if (va.isEmpty(theForm.previewed)) {
        va.addError(new Error(document.getElementById("docpreviewed"),'Du måste förhandsgranska brevet för att kunna skicka in beställningen'));
    }
    if (!va.isCheckBoxSelected(theForm.conditionsaccepted)){
        va.addError(new Error(theForm.conditionsaccepted,'Du måste sätta ett kryss i rutan för att kunna skicka in beställningen'));
    }
    return er.displayErrors(theForm,va.getErrors());
}


/*	#####################################################################################
 Funktion för hantering av förhandsgranskning av brevet
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function preview (theForm) {
    theForm.previewed.value = 'yes';
    // skapa dummyparameter för att få en unik URL och tvinga klient att hämta sida på nytt
    // parametern x används inte i applikationen
    var time = new Date().getTime();
    openWin(pseWin.SCROLLRESIZE, '/ebrevwebb/bin/eBrevPreviewServlet?x=' + time, 600, 600, 'Förhandsgranskning');
}

/*	#####################################################################################
 Funktion för validering av mottagaradress
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function validateRecipient (theForm) {
    var va = new Validator();
    var er = new ErrorRenderer();
    var fm = new Formatter();

    fm.trimAllFields(theForm);

    if (va.isEmpty(theForm.recipientName)) {
        va.addError(new Error(theForm.recipientName,'Här ska du fylla i namn'));
    }

    va.isListSelected(theForm.recipientCountry_0);

    countryCode = va.listValue;

    if (countryCode == "SE" && va.isEmpty(theForm.recipientZipcode)) {
        va.addError(new Error(theForm.recipientZipcode,'Här ska du fylla i postnummer'));
    } else if (countryCode == "SE" && !va.checkZipcode(theForm.recipientZipcode.value)) {
        va.addError(new Error(theForm.recipientZipcode,'Kontrollera postnumret'));
    }

    if (va.isEmpty(theForm.recipientCity)) {
        va.addError(new Error(theForm.recipientCity,'Här ska du fylla i postort'));
    }

    return er.displayErrors(theForm,va.getErrors());
}

/*	#####################################################################################
 Funktion för kontrollera att några mottagaradresser har lagts till manuellt
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function recipientsNext (theForm) {
    if(validateRecipientsNext(theForm)){
        //Submit the form.
        theForm.recipientName_0.value = '';
        theForm.address2_0.value = '';
        theForm.address3_0.value = '';
        theForm.address4_0.value = '';
        theForm.recipientZipcode_0.value = '';
        theForm.recipientCity_0.value = '';
        theForm.recipientCountry_0.options[theForm.recipientCountry_0.selectedIndex] == '0';

        submitFormAndShowProgress(theForm);
    }
}

function validateRecipientsNext(theForm){
    var va = new Validator();
    var er = new ErrorRenderer();
    if (theForm.numrecipients.value == 0) {
        va.addError(new Error(theForm.recipientName_0,'Mottagaradress - Inga adresser har lagts till ännu. Om du ångrat dig, klicka på "Tillbaka"'));
    }
    return er.displayErrors(theForm,va.getErrors());
}

/*	#####################################################################################
 Funktion för validering av girokortsinformation
Inparametrar:	theForm	- Formuläret
##################################################################################### */
function validateGiroCard (theForm) {
    var va = new Validator();
    var er = new ErrorRenderer();
    var fm = new Formatter();

    fm.trimAllFields(theForm);

    if (!va.isRadioSelected(theForm.girotype)) {
        va.addError(new Error(theForm.girotype,'Välj vilken typ av inbetalningskort du vill använda: PlusGiro eller Bankgiro.'));
    }

    if (va.isEmpty(theForm.gironumber)) {
        va.addError(new Error(theForm.gironumber,'Gironummer saknas i informationen du vill lämna på inbetalningskortet.'));
    }

    if (va.isEmpty(theForm.paymentreciever)) {
        va.addError(new Error(theForm.paymentreciever,'Betalningsmottagare saknas i informationen du vill lämna på inbetalningskortet.'));
    } else if (theForm.paymentreciever.value.length > 41) {
        va.addError(new Error(theForm.paymentreciever,'Betalningsmottagare innehåller fler än 41 tecken som är max för att kunna hanteras.'))
    }

    if (!va.isEmpty(theForm.giroamount)) {
        if (va.isOnlyDigits(theForm.giroamount.value)) {
            theForm.giroamount.value += ",00";
        }
        if (!va.checkAmount(theForm.giroamount.value)) {
            va.addError(new Error(theForm.giroamount,'Beloppet måste skrivas med kronor och ören, separerade med kommatecken, för att kunna hanteras.'));
        }
    }

    if (theForm.girotext1.value.length > 30) {
        va.addError(new Error(theForm.girotext1,'Referenstexten innehåller fler än 30 tecken per rad som är max för att kunna hanteras.'));
    }

    if (theForm.girotext2.value.length > 30) {
        va.addError(new Error(theForm.girotext2,'Referenstexten innehåller fler än 30 tecken per rad som är max för att kunna hanteras.'));
    }

    if (theForm.girotext3.value.length > 30) {
        va.addError(new Error(theForm.girotext3,'Referenstexten innehåller fler än 30 tecken per rad som är max för att kunna hanteras.'));
    }

    if (theForm.girotext4.value.length > 30) {
        va.addError(new Error(theForm.girotext4,'Referenstexten innehåller fler än 30 tecken per rad som är max för att kunna hanteras.'));
    }

    if (theForm.girotext5.value.length > 30) {
        va.addError(new Error(theForm.girotext5,'Referenstexten innehåller fler än 30 tecken per rad som är max för att kunna hanteras.'));
    }

    if (theForm.girotext6.value.length > 30) {
        va.addError(new Error(theForm.girotext6,'Referenstexten innehåller fler än 30 tecken per rad som är max för att kunna hanteras.'));
    }

    return er.displayErrors(theForm,va.getErrors());
}


/* Logon */
function logon (theForm, userField, pwdField) {

   if (eval("theForm." + userField + ".value") && eval("theForm." + pwdField + ".value")) {
        return true;
   }
   return false;
}

/* Öppna URL i "main"window, funktionen kopierad från window2.js som inte verkar tas med 060930 */
function showInMainWinWithFocus(theUrl){
    var objWO = window.opener;
    if ((!objWO) || (objWO == null) || (objWO.closed)){
        window.open(theUrl);
    }else{
        objWO.location.href=theUrl;
        objWO.focus();
    }

}

function showInMainWin(theUrl){
    if (window.opener){
        if(window.opener.closed){
            window.open(theUrl);
        }else{
            window.opener.location.href=theUrl;
        }
    }else{
        window.open(theUrl);
    }
}

function getForm(theForm){
    return document.getElementById(theForm);
}


//Submit form, show progressinfo, no multiple submits.
var submitCounter = 0;
function submitFormAndShowProgress(objForm){
    //Prevent multiple submits.
    submitCounter++;
    //Prevent multiple submits
    if(submitCounter == 1){
        //Try to show progress info
        try{
            showSaveInProgress();
        }catch(e){
            //Do nothing. Continue to submit even if progressinfo fails to show.
        }
        //Send form
        objForm.submit();
    }

}


//##################################
//Functions for showing progress information when saving complaint - start
//##################################
//-------------------------------------------------
// Name: showSaveInProgress
// Purpose:  Present a message (centered in broserwin) with info that the complaint is being saved. The message is animated for more positive user experience.
// Return value: none
//-------------------------------------------------
function showSaveInProgress(){
var elemSaveInProgress = document.getElementById("infoSaveInProgress");
if(elemSaveInProgress != null){
    //Position progressinfo (find out documents inner width and height first, and scrollvalues)
    var docInnerWidth = getDocInnerWidth();
    var docInnerHeight = getDocInnerHeight();
    var docScrollTop = getDocScrollTop();
    var docScrollLeft = getDocScrollLeft();
    //Show progressinfo
    if(docInnerWidth != null && docInnerHeight != null){
        //Find out the progressinfo-element's actual width and height.
        var elemWidth = getElemWidth(elemSaveInProgress);
        var elemHeight = getElemHeight(elemSaveInProgress);
        //Calculate where progressinfo-element should be positioned.
        var posX = parseInt(((docInnerWidth/2) + docScrollLeft) - (elemWidth/2));
        var posY = parseInt(((docInnerHeight/2) + docScrollTop) - (elemHeight/2));
        //alert("posX:" + posX);
        //alert("posY:" + posY);
        //Position the element
        posElem(elemSaveInProgress, posX, posY);
    }
    elemSaveInProgress.style.visibility = "visible";
    var objAnimationInterval = setInterval("animateSaveInProgress()",1000);
}
}

//-------------------------------------------------
// Name: animateSaveInProgress
// Purpose:  Animate message to user to simulate a loadingbar.
// Return value: none
//-------------------------------------------------
var objAnimationInterval;
var animateString = "";
var nrOfTimesAnimationDrawn = 0;
function animateSaveInProgress(){
var elemAnimatedSaveInProgress = document.getElementById("containerAnimationSaveInProgress");
if(elemAnimatedSaveInProgress){
    animateString += ". ";
    elemAnimatedSaveInProgress.innerHTML = animateString;
    nrOfTimesAnimationDrawn++;
    //Handle if user has waited too long (>5 mins, probably scripterror)
    if(nrOfTimesAnimationDrawn >300){
        clearInterval(objAnimationInterval);
        elemAnimatedSaveInProgress.innerHTML = "";
        var elemSaveInProgress = document.getElementById("infoSaveInProgress");
        elemSaveInProgress.innerHTML = "Något gick fel när uppgifterna skulle sparas.";
    }
}
}
//##################################
//Functions for showing progress information when saving complaint - start
//##################################


function toggleInfo(id){
var elemLinkMoreInfo = document.getElementById("link_" + id);
var elemLinkMoreInfoText = "";
if (document.getElementById(id).style.display == 'block'){
    document.getElementById(id).style.display='none';
    elemLinkMoreInfoText = "Mer info";
} else {
    document.getElementById(id).style.display='block';
    elemLinkMoreInfoText = "Stäng";
}
elemLinkMoreInfo.innerHTML = elemLinkMoreInfoText;
}

