// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults




// The following is for testing only...


// Functions to automatically enter competitor name when user enters competitor url (when adding a new one) - 'NC' stands for new competitor
var nc_name_changed = false; // if the user alters the Name manually, this is set to true, unless the Name is blank
var nmc_name_changed = false; // separate variable for main competitor (since  both in window at same time)
function NC_URLChanged(main) {
  
  if ($('new_comp_title').value == '') {
    nc_name_changed = false; // reset if changed from previous submission
  }
    
  if ((main == '' && nc_name_changed == false) || (main != '' && nmc_name_changed == false)) {
    if (main == '') {
        var title = $('new_comp_link').value;
    } else {
        var title = $('new_main_comp_link').value;
    }
    title = title.replace(/^(?:https?:\/\/)?(?:www\.)?/i, ''); // gets rid of http://www (s and www are optional)
    
    if (title.match(/\.co\.uk/) || title.match(/\.(?:(?:au)|(?:nz))/i)) { // .co.uk and .*.au or .*.nz have different patterns than other domain suffixes
        title = title.replace(/\.[a-z]+\.[a-z]+(?:\/.*)?$/i, ''); // gets rid of any domain suffix and trailing paths
    } else {
        title = title.replace(/\.[a-z]+(?:\/.*)?$/i, ''); // gets rid of any domain suffix and trailing paths
    }
    
    // reverse the order of the name and put in title case (docs.google becomes Google Docs)
    var title_to_print = title.split('.');
    for (i=0;i<title_to_print.length;i++) {
	   title_to_print[i] = (title_to_print[i].substring(0,1)).toUpperCase() + title_to_print[i].substring(1);
	   if (title_to_print[i] == '') {
	       title_to_print.splice(i,1); // remove a blank element so it doesn't result in an extra space
	   }
    }
    if (title_to_print.length > 1) {
        title_to_print = title_to_print.reverse();
        title_to_print = title_to_print.join(' ');
    }
    
    if (main == '') {
        $('new_comp_title').value = title_to_print;
    } else {
        $('new_main_comp_title').value = title_to_print;
    }
  }
}

// changes the global variable nc_name_changed, so the name is not updated if it's been changed manually (but not cleared)
function NC_NameChanged(main) {
  if (main == '') {
    if ($('new_comp_title').value == '') {
        nc_name_changed = false;
    } else {
        nc_name_changed = true;
    }
  } else {
    if ($('new_main_comp_title').value == '') {
        nmc_name_changed = false;
    } else {
        nmc_name_changed = true;
    }
  }
}
