server_type = 'main';


window.addEvent('domready', function(){
    $$('.tooltip').each(function(element,index) {
        var content = element.get('title').split('::');
        element.store('tip:title', content[0]);
        element.store('tip:text', content[1]);
    });

    var tooltip = new Tips('.tooltip',{
        className: 'tooltip',
        fixed: true,
        hideDelay: 50,
        showDelay: 50,
        offsets: {x: 10, y: 20}
    });

    tooltip.addEvents({
        'show': function(tip) {
            tip.fade('in');
        },
        'hide': function(tip) {
            tip.fade('out');
        }
    });


    new vlaDatePicker('birthday', {
        prefillDate: { day: 1, month: 1, year: 1995 },
        style: 'apple_widget',
        offset: { x: -105, y: 20 },
        defaultView: 'decade',
        'format': 'm/d/y',
        filePath: 'http://acard.ayalamalls.com.ph/js/vlaCalendar/'
    });

    check = '';

    setFormchecker();

    setEventListener();

});

function setEventListener() {
    //page 1
    $('btnNext').addEvent('click', function(){
        validateFieldPage1();
    });

    //page 2
    //back to page 1
    $('btnBack').addEvent('click', function(){
        validateFieldPage2('btnBack');
    });
    //send form
    $('btnDone').addEvent('click', function(){
        validateFieldPage2('btnDone');
    });

    $('occupation').addEvent('keyup', function(){
        setOccupationChoices();
    });
    $('occupation').addEvent('keydown', function(){
        setOccupationChoices();
    });
    $('occupation').addEvent('change', function(){
        setOccupationChoices();
    });


    $('mall_visit1').addEvent('change', function(){
        setMallVisitChoices('mall_visit1');
    });
    $('mall_visit2').addEvent('change', function(){
        setMallVisitChoices('mall_visit2');
    });
    $('mall_visit3').addEvent('change', function(){
        setMallVisitChoices('mall_visit3');
    });

    $('visit_frequency2').addEvent('change', function(){
        if ($('visit_frequency2').value == '') {
            $('mall_visit2').options[0].selected = 'Selected';
            $('mall_visit2').fireEvent('change');
        }
    });
    $('visit_frequency3').addEvent('change', function(){
        if ($('visit_frequency3').value == '') {
            $('mall_visit3').options[0].selected = 'Selected';
            $('mall_visit3').fireEvent('change');
        }
    });

    $('imgCalendar').addEvent('click', function(){
        $('birthday').fireEvent('click');
    });

    $('ckbInterestOthers').addEvent('click', function(){
        toggleInterestOthersBox();
    });

    $('professionSelfEmployed').addEvent('change', function(){
        if ('Other' == $('professionSelfEmployed').value) {
            $('txtSpecOccup').removeClass('hidden');
        }else {
            $('txtSpecOccup').addClass('hidden');
        }
    });

    $('city').addEvent('change', function(){
        if ('Other' == $('city').value) {
            $('city_other').removeClass('hidden');
        }else {
            $('city_other').addClass('hidden');
        }
    });
}



function toggleInterestOthersBox() {
    $('txtInterestOthers').value = '';

    if ($('ckbInterestOthers').getProperty('checked')) {
        $('txtInterestOthers').setStyle('display','block');
    }else {
        $('txtInterestOthers').setStyle('display','none');
    }
}

function setMallVisitChoices(current) {
    //if current selection is 1st
    if ('mall_visit1' == current) {
        //if 1st selection is empty; disable the 2nd and 3rd mall selection
        if ($(current).value == '') {
            setMallSelectionDisable(current);
        }else {
            //populate the 2nd second select mall
            //empty the 2nd select mall
            $('mall_visit2').empty();
            $('mall_visit3').empty();

            $(current).getChildren().each(function(el, i) {
                //check if not selected; then add the element to the 2nd mall list
                if(el.getProperty('selected') == false) {
                    el.clone().injectInside($('mall_visit2'));
                }
            });

            $('mall_visit2').removeProperty('disabled');
            // $('visit_frequency2').removeProperty('disabled');

            $('mall_visit3').setProperty('disabled');
        }
    }else if ('mall_visit2' == current) {
        //if 1st selection is empty; disable the  3rd mall selection
        if ($(current).value == '') {
            setMallSelectionDisable(current);
        }else {
            //populate the 3rd second select mall
            //empty the 3rd select mall
            $('mall_visit3').empty();

            $('mall_visit1').getChildren().each(function(el, i) {
                //check if not selected; then add the element to the 2nd mall list
                if(el.getProperty('selected') == false) {
                    //check the second if not selected; then add it to the 3rd selection
                    $('mall_visit2').getChildren().each(function(el2, i) {
                        if (el.value == el2.value) {
                            if(el2.getProperty('selected') == false) {
                                el2.clone().injectInside($('mall_visit3'));
                            }
                        }
                    });
                }
            });

            $('visit_frequency2').removeProperty('disabled');
            $('visit_frequency2').options[0].selected = 'Selected';
            $('visit_frequency3').options[0].selected = 'Selected';

            $('mall_visit3').removeProperty('disabled');
            // $('visit_frequency3').removeProperty('disabled');
        }
    }else if ('mall_visit3' == current) {
        if ($(current).value == '') {
            setMallSelectionDisable(current);
        }else {
            $('visit_frequency3').removeProperty('disabled');
        }
    }
}

function setMallSelectionDisable(current) {
    if ('mall_visit1' == current) {
        $('mall_visit2').empty();
        $('mall_visit3').empty();

        $('mall_visit2').setProperty('disabled');
        $('mall_visit3').setProperty('disabled');

        $('visit_frequency1').options[0].selected = 'Selected';
        $('visit_frequency2').options[0].selected = 'Selected';
        $('visit_frequency3').options[0].selected = 'Selected';

        $('visit_frequency2').setProperty('disabled');
        $('visit_frequency3').setProperty('disabled');

    }else if('mall_visit2' == current) {
        $('mall_visit3').empty();

        $('mall_visit3').setProperty('disabled');

        $('visit_frequency2').options[0].selected = 'Selected';
        $('visit_frequency3').options[0].selected = 'Selected';

        $('visit_frequency2').setProperty('disabled');
        $('visit_frequency3').setProperty('disabled');
    }else if('mall_visit3' == current) {
        $('visit_frequency3').options[0].selected = 'Selected';
        $('visit_frequency3').setProperty('disabled');
    }
}

/*
function getMallList(selected, current) {
    if ('mall_visit2' == current) {
        selected = selected + '|' + $('mall_visit1').value;
    }

    var url = app_root_url + 'acard/signup/listmall/' + selected + '/' + new Date().getTime();
    var req = new Request({
        method: 'get',
        url: url,
        // data: { 'do' : '1' },
        // data: mydata,
        // update:{$('mall_visit2'),$('mall_visit3')},
        onRequest: function() {
        },
        onSuccess: function(response){

            if ('mall_visit1' == current) {
                $('mall_visit2').set('html', response);
                $('mall_visit3').set('html', '');
            }
            if ('mall_visit2' == current) {
                $('mall_visit3').set('html', response);
            }
        },
        onComplete: function(response) {
        },
        onFailure: function(){
            alert('Unable to process your request, please try again later. Thank you.');
        }
    }).send();



    var url = app_root_url + 'acard/signup/listmallvisitfrequency/' + new Date().getTime();
    var req = new Request({
        method: 'get',
        url: url,
        onRequest: function() {
        },
        onSuccess: function(response){

            if ('mall_visit1' == current) {
                $('visit_frequency2').set('html', response);
                $('visit_frequency3').set('html', '');
            }
            if ('mall_visit2' == current) {
                $('visit_frequency3').set('html', response);
            }
        },
        onComplete: function(response) {
        },
        onFailure: function(){
            alert('Unable to process your request, please try again later. Thank you.');
        }
    }).send();

}*/

function setOccupationChoices() {
    $$('.occupationChoices').each(function(item, index) {
        item.addClass("hidden");
    });

    $$('.radioProfession').each(function(item, index) {
        item.removeProperty('checked');
    });

    $('professionSelfEmployed').options[0].selected = 'Selected'

    //make sure the following field is empty
    $('employed_office_tel').value = '';
    $('employed_office_add').value = '';
    $('employed_company_name').value = '';
    $('student_name_of_school').value = '';
    $('student_school_location').value = '';
    $('txtSpecOccup').value = '';

    $('txtSpecOccup').addClass('hidden');

    //set the default employed info properties
    $('employed_company_name').setProperty('class','text vlong');
    $('employed_office_add').setProperty('class','text mid smallspace');

    $('student_name_of_school').setProperty('class','text mid smallspace');
    $('student_school_location').setProperty('class','text mid');


    if ('Employed' == $('occupation').value) {
        $('liEmployed').removeClass("hidden");

        //add required on name of company and company address
        $('employed_company_name').addClass("requiredFieldP2 validate['required']");
        $('employed_office_add').addClass("requiredFieldP2 validate['required']");

    }else if ('Self Employed' == $('occupation').value) {
        $('liSelftEmployed').removeClass("hidden");
    }else if ('Student' == $('occupation').value) {
        $('liStudent').removeClass("hidden");

        $('student_name_of_school').addClass("requiredFieldP2 validate['required','length[45]']");
        $('student_school_location').addClass("requiredFieldP2 validate['required','length[45]']");
    }

    closeAllErrorMessage();
    setFormchecker();
}

function isValidBirthday() {
    if ('' == $('birthday').value) {
        return false;
    }else {
        birthday = $('birthday').value.split('/');
        b_year = birthday[2];
        age = 2008 - b_year;

        if (isNaN(age)) {
            return false;
        }else if (age == '') {
            return false;
        }else if (age < 13) {
            return false
        }else {
            //this should not happen
        }
    }

    return true;
}

function isConfirmedPassword() {
    if ($('password').value != $('cpassword').value) {
        return false;
    }

    return true;
}

function trimString(s) {
    return s.replace(/^\s+|\s+$/g,'');
}

function isEmailValid(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   // var reg = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/;

    if(reg.test(email) == false) {
        return false;
    }else {
        return true;
    }
}

function validateFieldPage1() {
    //trim the email address
    // $('birthday').value =
    $('email').value = trimString($('email').value);

    //check the required fields
    flag = true;
    ctr = 1;
    requiredField = '';

    $$('.requiredFieldP1').each(function(item, index) {
        if (item.value.trim() == '') {
            flag = false;
            requiredField = requiredField + "\n" + item.name;

            if (1 == ctr) {
                first_required_field = item;
            }
            ctr++;
        }
    });

    //check first if user already exist before checking the field
    var first_name = $('first_name').value;
    var last_name = $('last_name').value;
    var middle_initial = $('middle_initial').value;
    var email = $('email').value;

    if (false == flag) {
        first_required_field.fireEvent('blur');
        // showPage(1,2);
    }else {
        //check if valid birthday
        if (false == isValidBirthday()) {
            alert('Sorry, please check your birthdate. Only 13 years old and above can join the A Card program.');

                }else if (!isEmailValid($('email').value)) {
            alert('Sorry, the email is invalid.');
        
        
        }else if ('Other' == $('city').value && '' == $('city_other').value) {
            alert('Please specify other city. Thank you.');
        }else if (!isConfirmedPassword()) {
            alert("Your password doesn't mach. Please try typing again your password. Thank you.");
        }else {
            var user_exist = checkIfUserExist(first_name, last_name, middle_initial, email);

            user_exist.addEvent('onSuccess',function(response){
                try {
                    var is_exist = response.status;

                    if (0 == is_exist) {
                        $('buttonP1').setStyle('display','block');
                        showPage(1,1);
                        alert(response.msg);
                    }else {
                        showPage(1,2);
                        $('txtStoreFood1').focus();
                        closeAllErrorMessage();
                    }
                } catch (ex) {
                    $('buttonP1').setStyle('display','block');
                    showPage(1,1);
                    alert('Sorry, unable to process your request. Please try again later.');
                }
            });
        }
    }
}
function validateFieldPage2(button) {
    if ('btnBack' == button) {
        closeAllErrorMessage();
        showPage(2,1);

    }else {
        //check the required fields
        flag = true;
        ctr = 1;
        requiredField = '';

        $$('.requiredFieldP2').each(function(item, index) {
            if (item.value.trim() == '') {
                flag = false;
                requiredField = requiredField + "\n" + item.name;

                if (1 == ctr) {
                    first_required_field = item;
                }
                ctr++;
            }
        });

        if (false == flag) {
            first_required_field.fireEvent('blur');
        }else {
            // validate the mall information
            if ($('mall_visit2').value != '' && $('visit_frequency2').value == '') {
                alert('Please complete the mall information. Thank you.');
                return;
            }else if ($('mall_visit3').value != '' && $('visit_frequency3').value == '') {
                alert('Please complete the mall information. Thank you.');
                return;
            }else if ('Other' == $('professionSelfEmployed').value && '' == $('txtSpecOccup').value) {
                alert('Please specify other profession. Thank you.');
                return;
            }

            //send confirmation alert to user
            confirm_message = "You are about to submit the form. If you're sure that the information is correct click Ok button, press Cancel button to edit your information. Thank you.";

            if (true == confirm(confirm_message)) {
                sendForm($('frmRegister'));
            }

        }

    }
}

function closeAllErrorMessage() {
    $$('.close').each(function(item, index) {
        item.fireEvent('click');
    });
}

function testCheckUser() {
    var user_exist = checkIfUserExist('Juan', 'Dela Cruz', 'D', 'ronald@gmail.com');

    user_exist.addEvent('onSuccess',function(response){
        try {
            if (0 == response.status) {
                alert(response.msg);
            }else {
                alert(response.msg);
            }
        } catch (ex) {
            alert('Sorry, unable to process your request. Please try again later.');
        }
    });
}

function checkIfUserExist(first_name, last_name, middle_initial, email) {
    var url = app_root_url + 'acard/applicant/isuserexist';
    var req = new Request.JSON({
        // async: false,
        method: 'post',
        url: url,
        data: {
            'first_name' : first_name,
            'last_name' : last_name,
            'middle_initial' : middle_initial,
            'email' : email
        },
        // update:{$('mall_visit2'),$('mall_visit3')},
        onRequest: function() {
            $('buttonP1').setStyle('display','none');

            $('ajaxStatusTextLoader').setStyle('display','block');
            $('frmPage1').addClass("frmHide");
        },
        onSuccess: function(response){
            $('ajaxStatusTextLoader').setStyle('display','none');
            $('frmPage1').addClass("frmShow");
        },
        // onComplete: function(response) {
        // },
        onFailure: function(){
            alert('Unable to process your request, please try again later. Thank you.');
            $('ajaxStatusTextLoader').setStyle('display','none');
            showPage(1,1);
        }
    }).send();

    return req;
}

function sendForm(mydata) {
    var url = app_root_url + 'acard/signup/';
    var req = new Request.JSON({
        method: 'post',
        url: url,
        data: mydata,
        // update:{$('mall_visit2'),$('mall_visit3')},
        onRequest: function() {
            $('buttonP2').setStyle('display','none');
            $('ajaxStatusTextLoader').setStyle('display','block');
            $('frmPage2').addClass("frmHide");
        },
        onSuccess: function(response){
            try {
                $('ajaxStatusTextLoader').setStyle('display','none');
                $('frmPage2').addClass("frmShow");

                if (0 == response.status) {
                    $('buttonP2').setStyle('display','block');
                    showPage(2,2);
                    alert(response.msg);
                }else {
                    $('pDone').set('html', response.msg);
                    showPage(2,3);
                }
            } catch (ex) {
                $('buttonP2').setStyle('display','block');
                showPage(2,2);
                alert('Sorry, unable to process your request. Please try again later.');
            }
        },
        onComplete: function(response) {
        },
        onFailure: function(){
            alert('Unable to process your request, please try again later. Thank you.');
        }
    }).send();
}
