/**
* the count of other cities @ 1 unit each
*/
var other_city_total_tmp=0;
/**
* array for the other cities not @ 1 unit each
*/
var other_city_units = []; 
var other_city_units_operations = []; 
/**
* set the default values in units for the sixth other cities to 0
*/
for (i=1; i<=6; i++) {
  other_city_units[i] = 0;
  other_city_units_operations[i] = '0';
}

/**
* calculates the units score for the default cities from the list
*/
function calculate(chk) {
  //splits the value of the checkbox
  var vals = chk.value.split(' : ');
  var city  = vals[0]; //get city name
  var units = parseInt(vals[1]); //get units for the city
  //get the id of the added/modified other city
  var id    = parseInt(chk.id.replace(/^ws_other_city/, ''));
  var total = document.getElementById('units_total'); //get the total of the Units score for all of the cities
  var other_city_price = document.getElementById('other_city_unit' + id);
  
  //if checkbox has no value do nothing
  if (chk.value != '') {
    if (chk.checked) {
      total.value = parseInt(total.value) + units;
      if (chk.id.match(/^ws_other_city/) && other_city_price.value == '') {
        other_city_price.value = '1';
      }
    } else {
      if (parseInt(total.value) > 0) {
        total.value = parseInt(total.value) - units;
      }

    }
  }

  //assign a new value for the Units score placed at the top of the page
  document.getElementById('units').value = total.value;
}

/**
* calculates how many other cities has value 1 unit
*/
function other_city_total_func(txt) {
  add_other_cities_value = txt.value;
  //set the default value to 0 of the 'total other cities @ 1 unit each' input textbox
  if (txt.value == '') {
    add_other_cities_value = 0;
  }

  //get the total of the units for all of the cities from the input textbox at the page bottom
  var units = document.getElementById('units_total');
  //calculates the new total
  units.value = parseInt(units.value) + parseInt(add_other_cities_value) - other_city_total_tmp;
  //assign a new value for the Units score placed at the top of the page
  document.getElementById('units').value = units.value;
  //assign a new value for the global variable which saves the units score for other cities @ 1 unit each
  other_city_total_tmp=parseInt(add_other_cities_value);
}

/**
* calculates how many other cities has different than 1 unit value
*/
function calculate_other_cities(txt_label) {
  txt = document.getElementById(txt_label);
  //get global value of all units from the input textbox at the page bottom
  var total     = document.getElementById('units_total');
  //get the id of the added/modified other city
  var id        = parseInt(txt.id.replace(/^other_city_unit/, ''));
  //get the checkbox of the selected above other city 
  var chk       = document.getElementById('ws_other_city' + id);
  //get the city name of the selected above other city 
  var city      = document.getElementById('other_city_name' + id);
  //get the 'Units' input textbox at the page top
  var units_top = document.getElementById('units');
  //set the default value to 0 of the Unit input textbox for the other cities
  if (txt.value == '') {
    txt.value = '1';
  }

  //calculate the new value of the units tatal
  total.value = parseInt(total.value) + parseInt(txt.value) - parseInt(other_city_units[id]);
  //assign a new 'units' value for the selected other city to the global array with 'units' values of the other cities
  other_city_units[id] = parseInt(txt.value);

  //assign a new value to the selected other city checkbox
  chk.value = city.value + ' : ' + txt.value;
  //assign a new value for the Units score placed at the top of the page
  units_top.value = total.value;
}

/**
* calculates the other cities input textboxes content.
*/
function calculateAllOtherCities(num, init) {
  //get global value of all units from the input textbox at the page bottom
  var total     = document.getElementById('units_total');
  //get the 'Units' input textbox at the page top
  var units_top = document.getElementById('units');
  //get the 'Other City Units Total' input textbox
  var subtotal  = document.getElementById('other_city_total');

  //get the checkbox of the selected other city 
  var chk   = document.getElementById('ws_other_city' + num);
  //get the city name of the selected other city 
  var city  = document.getElementById('other_city_name' + num);
  //get the city units of the selected other city 
  var units = document.getElementById('other_city_unit' + num);


  if (city.value && init && init != 'chk') {
    checkTheCheckBox(num);
  }

  //if units input is empty, assign as value '1'
  if (init =='city' && city.value && !units.value && chk.checked) {
    units.value = 1;
  } else if (init !='units' && !units.value && chk.checked) {
    units.value = 1;
  }

  var units_value = 0;
  if (units.value) {
    units_value = parseInt(units.value);
  }

  if (total.value == '') {
    units_top.value = 0;
    total.value     = 0;
  }

  //assign a new value to the selected other city checkbox
  chk.value = city.value + ' : ' + units.value;

  //if the checkbox is checked
  if (chk.checked) {
    //if no operation was made
    if (other_city_units_operations[parseInt(num)] == '0') {

      //assign that an operation was made
      other_city_units_operations[parseInt(num)] = '1';
      //calculate the subotal of other cities
      subtotal.value = parseInt(subtotal.value) + units_value;
      //calculate the new value of the units total
      total.value = parseInt(total.value) + units_value;
      //assign a new value for the Units score placed at the top of the page
      units_top.value = total.value;
      //assign a new 'units' value for the selected other city to the global array with 'units' values of the other cities
      other_city_units[parseInt(num)] = units_value;

    } else if (other_city_units_operations[parseInt(num)] == '1') {

      //if an operation already had been made
      //if units input is not empty and it's differnet than stored value for units
      if (units.value && other_city_units[parseInt(num)] != units.value) {

        //assign that no operation was made
        other_city_units_operations[parseInt(num)] = '1';
        //calculate the subotal of other cities
        subtotal.value = parseInt(subtotal.value) + units_value - parseInt(other_city_units[parseInt(num)]);
        //calculate the new value of the units total
        total.value = parseInt(total.value) + units_value - parseInt(other_city_units[parseInt(num)]);
        //assign a new value for the Units score placed at the top of the page
        units_top.value = total.value;
        //assign a new 'units' value for the selected other city to the global array with 'units' values of the other cities
        other_city_units[parseInt(num)] = units_value;
      }

    }

    //other_city_units_operations[parseInt(num)] = '1';
  } else if (!chk.checked) {

    if (other_city_units[parseInt(num)]){
      other_city_units_operations[parseInt(num)] = '0';
      //caluclate the subtotal
      subtotal.value = parseInt(subtotal.value) - parseInt(other_city_units[parseInt(num)]);
      //calculate the new value of the units total
      total.value = parseInt(total.value) - parseInt(other_city_units[parseInt(num)]);
      //assign a new value for the Units score placed at the top of the page
      units_top.value = total.value;
      //assign a new 'units' value for the selected other city to the global array with 'units' values of the other cities
      other_city_units[parseInt(num)] = units_value;
    }
  }

  if (init == 'chk' && !chk.checked) {
    city.value  = '';
    units.value = '';
    other_city_units[parseInt(num)] = 0;
  }


}

/**
* check the checkbox
*/
function checkTheCheckBox(num) {
  var chk = document.getElementById('ws_other_city' + num);
  if (!chk.checked) {
    chk.checked = true;
  }

}

/**
* sets default value for the units fields
*/
function setDefaultUnitsValue(chk, txt) {
  //get global value of all units from the input textbox at the page bottom
  var total     = document.getElementById('units_total');
  //get the 'Units' input textbox at the page top
  var units_top = document.getElementById('units');
  txt_obj = document.getElementById(txt);
  //get the id of the added/modified other city
  var id        = parseInt(txt_obj.id.replace(/^other_city_unit/, ''));
  chk_obj = document.getElementById(chk);
  if (!chk_obj.checked) {
    chk_obj.checked = true;
    if (txt_obj.value == '') {
      txt_obj.value = '1';
    }
    
    total.value = parseInt(total.value) + parseInt(txt_obj.value);
    units_top.value = parseInt(total.value) + parseInt(txt_obj.value);
    other_city_units[id] = parseInt(txt_obj.value);
  }

  //get the city name of the selected above other city 
  var city      = document.getElementById('other_city_name' + id);
  //assign a new value to the selected other city checkbox
  chk_obj.value = city.value + ' : ' + txt_obj.value;

}

//global vars containing the field names
var err_index = [];
var required_fields = [];
var date_fields     = [];
var required_dates  = [];
var date_format     = 'MM/DD/YY';

/**
* validation of the form
*/
function validate() {
  if (document.getElementById('talentestimate')) {
    required_fields = ['agency', 'requestedby', 'telephone', 'advertiser', 'spotid'];
    date_fields     = ['wildspotstart', 'wildspotend', 'networkstart', 'networkend', 'daterequested', 'datedue'];
    required_dates  = ['daterequested', 'datedue'];
    //init the error array
    err_index = ['agency', 'requestedby', 'telephone', 'email', 'daterequested', 'datedue', 'advertiser', 'spotid', 'wildspotstart', 'wildspotend', 'networkstart', 'networkend', 'other_city_name1', 'other_city_unit1', 'other_city_name2', 'other_city_unit2', 'other_city_name3', 'other_city_unit3', 'other_city_name4', 'other_city_unit4', 'other_city_name5', 'other_city_unit5', 'other_city_name6', 'other_city_unit6'];
  }

  if (document.getElementById('tv_talentestimate')) {
    required_fields = ['agency', 'requestedby', 'telephone', 'daterequested', 'datedue', 'advertiser', 'spotid'];
    date_fields     = ['wildspotstart', 'wildspotend', 'cablestart', 'cableend','programstart','programend', 'daterequested', 'datedue'];
    required_dates  = ['daterequested', 'datedue'];
    //init the error array
    err_index = ['agency', 'requestedby', 'telephone', 'email', 'daterequested', 'datedue', 'advertiser', 'spotid', 'wildspotstart', 'wildspotend', 'cablestart', 'cableend','programstart','programend', 'other_city_name1', 'other_city_unit1', 'other_city_name2', 'other_city_unit2', 'other_city_name3', 'other_city_unit3', 'other_city_name4', 'other_city_unit4', 'other_city_name5', 'other_city_unit5', 'other_city_name6', 'other_city_unit6'];
  }

  if (document.getElementById('nb_industrial')) {
    required_fields = ['prod_company', 'requestedby', 'telephone', 'fax','email', 'title_project', 'intended_audience', 'shootrecord_location', 'casting_agent', 'casting_agent_ph'];
    date_fields     = ['daterequested', 'shootrecord_date'];
    required_dates  = ['daterequested', 'shootrecord_date'];
    //init the error array
    err_index = ['prod_company', 'requestedby', 'telephone', 'fax','email', 'daterequested', 'title_project', 'intended_audience', 'shootrecord_date', 'shootrecord_location', 'casting_agent', 'casting_agent_ph'];
  }



  return do_validate();
}



/**
* validation of the form
*/
function do_validate() {
  var valid  = true;
  var errors = [];
/*
  var required_fields = ['agency', 'requestedby', 'telephone', 'daterequested', 'datedue', 'advertiser', 'spotid'];
  var date_fields     = ['wildspotstart', 'wildspotend', 'networkstart', 'networkend', 'daterequested', 'datedue'];
  var required_dates  = ['daterequested', 'datedue'];
  var date_format     = 'MMDDYY';
*/
  //check for valid email
  var email = trim(document.getElementById('email').value);
  var label = document.getElementById('lbl_email');
  regex = /^[A-Za-z][-\.A-Za-z0-9_]+@[A-Za-z][-A-Za-z0-9_]+(\.[A-Za-z][-A-Za-z0-9_]+)+$/;
  var class_name = '';
  if (!email.match(regex, email)) {
    valid = false;
    class_name = 'error';
    errors['email'] = 'Please insert valid "Email"';
  }
  if (label) {
    label.className = class_name;
    //remove the asterisks at the end
    label.innerHTML = label.innerHTML.replace(/\**$/, '');
    if (class_name == 'error') {
      label.innerHTML += '*';
    }
  }

  //check required fields
  for (i=0; i<required_fields.length ;i++ ) {
    field_id = required_fields[i];
    var field = document.getElementById(field_id);
    var label = document.getElementById('lbl_' + field_id);
    var class_name = '';
    if (!trim(field.value)) {
      valid = false;
      class_name = 'error';
      if (label) {
        errors[field_id] = 'Please insert "' + label.innerHTML.replace(/\**$/, '') + '"';
      }
    }
    if (label) {
      label.className = class_name;
      //remove the asterisks at the end
      label.innerHTML = label.innerHTML.replace(/\**$/, '');
      if (class_name == 'error') {
        label.innerHTML += '*';
      }
    }
  }

  //check date fields
  for (i=0; i<date_fields.length ;i++ ) {
    field_id = date_fields[i];
    var field = document.getElementById(field_id);
    var label = document.getElementById('lbl_' + field_id);
    var class_name = '';
    if (field.value != date_format && !valid_date(field.value)) {
      valid = false;
      class_name = 'error'
      errors[field_id] = 'Please insert valid "' + label.innerHTML.replace(/\**$/, '') + '"' +
                         '<br />Format date exactly as shown';
    }
    if (label) {
      label.className = class_name;
      //remove the asterisks at the end
      label.innerHTML = label.innerHTML.replace(/\**$/, '');
      if (class_name == 'error') {
        label.innerHTML += '*';
      }
    }
  }

  //check required date fields
  for (i=0; i<required_dates.length ;i++ ) {
    field_id = required_dates[i];
    var field = document.getElementById(field_id);
    var label = document.getElementById('lbl_' + field_id);
    var class_name = '';
    if (!trim(field.value) || field.value == date_format || !valid_date(field.value)) {
      valid = false;
      class_name = 'error'
      errors[field_id] = 'Please insert valid "' + label.innerHTML.replace(/\**$/, '') + '"' +
                         '<br />Format date exactly as shown';
    }
    if (label) {
      label.className = class_name;
      //remove the asterisks at the end
      label.innerHTML = label.innerHTML.replace(/\**$/, '');
      if (class_name == 'error') {
        label.innerHTML += '*';
      }
    }
  }

  //validate custom entered other cities
  if (!document.getElementById('nb_industrial')) {
    for (i=1; i<=6; i++) {
        var chk        = document.getElementById('ws_other_city' + i);
        var other_city = document.getElementById('other_city_name' + i);
        var other_city_unit = document.getElementById('other_city_unit' + i);
        var class_name = 'border';
        if (chk.checked && !trim(other_city.value)) {
            valid = false;
            class_name += ' error';
            errors['other_city_name' + i] = 'Please insert name of Additional City ' + i;
        }
        other_city.className = class_name;
        var class_name = 'border';
        if (chk.checked && !trim(other_city_unit.value)) {
            valid = false;
            class_name += ' error';
            errors['other_city_unit' + i] = 'Please insert units of Additional City ' + i;
        }
        other_city_unit.className = class_name;
    }
  }

  //display the errors
  var err = document.getElementById('errors');

  if (!valid) {
    //display the errors
    var err = document.getElementById('errors');
    var err_str = '';
    for (var idx in err_index) {
      var e = err_index[idx];
      if (errors[e]) {
        var lbl = document.getElementById('lbl_'+e);
        var title = 'Click to correct this error';
        if (lbl) {
          lbl_title = lbl.innerHTML.replace(/\**$/, '');
          title = 'Click to correct error in ' + lbl_title;
          title = title.replace(/ *<br ?\/?>\n*\ */, ' ');
        }
        err_str += '<li><a href="#" id="err_'+e+'" onclick="focusError(this); return false;" title="'+title+'">'+errors[e]+'</a></li>\n';
      }
    }
    err.style.display = 'block';
    err.innerHTML = '<ul>'+err_str+'</ul>';
    scroll(0,0);
    alert('There are errors. Please fill in all fields with a red asterisk.\nThe details are displayed at the top of the page.\nPlease click an error message to target and fix the error.');

  } else {
    err.style.display = 'none';
    //clear dates with default date format
    for (i=0; i<date_fields.length ;i++ ) {
      field_id = date_fields[i];
      var field = document.getElementById(field_id);
      if (field.value == date_format) {
        //clear the default format
        field.value = 'MM/DD/YY';
      }
    }

    return (confirm('Are you sure you want to submit this form?'));

  }

  return valid;
}
function focusError(err) {
  try { 
    eid = err.id.replace(/^err_/, '');
    document.getElementById(eid).focus();
  }
  catch (e) {}
}

/**
* Removes spaces from the beginning and the end ot the text. 
*/
function trim(text){
    // Removes spaces from the beginning of the text.
    var re = /^ /;
    while(re.test(text)){
        text = text.replace(re, "");
    }
    
    // Removes spaces from the end of the text.
    var re1 = / $/;
    while(re1.test(text)){
        text = text.replace(re1, "");
    }

    return text;
};

function removeLeadingZero(num) {
  num = parseInt(num.replace(/^0*/, ''));

  return num;
}
/**
* get fields value MM/DD/YYYY and splits it into three vars and 
*/
function valid_date(txt) {

  var vars = txt.split('/');

  //check for valid format MM/DD/YYYY
  if (vars.length != 3) {
    return false;
  }

  var month = removeLeadingZero(vars[0]);
  var day   = removeLeadingZero(vars[1]);
  var year  = parseInt('20' + vars[2]);


/*
  var month = (txt.substring(0,2));
  var day = (txt.substring(2,4));
  var year = ('20' + txt.substring(4,6));
*/


  if (txt.length != 8) {
      return false;
  }

  return isValidDate(month, day, year);
}

/**
* validates date
*/
function isValidDate(month, day, year) {
  //check if all the items have values
  if (!month || !day || !year) {
    return false;
  }

  //check the year
  if (year < 1000 || year > 9999) {
    return false;
  }
  //check if the year is leap
  var leap_year = false;
  if (year % 4 != 0) {
    leap_year = false;
  } else if (year % 400 == 0) {
    leap_year = true;
  } else if (year % 100 == 0) {
    leap_year = false;
  } else {
    leap_year = true;
  }

  //check the month
  if (month <= 0 || month > 12) {
    return false;
  }
  //get the max days for the month
  var max_days = 0;
  if((month == 4) || (month == 6) || (month == 9) || (month == 11)) {
    max_days = 30;
  } else if(month == 2) {
    //check for leap year
    max_days = leap_year ? 29 : 28;
  } else {
    max_days = 31;
  }

  //check the day
  if (day <= 0 || day > max_days) {
    return false;
  }

  return true;
}

/*Macromedia*/
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
