
//var emailRe = "/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/"
//TODO: Warning, the expression above is VERY VERY #@$#$ PERFORMANCE WRONG. 
//Try to use it and enter around 15-20 characters in email text input area in editor.. browser hangup sure!
//var emailRe = /^(\w+\.)*(\w+)@(\w+\.)+([a-zA-Z]{2,4})$/  --wrong cause does not accept "nthx-tomasz@nthx.pl"
var emailRe = /^([\w!#$%*/?|^{}`~&\'+-=_]+)*([\w!#$%*/?|^{}`~&\'+-=_]+)@([\w-]+\.)+([a-zA-Z]{2,4})$/
var sipRe = /^([a-zA-Z_@])+([a-zA-Z_@0-9])*$/
var intRe = /^[0-9]*$/
var phoneRe = /^[+\ \.\-\(\)\\\/0-9]*$/

//Some global variable for developer's use
var global = [];

if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

/* TODO: make it work under IE!
if(!Array.push){
    Array.prototype.push = function(obj){
        this[this.length] = obj;
    }
}
*/


    

//todo: better map, real removes
function Map() {};

//is there any editing process?
var is_record_edition_ongoing = false;


/* Makes input to look like it is [not] validated */
function fieldNotValidated(field){
    //TODO: color taken from input.validation-failed in style.css
    $(field).css( "background", "#FFC0CB" );
    //Also enable input, so interpreter has a chance to edit field
    field.disabled = false;
}
function fieldValidated(jq_field){
    jq_field.css("background", "");
}

function disableButton(jqBtn){
    jqBtn.attr("disabled", "true");
}
function enableButton(jqBtn){
    jqBtn.removeAttr("disabled");
}


/* Returns true, when text is valid email */
function validator_email(text) {
    //console.debug('validator_email');
    //text = trim(text);
    return emailRe.test(text)
        && text != ''
        && text.length > 2
        && text.substr(0,1) != '.'
        && -1 == text.indexOf('.@');
}
/* Returns true, when text is present */
function validator_required(text, field_type) {
    //console.debug('validator_required');
    switch (field_type){
    case "text":
        return !is_empty(text);
    case "select-one":
        return !(is_empty(text) || text == "-1");
    default:
        console.error("wrong type specified: " + field_type);
    }
}
function validator_int(text, field_type) {
    //console.debug('validation_int: ' + parseInt(text));
    return !isNaN(parseInt(text)) && intRe.test(text);
}
/* Returns true, when text different than simple '0' */
function validator_local_phone(text, field_type){
    //console.debug('validator_local_phone');
//    text = trim(text); --for performance reasons
    
    //[1-9]abcdef ok
    if (text.length>0 && '0'!=text.substr(0, 1))
        return true;

    //00abcde - ok
    if (text.length>1 && '0'!=text.substr(1, 1))
        return true;
    
    //0[1-9]* - not ok
    for (var i=1; i<text.length; i++)
    {
        if ('0' != text.substr(i, 1))
            return true; 
    }
    return false;
}

/* Returns true, when phone contains: [0-9] and + characters */
function validator_phone_numbers_only(text, field_type, owning_record){
    //console.debug('validator_phone_numbers_only');

    var phone_country = owning_record.fields.phone_country;
    var country_code = phone_country.getValue();
    if (is_sip(country_code)){
        //always true, when selected sip@phone
        return true;
    }

    return phoneRe.test(text);
}


/* Returns true, when text is part of valid date */
function validator_proper_date_ym(text, field_type) {
    //console.debug('validator_proper_date_ym');
/* check date_ym and date_d if they merge to a proper date */
    if (!editor.dateSubject.fields.date_d.edit)
        return true;

    var date_d = editor.dateSubject.fields.date_d.getValue();
    if (is_empty(text) || text == "-1"
        || is_empty(date_d) || date_d == "-1"){
        return true;
    }

    //function from DatePopup.js
    var result = parseDate(text + "-" + date_d);
    return null != result;

}
/* Returns true, when text is part of valid date */
function validator_proper_date_d(text, field_type) {
/* check date_ym and date_d if they merge to a proper date */
    //console.debug('validator_proper_date_d');
    if (!editor.dateSubject.fields.date_ym.edit)
        return true;

    var date_ym = editor.dateSubject.fields.date_ym.getValue();

    if (is_empty(text) || text == "-1"
        || is_empty(date_ym) || date_ym == "-1"){
        return true;
    }

    //function from DatePopup.js
    var result = parseDate(date_ym + "-" + text);
    return null != result;
}

/*  */
function validator_phone_country(text, field_type) {
    //console.debug("validator_phone_country: " + text + "/" + field_type);
    return !is_empty(text);
}

/** Shows warning tooltips when phone has leading '0' */
function depending_trick_remove_leading_zero(phone, dependants, record){
    //console.debug('depending_trick_remove_leading_zero');
    //dependants: d0=area, d1=country
    var phone_area = dependants[0];
    var phone_country = dependants[1];
//    var v = trim(phone.getValue()); --for performance reasons
    var v = phone.getValue();
    var country_code = phone_country.getValue();
    
    if (is_sip(country_code)){
        //do not show warnings for SIP numbers - may start with '0'
        return;
    }
    
    if ((v.length>0 && '0' == v.substr(0,1) ) &&
        !(v.length>1 && '00' ==  v.substr(0,2))
        ){
        record.show_all_tooltips();
    } else {
        record.disable_all_tooltips();
    }
}

function depends_phone_to_phone_country(phone, dependants){
    //console.debug('depends_phone_to_phone_country');
    //dependants: d0=area, d1=country
    var phone_area = dependants[0];
    var phone_country = dependants[1];

    //do nothing, unless user enters 5 characters
    var pv = phone.getValue();
    if (!is_empty(pv) && pv.length <=5)
        return;

    var splited = split_to_area_phone_with_proper_phone(phone.getValue())
    if (!is_empty(splited[0])) {
        phone_country.setValue(splited[0]);
        phone_country.validate_after_dependant_change('depends_phone_to_phone_country');
        
        phone.setValue(splited[1]);
        phone.validate_after_dependant_change('depends_phone_to_phone_country');
    } else if (is_empty(phone_area)){
        phone_country.setValue("");
        phone_country.validate_after_dependant_change('depends_phone_to_phone_country');
    }
}
function depends_phone_to_phone_area(phone, dependants){
    //console.debug('depends_phone_to_phone_area');
    //dependants: d0=area, d1=country
    var phone_area = dependants[0];

    var pv = phone.getValue();
    //do nothing, unless user enters 5 characters
    if (!is_empty(pv) && pv.length <=5)
        return;

    var splited = split_to_area_phone_with_proper_phone(phone.getValue())
    if (!is_empty(splited[0]) && !is_sip(splited[0])){
        phone_area.setValue("+"+splited[0]);
        phone_area.jq_edit.show();
        phone_area.validate_after_dependant_change('depends_phone_to_phone_area');
    }
}


function depends_phone_area_to_phone_country(phone_area, dependants){
    //console.debug('depends_phone_area_to_phone_country');
    //dependants: d0-country, d1-phone
    var phone_country = dependants[0];
    var splited = split_to_area_and_phone(phone_area.getValue());
    var pc_value = phone_country.edit.options[phone_country.edit.options.selectedIndex].value;
    if (splited[0] && "" ==splited[1]){
        phone_country.setValue(splited[0]);
        phone_country.validate_after_dependant_change('depends_phone_area_to_phone_country');
    } else  if ("sip" != pc_value) {
        phone_country.setValue("");
        phone_country.validate_after_dependant_change('depends_phone_area_to_phone_country');
    } else  if ("sip" == pc_value) {
        ;//do nothing, so 'sip' does not dissapear
    }
}
function depends_phone_area_to_phone(phone_area, dependants){
    //console.debug('depends_phone_area_to_phone');
    //dependants: d0-country, d1-phone
    var phone = dependants[1];
    var p_a = split_to_area_and_phone(phone_area.getValue());
    var p_p = split_to_area_phone_with_proper_phone(phone.getValue());
    if (p_a[0] && p_p[0] && p_p[1] && is_empty(phone.getValue())){
        phone.setValue(p_p[1]);
        phone.validate_after_dependant_change('depends_phone_area_to_phone');
    }
}
function depends_phone_country_to_phone_area(phone_country, dependants){
    //console.debug('depends_phone_country_to_phone_area');
    var phone_area = dependants[0];
    if (phone_country.getValue() && !is_sip(phone_country.getValue())){
        phone_area.setValue("+" + phone_country.getValue());
        phone_area.validate_after_dependant_change('depends_phone_country_to_phone_area');
    } else if (!is_sip(phone_country.getValue())){
        phone_area.setValue("");
        phone_area.validate_after_dependant_change('depends_phone_country_to_phone_area');
    }
}
function depends_date_h_to_date_t(date_h, dependants){
    //console.debug('depends_date_h_to_date_t');
    var date_t = dependants[0];
    var h = date_h.getValue();
    var t = date_t.getValue();
    if (!is_empty(h) && is_empty(t)){
        date_t.setValue("00");
        date_t.validate_after_dependant_change('depends_date_h_to_date_t');
    }

}
function get_dependant_fn(name){
    switch (name){
    case "depends_phone_country_to_phone_area":
        return depends_phone_country_to_phone_area;
    case "depends_phone_area_to_phone":
        return depends_phone_area_to_phone;
    case "depends_phone_area_to_phone_country":
        return depends_phone_area_to_phone_country;
    case "depends_phone_to_phone_area":
        return depends_phone_to_phone_area;
    case "depends_phone_to_phone_country":
        return depends_phone_to_phone_country;
    case "depends_date_h_to_date_t":
        return depends_date_h_to_date_t;
    case "depending_trick_remove_leading_zero":
        return depending_trick_remove_leading_zero;
    default:
        console.error("wrong dependant_fn_name specified: " + name);
        alert("wrong dependant_fn_name specified: " + name);
        return null;
    }

}
function is_sip(str){
    return "sip" == str;
}
function suspected_sip_number(str){
    return sipRe.test(str);
}


function validation_area(errors, username, translations) {

    var str ="<ul>"
    for (var i = 0; i<errors.length; i++){
        e = errors[i];
        str+= "<li>";
        console.debug("Got: " + e.type);
        if (e.type in translations){
            str+= translations[e.type];
        } else {
            str+= "Unexpected error of type: " + e.type;
        }
        str+= "</li>";
    }
    str+="</ul>";
    console.debug("created errors: \n" + str);
    return str;
}


var editor = null;
var select_lang_defaults = null;

var log_date = function(str){
    console.debug("" + new Date() + " : " + str);
}
    
var assert_jq_size_1 = function(jq){
    if (jq.length!=1)
        new AssertionFailed_JqSizeDiffersOne();
}
        
        
        
var fill_in_calendar_popup = function(translations){
    /* Calendar from:
    http://www.mattkruse.com/javascript/calendarpopup/index.html
    */
    date_popup = new CalendarPopup("cal_popup_div_id");
    date_popup.setMonthNames(
        translations['month.01'],translations['month.02'],translations['month.03'],
        translations['month.04'],translations['month.05'],translations['month.06'],
        translations['month.07'],translations['month.08'],translations['month.09'],
        translations['month.10'],translations['month.11'],translations['month.12']);
    date_popup.setDayHeaders(
        translations['day.sunday.short'], translations['day.monday.short'], translations['day.tuesday.short'],
        translations['day.wednesday.short'], translations['day.thursday.short'], translations['day.friday.short'],
        translations['day.saturday.short']);
    date_popup.setTodayText(translations['day.today']);
    date_popup.setWeekStartDay(1);
    date_popup.setReturnFunction("date_selected_by_popup");
}

var myTip = function(text){
    return Tip(text, BALLOON, true, ABOVE, true, OFFSETX, -17, FADEIN, 600, FADEOUT, 600, PADDING, 8, DURATION, 5000);
}