/* ifDirectory marketplace Signup step1 */

function verifyStep1(self) {
    var msg = ""
    // watch out for the non-breaking spaces in the following strings
    if (! self.membership.value)
        msg += "    - You must choose one membership to apply\n";
    if (msg) {
        alert("There are problems with the values you have provided:\n"
               + msg + "Please fix them, and try again.\n\n");
        return false;
    }
    return true;
}

/* ifDirectory marketplace Signup step2 */

function checkContact(self,isBusiness) {
    var youmust = "    - You must provide your ";
    if(isBusiness){
        youmust += "contact's ";
    }
    var msg = ''
    // watch out for the non-breaking spaces in the following strings
    if (! self.firstName.value) {
        msg += youmust+"first name\n";
    }
    if (! self.lastName.value) {
        msg += youmust+"last name\n";
    }
    if (isBusiness && !self.title.value) {
        msg += youmust+"position in the company\n";
    }
    return msg;
}

function verifyStep2(self) {
    var msg = checkContact(self,1);
    if (msg) {
        alert('There are problems with the values you have provided:\n'
                + msg + 'Please fix them, and try again.\n\n');
        return false;
    }
    return true;
}

/* Check the business description size */
function checkBusinessDescriptionSizeCorrect(self,maxSize){
    return checkSizeCorrect(self.businessDescription,maxSize,"company's description");
}

/* Check the offer description size */
function checkOfferDescriptionSizeCorrect(self,maxSize){
    return checkSizeCorrect(self.offerDescription,maxSize,"company's offer description");
}

function checkSizeCorrect(self,maxSize,attrName){
    if (maxSize==0) return "";
    if ((self.value).length > maxSize){
        return "    - Your "+attrName+" must be at the most "+ maxSize +" characters long\n";
    }
    return "";
}

// REVISAR SI LA USA ALGUIEN
/* ifDirectory edit Adherent check*/
function verifySizes(self,busDescMaxSize,offDescMaxSize){
    var msg = isBusinessDescriptionSizeCorrect(self, busDescMaxSize);
    msg += isOfferDescriptionSizeCorrect(self, offDescMaxSize);
    if(msg){
        alert('There are problems with the values you have provided:\n'
                + msg + 'Please fix them, and try again.\n\n');
        return false;
    }
    return true;
}

/* ifDirectory edit Adherent check*/
function checkEmailAddress(address){
    var msg = ''
    var regEmailNotValid = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
    var regEmailValid = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/; // valid
    if (! (!regEmailNotValid.test(address) && regEmailValid.test(address)))
        msg += "    - You must provide a valid e-mail address\n";

    var anUpperCase = /[A-Z]/;
    if (address.search(anUpperCase) != -1)
        msg += "    - Only lowercase characters are permitted in the email address\n";
    return msg;
}


/* ifDirectory marketplace Signup step3 */

function verifyAdherent(self, dirCountry, geoCountries, busDescMaxSize, offDescMaxSize, editing, isBusiness){
    var fullcheck = false;
    var worldwide = false;
    if (dirCountry == "world"){
        worldwide = true;
        selectedCountry = self.country.value;
        fullcheck = contains(geoCountries,selectedCountry);
    }else{
        fullcheck = contains(geoCountries,dirCountry)
    }
    if (fullcheck){
        return verifyAdherentFull(self,busDescMaxSize,offDescMaxSize,editing,isBusiness,worldwide);
    }else{
        return verifyAdherentBasic(self,busDescMaxSize,offDescMaxSize,editing,isBusiness,worldwide);
    }

}

function checkAdherentCommon(self, busDescMaxSize, offDescMaxSize, editing, isBusiness, ww) {
    var msg = '';
    // watch out for the non-breaking spaces in the following strings
    var youmust = "    - You must provide your ";
    if(isBusiness){
        youmust += "company's ";
        if (!self.name.value)
            msg += youmust+"name\n";
    }
    msg += checkContact(self,isBusiness);

    if(!editing){ // On edit, password won't participate
        if (!(self.password1.value || self.password2.value))
        msg += "    - You must provide a password.\n";
        else {
            if (!(self.password1.value && self.password2.value))
            msg += "    - You must enter your password twice.\n";
            else {
                if (self.password1.value != self.password2.value)
                msg += "    - Passwords don't match.\n";
                else if (self.password1.value.length < 6)
                msg += "    - Passwords must be at least 6 characters long.\n";
            }
        }
    }
    if (! self.username.value)
        msg += "    - You must provide an username\n";
    msg += checkEmailAddress(self.eMail.value);

    if(isBusiness){
        msg += checkBusinessDescriptionSizeCorrect(self, busDescMaxSize);
        msg += checkOfferDescriptionSizeCorrect(self, offDescMaxSize);

        if (! self.isOffering.value)
            msg += "    - You must choose at least one product/service provided\n";
        if (! self.offerDescription.value)
            msg += "    - You must provide your company's product/service description\n";
    }

    if (ww && !self.memberCountry.value)
        msg += youmust+"country\n";


    if (! self.address1.value)
        msg += youmust+"address\n";

    if (! self.city.value)
        msg += youmust+"city\n";

    if (! self.state.value)
        msg += youmust+"state/province\n";

    return msg;
}

function verifyAdherentBasic(self, busDescMaxSize, offDescMaxSize, editing,isBusiness,ww) {
    var msg = checkAdherentCommon(self,busDescMaxSize,offDescMaxSize,editing,isBusiness,ww);
    if (! self.phone.value)
        msg += "    - You must provide your phone number\n";
    if (msg) {
        alert("There are problems with the values you have provided:\n"
                + msg + "Please fix them, and try again.\n\n");
        return false;
    }
    return true;
}

function verifyAdherentFull(self, busDescMaxSize, offDescMaxSize, editing,isBusiness,ww) {
    var msg = checkAdherentCommon(self,busDescMaxSize,offDescMaxSize,editing,isBusiness,ww)

    //var regZipCodeValid = /^\d{5}$/; // valid
    //if (!regZipCodeValid.test(self.zipCode.value))
    if (! self.zipCode.value)
        msg += "    - You must provide your zip code\n";

    var regPhoneValid = /^\d{10}$/; // valid
    if (!regPhoneValid.test(self.phone.value))
        msg += "    - You must provide a ten-digit phone number\n\n";

    //if (self.fax.value && !regPhoneValid.test(self.fax.value))
    //  msg += "    - You must provide a ten-digit fax number\n\n";
    if (msg) {
        alert("There are problems with the values you have provided:\n"
              + msg + "Please fix them, and try again.\n\n");
        return false;
    }
    return true;
}

/* ifDirectory individual adding */

function verifyAddIndividual(self) {
    var msg = ''
    // watch out for the non-breaking spaces in the following strings
    if (! self.username.value)
        msg += "    - You must provide an username\n";

    if (!(self.password1.value || self.password2.value)){
        msg += "    - You must provide a password\n";
    }else {
        if (!(self.password1.value && self.password2.value)){
            msg += "    - You must enter your password twice.\n";
        }else {
            if (self.password1.value != self.password2.value){
                msg += "    - Passwords don't match.\n";
            }else if (self.password1.value.length < 6)
                msg += "    - Passwords must be at least 6 characters long.\n";
        }
    }
    if (! self.address1.value)
        msg += "    - You must provide your address\n";

    if (! self.city.value)
        msg += "    - You must provide your city\n";

    if (! self.state.value)
        msg += "    - You must choose your state/province\n";

    //var regZipCodeValid = /^\d{5}$/; // valid
    //if (!regZipCodeValid.test(self.zipCode.value))
    //  msg += "    - You must provide a five-digit zip code\n";
    if (! self.zipCode.value)
        msg += "    - You must provide your zip code\n";

    //var regPhoneValid = /^\d{10}$/; // valid
    //if (!regPhoneValid.test(self.phone.value))
    //  msg += "    - You must provide a ten-digit phone number\n\n";
    if (! self.phone.value)
        msg += "    - You must provide your phone number\n";

    msg += checkEmailAddress(self.eMail.value);

    if (! self.firstName.value) {
        msg += "    - You must provide first name\n";
    }
    if (! self.lastName.value) {
        msg += "    - You must provide last name\n";
    }
    if (msg) {
        alert('There are problems with the values you have provided:\n'
                + msg + 'Please fix them, and try again.\n\n');
        return false;
    }
    return true;
}

/* Characters counter on the description field */
function updateCounter(textarea, counterId, max){
    var counter = document.getElementById(counterId);
    var value = max - textarea.value.length;
    if (counter){
        counter.innerHTML = value
    }
}

function invertChildsOf(childsId,expandId){
    var childsElement = document.getElementById(childsId);
    var expandElement = document.getElementById(expandId);
    if (childsElement && expandElement){
        if (expandElement.innerHTML.indexOf('[+]') >=0 ){
            expandElement.innerHTML = '[-]';
            expandElement.title = 'Click here to contract sub-industries';
            childsElement.className = 'x';
        }else if (expandElement.innerHTML.indexOf('[-]') >=0 ){
            expandElement.innerHTML = '[+]';
            childsElement.className = 'ocult';
            expandElement.title = 'Click here to expand sub-industries';
        }
    }
    return;
}

/**
 * Next, the functions that act when signing up or editing a business. If the country choosen is 'geocodable',
 * then the 'states' field changes to be a dropdown. Otherwise, it is an input field. 
 * Besides, diferent checks are done in one case or the other, when he form is submitted.
**/

var req;
function loadXMLDoc(url) {
    req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
        try {
            req = new XMLHttpRequest();
        } catch(e) {
            req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {
                req = false;
            }
        }
    }
    if(req) {
        req.onreadystatechange = changeStatesField;
        req.open("GET", url, true);
        req.send("");
    }
}

var inputField = '<input type="text" id="state" name="state" size="25" tal:attributes="value content|nothing"/>';

/** Function that sets the html code that will replace the state input field:
    now it's gonna be the code that the ajax call brought...*/
function changeStatesField() {
    statesField = document.getElementById("stateField");
    /* Next, sets the states field to be an input field... but WARNING, if the template changes, this field might end up being ugly */
    statesField.innerHTML = inputField
    // only if req shows "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200) {
            // ...processing statements go here...
            statesField.innerHTML = req.responseText
        } else {
            alert("There was a problem retrieving the data:\n" + req.status +
                req.statusText);
        }
    }
}

/** If the country choosen is 'geocodable', then a select tag with it's states
    must overwrite the states' input tag 
    This assumes that geocodable countries have states inside.
*/
function onCountryChange(cid, geoCountries){
    wasGeoc = false;
    for (i in geoCountries){
        if (cid==geoCountries[i]){
            wasGeoc = true;
            templateURL = document.URL.substring(0,document.location.href.lastIndexOf('/'))+"/selectStatesInner?cid="+geoCountries[i];
            loadXMLDoc(templateURL);
            break;
        }
    }
    if(!wasGeoc){
        /* The 'states' field must be an input field... but WARNING, if the template changes, this field might end up being ugly */
        statesField = document.getElementById("stateField");
        statesField.innerHTML = inputField;
    }
}

function onMembershipChange(mid,payings,dirCountry,geoCountries,isBusiness,busDescMaxSize,busDescMaxSizePremium,offDescMaxSize,offDescMaxSizePremium){

    if(!isBusiness){
//         Nothing to do with individuals so far
        return;
    }else{
        if(contains(payings,mid)){
            maxBus = busDescMaxSizePremium;
            maxOff = offDescMaxSizePremium;
        }else{
            maxBus = busDescMaxSize;
            maxOff = offDescMaxSize;
        }
        var busDescElem = document.getElementById("businessDescription");
        busDescElem.setAttribute("onkeyup","updateCounter(this,'counterBusDesc',"+maxBus+")");
        updateCounter(busDescElem,"counterBusDesc",maxBus);
        var offDescElem = document.getElementById("offerDescription");
        offDescElem.setAttribute("onkeyup","updateCounter(this,'counterOffDesc',"+maxOff+")");
        updateCounter(offDescElem,"counterOffDesc",maxOff);
        var formElem = document.getElementById("modifyListingInfo");
        newVerifyCall = "javascript:return verifyAdherent(this,'"+dirCountry+"',"+geoCountries.toSource()+","+maxBus+","+maxOff+",1,1)";
        formElem.setAttribute("onsubmit",newVerifyCall);
    }
}


function initEnableDisableInputs(inputs){
    for (i in inputs){
        id = inputs[i];
        cbox = document.getElementById(id+"-autoFill");
        disableEnableInput(cbox,id);
    }
    return;
}

/* Disable input if cbox is marked, enable it otherwise */
function disableEnableInput(cbox, elementId){
    var element = document.getElementById(elementId);
    if (cbox.checked){
        element.disabled = true;
        element.className = 'field-disabled' ;
    }else{
        element.disabled = false;
        element.className = 'field-enabled' ;
    }
    return;
}


function contains(A,elem){
    result = false;
    for (i in A){
        if(elem == A[i]){
            result = true;
            break;
        }
    }
    return result;
}