/* V A L I D A T E    F O R M */
function validateForm(validate) {
    var curr_field, fieldName, filterList, element, errno, tvalue, len;
    var missinginfo = '';
    var matchEmail =/email/i
    var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
    var matchField = /([a-zA-Z0-9]{1}[\w_]+[a-zA-Z0-9]{1})\[([\S]{0,})\]/i

    /*filters used*/
    var filter1 = /len/i //maximum length
    var filter2 = /numeric/i //numeric fields

    var checkList = validate.split(",");
    for( var z=0; z < checkList.length; z++ ) {
        //get the field name
        fieldName = checkList[z].replace(matchField,"$1");
        //get the field criterias
        curr_field = checkList[z].replace(matchField, "$2");
        element = document.getElementById(fieldName);
        
        //check if this field is the email field to use different filter
        if(matchEmail.test(fieldName)) {
            if( !filter.test(element.value) ) { errno = 3;  } else { errno = 0;  }
        } else {
            //check if field is blank
            if( element.value == '' ) {
                errno = 1;
            } else {
                filterList = curr_field.split(";");
                for( var f=0; f < filterList.length; f++ ) {
                    
                    tvalue = filterList[f].split("=");
                    if(filter1.test(filterList[f])) {//check field length
                        if(element.value.length > tvalue[1] ) { errno = 2; len=tvalue[1]; } else { errno = 0; }
                    } else if(filter2.test(filterList[f])){//check if field is numeric
                        if(!IsNumeric(element.value)) { errno = 4; } else { errno = 0; }
                    }
                }
            }
        }
        //clear underscores from field name
        fieldName = fieldName.replace(/[_' ']/g," ");

        //ERRORS messages type
        if(errno==0 || !errno){ //field is valid
            element.style.backgroundColor='#FFFFFF';
        }else if(errno==1) {//field is blank
            missinginfo += '\n - '+ capitalize(fieldName)+ ' is required';
            element.style.backgroundColor='#E3F0FF';
        }else if(errno==2) {//max characters permitted
            missinginfo += '\n - '+ capitalize(fieldName)+ ' Max. Characters permitted = '+len;
            element.style.backgroundColor='#E3F0FF';
        }else if(errno==3) {//invalid email
            missinginfo += '\n - '+ capitalize(fieldName)+ ' is not valid';
            element.style.backgroundColor='#E3F0FF';
        }else if(errno==4) {//numeric fields
            missinginfo += '\n - '+ capitalize(fieldName)+ ' is a numeric field';
            element.style.backgroundColor='#E3F0FF';
        }
    }
    if (missinginfo != '') {
        missinginfo = '_____________________________\n' + 'Please fill in correctly the following information:\n' +
        missinginfo + '\n_____________________________';
        alert(missinginfo);
        return false;
    } else {
        return true;
    }
    return false;
}

function ajax(fragment_url,element_id) {

    var element = document.getElementById(element_id);

    document.body.style.cursor = "progress";

    element.innerHTML = '<img src="/images/spinner.gif">';
    if (window.XMLHttpRequest) { //for all browers but IE
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) { //for IE
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.open("GET", fragment_url+ '&r='+Math.random());
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.body.style.cursor = "auto";
            element.innerHTML = (unescape(xmlhttp.responseText)).replace(/\+/gi," ");
        }
    }
    xmlhttp.send(null);
}

/*R E S I Z E   I F R A M E   H E I G H T*/
function autofitIframe(id){
    if (!window.opera && !document.mimeType && document.all && document.getElementById){
        parent.document.getElementById(id).style.height=this.document.body.offsetHeight+"px";
    }
    else if(document.getElementById) {
        parent.document.getElementById(id).style.height=this.document.body.scrollHeight+"px"
    }
}

/*C O N V E R T   F I R S T   L E T T E R   T O    U P P E R C A S E*/
function capitalize(str) {
  var arr=str.split("");
  arr[0]=arr[0].toUpperCase();
  var s=arr.join("");
  return s;
}

/*C H E C K   I F   A   F I E L D   I S   N U M E R I C*/
function IsNumeric(sText){
    var ValidChars = "0123456789.";
    var IsNumber=true;
    var Char;


    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
   return IsNumber;

}

/*T A B S    C O N T R O L*/
var dTab = 1;
function tabs(display,numTabs ){
    if(!numTabs){ numTabs = 6; }
    for( var i=1; i<=numTabs; i++ ){
        if( i != display) {
            if( document.getElementById('tbl'+i) ) {
                document.getElementById('tbl'+i).style.display='none';
                document.getElementById('tab'+i).className = 'tabs';
            }
        } else {
            document.getElementById('tab'+i).className = 'tabsSel';
        }
    }
    document.getElementById('tbl'+display).style.display='block';
    
}

/* P O P U L A T E   D R O P   D O W N*/
function popLoc(mod, value, selected){
    var url = '/index.php?action=popLoc&m='+ mod +'&id='+ value;
    
    if(selected){
        url = url + '&sel='+selected;
    }
    
    ajax(url ,'s_'+ mod);
    
    if( !selected && mod == 'country' ){
        document.getElementById('location').style.display='none';
    } else {
        document.getElementById('location').style.display='';
    }

}

/*D E L E T E   F A C I L I T Y*/
function deleteFacility(id,resortId){
    var cf = confirm('Are you sure you wish to delete this facility?');
    if( cf ) {
        ajax('/index.php?action=facility&m=delete&rId='+resortId+'&id='+ id,'facilityBox');
    } else {
        return false;
    }
}


/*A D D   F A C I L I T Y*/
function addFacility(resortId, user_id){
    var f = document.getElementById('facility');
    var dm = document.getElementById('distance_miles');
    var dkm = document.getElementById('distance_km');
    ajax('/index.php?action=facility&m=add&rId='+resortId+'&f='+f.value+'&dm='+dm.value+'&dkm='+dkm.value+'&user_id='+user_id,'facilityBox');
    dm.value = '';
    dkm.value = '';
}


/*D E L E T E   U N I T*/
function deleteUnit(id,resortId){
    var cf = confirm('Are you sure you wish to delete this Unit?');
    if( cf ) {
        ajax('/index.php?action=unitType&m=delete&rId='+resortId+'&id='+ id,'unitBox');
    } else {
        return false;
    }
}

/*A D D   U N I T*/
function addUnit(resortId){
    var u = document.getElementById('userId');
    var t = document.getElementById('unitType');
    var o = document.getElementById('occupancy');
    var w = document.getElementById('weekNo');
    var p = document.getElementById('price');
    var pt = document.getElementById('points');
    ajax('/index.php?action=unitType&m=add&u='+u.value+'&rId='+resortId+'&t='+t.value+'&o='+o.value+'&w='+w.value+'&p='+p.value+'&pt='+pt.value,'unitBox');
    u.value = '';
    p.value = '';
    pt.value = '';
}

/*E X E C U T E   S E A R C H */
function doSearch(){
    var searchBy = getRadioValue('by');
    var admin = document.getElementById('admin');
    var fields;

    if( searchBy == '0' ) {
        /*if(admin){
            if(validateForm('country[]')) { return true; } else { return false; }
        } else {
            if(validateForm('country[],location[]')) { return true;  } else { return false; };
        }*/
        if(validateForm('country[]')) { return true; } else { return false; }

    } else {
        if( validateForm('reference[]') ) {
            return true;
        } else {
            return false;
        }
    }
}

/*S H O W / H I D E   R E S O R T   I D*/
function showResortId(display){
    if(display) {
        document.getElementById('resortId').style.display='';
        document.getElementById('reference').value = '';
        document.getElementById('loc').style.display='none';
    } else {
        document.getElementById('resortId').style.display='none';
        document.getElementById('loc').style.display='';
    }
}

/*G E T   R A D I O   B O X   V A L U E*/
function getRadioValue(radioN){
    for(i=0;i<document.search[radioN].length;i++){
        if (document.search[radioN][i].checked == true)
            return document.search[radioN][i].value;
    }

}


/* R E S O R T S   I M  PO R T    F O R M*/
function dOptions(value){
    
    if(value == 'rci'){
        document.getElementById('rci').style.display='';
    } else {
        document.getElementById('rci').style.display='none';
    }
}


/*P O P U L A T E   W E E K S*/
function popWeeks(week){
    if( week == '' )
        return false;
    
    document.getElementById('week').style.display = 'inline';
    var url = '/index.php?action=popWeeks&w=';
    ajax(url + week,'week');

}

function importResort(){
    var resort = document.getElementById('import');
    window.location.href='/index.php?action=importResort&r='+ resort.value;
    resort.value = '';
}

function weekDetails(type){
    if( type >= 9 ) {
        document.getElementById('week_details').style.display = 'none';
        document.getElementById('points_details').style.display = '';
        
        if( type == 9 ){
            document.getElementById('season').innerHTML = 'Number of Points:';
        } else {
            document.getElementById('season').innerHTML = 'Season:';
        }
        
    } else {
        document.getElementById('week_details').style.display = '';
        document.getElementById('points_details').style.display = 'none';
    }
}
