/***********************************************************/
//Author: Joel Azcuna
//Created: December 2010
//Updated: March 03, 2011
//File: basic.js
//Desc: General user-defined JS functions
/***********************************************************/

/*--- Variables -----------------------------*/
var prompt_style = {
    'background-color':'#ACA589',
    'color':'#7F080A',
    'font-weight':'bold',
    'text-align':'center',
    'padding':'5px',
    'font-size':'120%'
};

/*--- Date -----------------------------*/

//Created: January 2011
//Updated: 
//Desc: generate JS date from F&C date format e.g. 25-01-2011
function convert_date(date) {
    var date_array = date.split('-');
    
    var day = date_array[0];
    var month = date_array[1] - 1;
    var year = date_array[2];
    
    var this_date = new Date();
        this_date.setYear( year );
        this_date.setMonth( month );
        this_date.setDate( day );

    return this_date;
    //return year + ' ' + month + ' ' + day;
}


/*--- Numeric -----------------------------*/

//Created: December 2010
//Updated:
//Desc: check if value is a currency/float.
//      deem to be deprecated..
function is_currency(val) {
    //var = alltrim(val);
    return /^[-+]?[0-9]+(\.[0-9]+)?$/.test( remove_comma(val) );
}

//Created: March 02, 2011
//Desc: check if the val is float, to be use for currency or float fields.
//      will supersede is_currency.
function is_float(val){
    val = remove_comma(val);
    var val_array = val.split('.');
    if( val_array.length != 2 ) {
        return false;
    } else {
        var left_val  = val_array[0];
        var right_val = val_array[1];
        if( is_int(left_val) && is_int(right_val) ) {
            return true;
        } else {
            return false;
        }
    }

}

//Created: March 02, 2011
//Updated: 
//Desc: check if value is an integer
function is_int(val){
   for (var i = 0 ; i < val.length ; i++) {
      if ( (val.charAt(i) < '0') || (val.charAt(i) > '9') ) {
        return false
      }
   }
   return true;
}

/*--- String -----------------------------*/

//Created: December 2010
//Updated:
//Desc: remove comma in a string, use for curreny val
function remove_comma(val) {
   return val.replace(/,/g,'');
}

//Created: March 02, 2011
//Updated: March 07, 2011
//Desc: check if value (str) is empty 
function is_str_empty(val) {
    if( parseInt(val.length) < 1 ) {
        return true;
    }
    return false;
}

//Created: March 02, 2011
//Updated: 
//Desc: search string in a target string
function is_str_found(this_str, to_search) {
    this_str = this_str.toLowerCase();
    //to_search = $.trim(to_search.toLowerCase());
    to_search = to_search.toLowerCase();

    if( this_str.search(to_search) >= 0 ) {
        return true;
    } else {
        return false;
    }
}

/*--- Array -----------------------------*/

//Created: March 02, 2011
//Updated: 
//Desc: check value in an array.
//Dependencies: jQuery $.inArray
function is_in_array(this_val, this_array) {
    if( $.inArray( this_val, this_array ) != -1 ) {
        return true;
    } else {
        return false
    }
}

/*--- Validation -----------------------------*/

//Created: March 02, 2011
//Updated: 
//Desc: validate email address format
function is_valid_email(this_email) {
    var emailRegexp = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i
    if( !emailRegexp.test( this_email ) ) {
        return false;
    } else {
        return true;
    }
}

//Created: March 03, 2011
//Updated:
//Desc: validate a radio group, returns true if one is ticked, false if none.
//      Also applicable to checkbox.
//Dependencies: jQuery - attr
function validate_radio(this_fields) {
    var is_ticked = false;
    this_fields.each(function(){
        if( $(this).attr('checked') == true ) {
            is_ticked = true;
        }
    });
    return is_ticked;
}

//Created: March 08, 2011
//Updated:
//Desc: validate a currency/float value
//Dependencies: jQuery - val, Basic.js is_str_found, is_str_empty, is_float.
function validate_float(this_field) {
    //Check if it's optional
    if( is_str_found( this_field.attr('class'), 'optional' ) ) {
        //Check if negative values AND empty AND not float.
        if ( parseFloat(this_field.val()) < 0
                && !is_str_empty(this_field.val())
                    && !is_float( this_field.val() ) ) {

            //prompt_custom(this_field, '', 'prompt_'+table_no);
            //is_empty = true;
            return {'flag':false, 'message':'must have numeric value and not less than 0'};
        }
    } else { //No Optional, must have value and it's non-negative
        if ( parseFloat(this_field.val()) <= 0 || !is_float( this_field.val() ) ) {
            //prompt_custom(this_field, 'must have numeric value and should be more than 0', 'prompt_'+table_no);
            //is_empty = true;
            return {'flag':false, 'message':'must have numeric value and more than 0'};
        }
    }
    return {'flag':true};
}

//Created: March 08, 2011
//Updated:
//Desc: validate an integer value
//Dependencies: jQuery - val, Basic.js - is_int
function validate_integer(this_field) {
    //Original code here..
    /*
    if( parseInt( this_field.val() < 0 ) || !is_int( this_field.val() ) ) {
        return {'flag':false, 'message':'must have integer value and should not be less than 0'};
    }
    */
    if( is_str_found( this_field.attr('class'), 'optional' ) ) {
        if( !is_str_empty( this_field.val()) ) {
            //Proceed ONLY if the user enters some values, the user has the option to enter empty value.
            if( parseInt( this_field.val() ) < 0 || !is_int( this_field.val() ) ) {
                return {'flag':false, 'message':'must be a whole integer and not less than 0'};
            }
        }
    } else {
        //console.log( this_field.val() );
        this_field_val = $.trim( this_field.val() );
        if( ! is_int( this_field_val ) ) { //  // parseInt( this_field_val, 10 ) < 0
            return {'flag':false, 'message':'must be a whole integer and not less than 0'};
        }

        if( parseInt( this_field_val ) < 0 ) {
            return {'flag':false, 'message':'must be a whole integer and not less than 0'};
        }
    }
    return {'flag':true};
}

/*--- Prompts -----------------------------*/

//Created: December 2011
//Updated:
//Desc: show prompt to users for radio buttons.
//Dependencies: jQeury - show, css, text
function prompt_radio(this_field, message, container_id) {
    $('.prompt').hide();
    this_field.focus();
    $('#'+container_id).show();
    $('#'+container_id).css(prompt_style);
    $('#'+container_id).text( message + '?' );
}


function prompt_custom(this_field, this_message, container_id) {
    //hide/clear all prompt containers e.g. <div>
    $('.prompt').hide();

    var field_name = this_field.attr('title');
    this_field.focus();
    $('#'+container_id).show();
    $('#'+container_id).css(prompt_style);
    $('#'+container_id).text(field_name + ' ' + this_message +'.' );
}

/*--- Others -----------------------------*/

//Created: December 2010
//Updated: 
//Desc: Pop-ups window for printing e.g. reports.
function report_window(mypage,myname,w,h,scroll,pos) {
    if(pos=="random"){
            LeftPosition = (screen.width)?Math.floor(Math.random()*(screen.width-w)):100;
            TopPosition  = (screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;
    }
    if(pos=="center"){
            LeftPosition = (screen.width)?(screen.width-w)/2:100;
            TopPosition  =(screen.height)?(screen.height-h)/2:100;
    }
    else if((pos!="center" && pos!="random") || pos==null) {
            LeftPosition=0;TopPosition=20
    }

    settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes';
    win=window.open(mypage,myname,settings);

    //To ensure that the common print page is on focus every time a print button is click in all of report modules.
    if (window.focus) {win.focus()}
}
