/**
 * Restore Helper
 */
var RestoreForm = {
    /**
     * Restores radiobox - Just provide an ID of element or element itself which needs to be restored
     * @param {Object} id
     */
    radio  : function(id) {
        try{
            $(id).checked = true;
        }
        catch(e){}
    },
    /**
     * Restires Drop Down by key - Just provide an ID and Key value that needs to be restored
     * @param {Object} id
     * @param {Object} value
     */
    dropdown : function(id, value) {
         var elem = $(id);

         var selInx = 0;
         for(var i = 0, iL = elem.options.length; i<iL; i++)
         {
            if(elem.options[i].value == value)
            {
                selInx = i;
                break;
            }
         }
         elem.selectedIndex = i;
    },
    /***
     * Restore Input Text
     * @param {Object} id
     * @param {Object} value
     */
    input : function(id, value) {
        try
        {
            var elem = $(id);
            if(value == "") {
                elem.value = elem.defaultValue;
            }
            else {
                elem.value = value;
            }
        }
        catch(e){}
    }
}
/**
 * Switch Between Login and Forget Password forms
 * @param  id
 */
function toggleLoginBox(id) {
    if(id == 'login') {
        $('loginBoxForm').style.display = 'block';
        $('forgotPasswordForm').style.display = 'none';
        $('loginBoxMsg').style.display = 'none';
    }
    else if(id == 'forgotpassword') {
        $('forgotPasswordForm').style.display = 'block';
        $('loginBoxForm').style.display = 'none';
        $('loginBoxMsg').style.display = 'none';
    }
    else {
        $('forgotPasswordForm').style.display = 'none';
        $('loginBoxForm').style.display = 'none';
        $('loginBoxMsg').style.display = 'block';
    }
}
/**
 * Checks if elements exists in array
 */
function in_array(needle, haystack, strict) {

    var found = false, key, strict = !!strict;

    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }

    return found;
}
/**
 * checks if a variable is an instance of Array
 */
function is_array( mixed_var ) {
    return ( mixed_var instanceof Array );
}
/**
 * Checks if provided string is a correct email address
 */
function isSimpleEmail(email)
{
    return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
}
/**
 *
 */
function applyToApplication(application)
{
    var type = '';
    var url = 'index.php?action=apply&type=';
    switch(application)
    {
        case 'A':case 'B':case 'B2': case 'S':
            type = application;
            break;
        default:
            type = '';
            break;
    }
    window.location.href=url+type;
}
/**
 *
 */
function changeStudentAwardType(awardElem)
{
    var val = awardElem.value;
    var divs = ['SRF', 'IRF', 'NIF', 'PF', 'RTF', 'RS'];
    for(var i=0, iL=divs.length; i<iL; i++)
    {
        var tmpEl = $('additional_' + divs[i]);
        if(val == divs[i])
        {
            tmpEl.style.display = 'block';
            continue;
        }
        tmpEl.style.display = 'none';
    }
}
/**
 *
 */
function sendForgotEmail()
{
    var email = $('forgotpassword_email').value;
    if(!isSimpleEmail(email)) {
        alert('Please provide a valid email address.');
        return false;
    }

    new Ajax.Request('/_ajax/user_forgot_password.php',
                  {
                     parameters : {
                         useremail : email
                     },
                     method : 'post',
                     onSuccess : function(text) {
                        var res = text.responseText;
                        $('loginBoxMsg').update(res);
                        toggleLoginBox('loginBoxMsg');
                     }
                  });
    $('loginBoxMsg').update('Processing your request...');
    toggleLoginBox('loginBoxMsg');
}
/**
 *
 */
function getRPGDataMap()
{
    var data =     [
        {name:'app[citizenship]'     , id: 'app_citizenship'    , type:'radio' },
        {name:'app[is_enrolled]'     , id: 'app_is_enrolled'    , type:'radio' },
        {name:'app[is_appointed]'    , id: 'app_is_appointed'   , type:'radio' },
        {name:'app[is_ontario_resident]'    , id: 'app_is_ontario_resident'   , type:'radio' },
        {name:'app[is_sole_invest]'  , id: 'app_is_sole_invest' , type:'radio' },
        {name:'app[num_invest]'      , id: 'app_num_invest'     , type:'text'  },
        {name:'app[is_new]'          , id: 'app_is_new'         , type:'radio' },
        {name:'app[is_expect_other]' , id: 'app_is_expect_other', type:'radio' },
        {name:'app[other_invest]'    , id: 'app_other_invest'   , type:'text'  } //,
//        {name:'app[award]'           , id: 'app_award'          , type:'select', items:['BJSEF','OMHF','Both']}
    ];
    return data;
}
/**
 *
 */
function getStudentDataMap()
{
    var data =     [
        {name : 'app[citizenship]', id:'app_citizenship', type:'radio'},
        {name : 'app[is_enrolled]', id:'app_is_enrolled', type:'radio'},
        {name : 'app[is_new]'     , id:'app_is_new'     , type:'radio'},
        {name : 'app[award]'      , id:'app_award'      , type:'select',
         items:['SRF','IRF','NIF','PF','RTF','RS']}
    ];
    return data;
}
/**
 *
 */
function submitRPGForm()
{
    var form     = $('applyform');
    var fields   = getRPGDataMap();
    var errors   = [];
    var sucesses = [];

    for(var i=0, iL=fields.length; i<iL; i++)
    {
        switch(fields[i]['type'])
        {
            case 'radio':
                var elems = document.getElementsByName(fields[i]['name']);
                if(!isRadioChecked(elems))
                    errors.push(fields[i]['id']);
                else
                    sucesses.push(fields[i]['id']);
                break;
            case 'text':
                //SPECIAL CASE OF NUMBER INVESTERS
                if( fields[i]['id'] == 'app_num_invest')
                {

                   if( $('app_is_sole_invest_0').checked == true )
                    {//ONLY IF NO
                        var val = $(fields[i]['id']).value;
                        if(!isNumber(val , 1, 1000000))
                            errors.push(fields[i]['id']);
                        else
                            sucesses.push(fields[i]['id']);
                    }
                    else
                    {//IF YES, ALWAYS SUCCESS
                        sucesses.push(fields[i]['id']);
                    }
                }
                //SPECIAL CASE OF INVESTERS NAME, TYPE
                if( fields[i]['id'] == 'app_other_invest')
                {

                   if( $('app_is_expect_other_1').checked == true )
                    {//ONLY IF NO
                        var val = $(fields[i]['id']).value;
                        if(!isBetween(val , 1, 1000000))
                            errors.push(fields[i]['id']);
                        else
                            sucesses.push(fields[i]['id']);
                    }
                    else
                    {//IF YES, ALWAYS SUCCESS
                        sucesses.push(fields[i]['id']);
                    }
                }
                break;
            case 'select':
				try
				{
                  var val = $(fields[i]['id']).value;					
				}
				catch (e)
				{
					console.log(fields[i]);
				}

                if(!in_array(val, fields[i]['items']))
                    errors.push(fields[i]['id']);
                else
                    sucesses.push(fields[i]['id']);
                break;
        }
    }
    applyFormErrors(errors);
    applyNoFormErrors(sucesses);
    if(errors.length > 0)
    {
        return;
    }
    form.submit();
}
/**
 *
 */
function submitStudentForm()
{
    var form     = $('applyform');
    var fields   = getStudentDataMap();
    var errors   = [];
    var sucesses = [];

    for(var i=0, iL=fields.length; i<iL; i++)
    {
        switch(fields[i]['type'])
        {
            case 'radio':
                var elems = document.getElementsByName(fields[i]['name']);
                if(!isRadioChecked(elems))
                    errors.push(fields[i]['id']);
                else
                    sucesses.push(fields[i]['id']);
                break;
            case 'text':
                //THERE IS NO TEXT FIELDS
                break;
            case 'select':
                var val = $(fields[i]['id']).value;

                if(!in_array(val, fields[i]['items']))
                    errors.push(fields[i]['id']);
                else
                    sucesses.push(fields[i]['id']);

                //SPECIAL CASE
                break;
        }
    }
    //SPECIAL CASE : Check Award Data
    var award = $('app_award').value;
    var radios = [];
    var texts  = [];
    var checkboxes = [];
    var selects = [];
    switch(award)
    {
        case 'SRF': case 'IRF':
            radios = [
                      {name:'app[is_' + award + '_before]', id:'app_is_'+award+'_before'} ,
                      {name:'app[is_' + award + '_other]' , id:'app_is_'+award+'_other'}
                     ];
            if( $('app_is_'+award+'_other_1').checked == true )
            {
                texts = ['app_'+award+'_title'];
            }
            break;
        case 'NIF':
            checkboxes = [
                'app_is_'+award+'_salary',
                'app_is_'+award+'_substitution',
                'app_is_'+award+'_operating'
            ];
            radios = [{name:'app[is_' + award + '_other]' , id:'app_is_'+award+'_other'}];
            if( $('app_is_'+award+'_other_1').checked == true )
            {
                texts = ['app_'+award+'_title'];
            }
            break;
        case 'PF': case 'RTF': case 'RS':
            var t_items = [1,2,3];
            if(award == 'PF')
            {
                t_items = [2,3]
            }
            selects = [{id:'app_'+award+'_years', items:t_items}];
            break;
    }

    //
    //additional radios
    //
    for(var i=0, iL=radios.length; i<iL; i++)
    {

        var elems = document.getElementsByName(radios[i]['name']);

        if(!isRadioChecked(elems))
            errors.push(radios[i]['id']);
        else
            sucesses.push(radios[i]['id']);
    }
    //
    // additonal texts
    //
    for(var i=0, iL=texts.length; i<iL; i++)
    {
        var val = $(texts[i]).value;
        if(!isBetween(val, 1,255))
            errors.push(texts[i]);
        else
            sucesses.push(texts[i]);
    }
    //
    // additonal selects
    //
    for(var i=0, iL=selects.length; i<iL; i++)
    {
        var val = $(selects[i]['id']).value;
        if(!in_array(val, selects[i]['items']))
            errors.push(selects[i]);
        else
            sucesses.push(selects[i]);
    }
    applyFormErrors(errors);
    applyNoFormErrors(sucesses);
    if(errors.length > 0)
    {
        return;
    }
    form.submit();
}
/**
 *
 */
function isRadioChecked(elems)
{
    for(var i=0, iL=elems.length; i<iL; i++)
    {
        if(elems[i].checked == true)
        {
            return true;
        }
    }
    return false;
}
/**
 *
 */
function isBetween(val, minimum, maximum)
{
    if(!val || val == '')
    {
        return false;
    }
    if(val.length < minimum || val.length>maximum)
    {
        return false;
    }
    return true;
}
/**
 *
 */
function isNumber(val, minimum, maximum)
{
    if(!val || val == '')
    {
        return false;
    }
    val = parseInt(val);
    if(val < minimum || val>maximum)
    {
        return false;
    }
    return true;
}

/**
 *
 */
function applyFormErrors(errors)
{
    applyBackgroundStyle(errors, '#FFDFDF');
}
/**
 *
 */
function applyNoFormErrors(sucess)
{
    applyBackgroundStyle(sucess, '#FFFFFF');
}
/**
 *
 */
function applyBackgroundStyle(elems, color)
{
    for(var i=0, iL=elems.length; i<iL; i++)
    {
        try
        {
            var tmp = $('tr_' + elems[i]);
            tmp.style.backgroundColor = color;
        }catch(e)
        {
            //alert('Error:' + elems[i]);
        }
    }
}
function getAllAdditional()
{
    var elems = [
        $('app_is_NIF_salary'),
        $('app_is_NIF_substitution'),
        $('app_is_NIF_operating')
    ];
    return elems;
}
/**
 *
 */
function checkAdditional(elem)
{
    if(elem.checked == true)
    {
        var isAllChecked  = true;
        var elems = getAllAdditional();
        for(var i=0, iL = elems.length; i<iL; i++)
        {
            if(!elems[i].checked)
            {
                isAllChecked = false;
                break;
            }
        }
        //---check if all not checked
        if(isAllChecked)
        {
            alert('Can only select 1 or 2 of 3 (Not all 3)');
            elem.checked = false;
        }

    }
}