/*------------------------------------------------------------------------
 * set_cookie(name, value, days)
 * 
 * Set a cookie with the name and value passed as the first two arguments, 
 * set to expire in the number of days specified in the third argument.
 *------------------------------------------------------------------------*/

function set_cookie(name, value, days) {
  var expires;

  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days*24*60*60*1000));
    expires = "; expires=" + date.toGMTString();
  }
  else 
    expires = "";

  document.cookie = name + "=" + value + expires + "; path=/";
}


/*------------------------------------------------------------------------
 * get_cookie(name)
 * 
 * Returns the value of the cookie identified by the name argument.
 *------------------------------------------------------------------------*/

function get_cookie(name) {
  var namestr  = name + "=";
  var cookbits = document.cookie.split(';');
  var n;

  for(n = 0; n < cookbits.length; n++) {
    var c = cookbits[n];

    /* remove leading whitespace */
    while (c.charAt(0) == ' ') 
      c = c.substring(1, c.length);

    /* if the name start this cookie fragment, return the value */
    if (c.indexOf(namestr) == 0) 
      return c.substring(namestr.length, c.length);
  }
  return null;
}

/*------------------------------------------------------------------------
 * functions to handle multiple handler for onload and onunload events.
 *------------------------------------------------------------------------*/

var onload_functions   = new Array();
var onunload_functions = new Array();

function page_load() {
    for(var i = 0; i < onload_functions.length; i++) {
        try { eval(onload_functions[i]); }
        catch(err) { }
    }
}

function page_unload() {
    for(var i = 0; i < onunload_functions.length; i++)
        eval(onunload_functions[i]);
}

function page_onload(func) {
    onload_functions.push(func);
}

function page_onunload(func) {
    onunload_functions.push(func);
}
/* onChange handler called when user selects a registration period for a domain */

function select_product(select_node, domain_id) {
    var select_item  = select_node.selectedIndex;
    if (select_item == 0) {
        /* first item in list is -- Select Registration Period -- */
        document.getElementById(domain_id + '_product_price').innerHTML = '';
        document.getElementById('total_price').innerHTML = '';
        return;
    }

    var product_item   = select_node.options[select_item];
    var product_price  = product_item.text.match(/([\d\.]+)\s*$/);
    document.getElementById(domain_id + '_product_price').innerHTML = 
         product_price ? '&pound;' + product_price[0] : 'FREE';

    total_price();
}

/* onChange handler called when user selects a package for a domain */

function select_package(select_node, domain_id) {
    var select_item  = select_node.selectedIndex;
    if (select_item == 0) {
        /* first item in list is -- Select Package -- */
        document.getElementById(domain_id + '_package_price').innerHTML = '';
        document.getElementById('total_price').innerHTML = '';
        return;
    }
        
    var package_item  = select_node.options[select_item];
    var package_price = package_item.text.match(/([\d\.]+)\s*$/);
    document.getElementById(domain_id + '_package_price').innerHTML = 
         package_price ? '&pound;' + package_price[0] : 'FREE';
    
    var package_code = package_item.value.replace(/\W+/g, '_');
    var source_node  = document.getElementById(package_code + '_pkg_info_def');
    var target_node  = document.getElementById(domain_id + '_pkg_info');
    target_node.className = 'pkg_info';
    target_node.innerHTML = source_node.innerHTML;

    source_node  = document.getElementById(package_code + '_pkg_opt_def');
    target_node  = document.getElementById(domain_id + '_options');

    var source_code = source_node.innerHTML;
    source_code = source_code.replace(/\[domain\]/g, domain_id);
    target_node.innerHTML = source_code;
    
//    source_code = source_code.replace(/>/g, '&gt;').replace(/</g, '&lt;');
//    document.getElementById('debug_output').innerHTML = source_code;
//    alert(source_code); 

    total_price();
}

function check_option(check_node, option_id, domain_id) {
    var price = check_node.value;
    document.getElementById(option_id + '_price').innerHTML = 
         check_node.checked ? '&pound;' + check_node.value : '';
}

/* function called by above onChange handlers to recalculate total price  */
 
function total_price() {
    var total_price = 0;
    var dbg = '';
    
    for (var n in domains) {
        var domain_name = domains[n];
        var domain_id   = domain_name.replace(/\W+/g, '_');
        var prod_price  = document.getElementById(domain_id + '_product_price').innerHTML.match(/([\d\.]+)\s*$/);
        var pack_price  = document.getElementById(domain_id + '_package_price').innerHTML.match(/([\d\.]+)\s*$/);
        prod_price = prod_price ? pounds2pence(prod_price[0]) : 0;
        pack_price = pack_price ? pounds2pence(pack_price[0]) : 0;
        total_price += prod_price + pack_price;
    }
    
    for (var n = 0; n < basket_size; n++) {
        var item_price = document.getElementById('basket_' + n + '_price').innerHTML.match(/([\d\.]+)\s*$/);
        item_price = item_price ? pounds2pence(item_price[0]) : 0;
        total_price += item_price;
    }

    /* update total price element */
    document.getElementById('total_price').innerHTML = 
         '&pound;' + pence2pounds(total_price);
    
    /* make sure the correct message is displayed */
    document.getElementById('sequence').className = 'sequence';
}

function pounds2pence(pounds) {
    return Math.round(parseFloat(pounds) * 100);
}

function pence2pounds(pence) {
    var pounds = Math.floor(pence / 100);
    pence = pence % 100;
    if (pence == 0)
        pence = '00';
    else if (pence < 10)
        pence = '0' + pence;    
    return pounds + '.' + pence;
}
function toggle_info(info_node_id) {
    return toggle_hidden(info_node_id, 'info');
    
    var info_node = document.getElementById(info_node_id);
    if (info_node) {
        info_node.className = 
            (info_node.className == 'hidden info')
                ? 'info' : 'hidden info';
        return false;
    }
}

function toggle_pkginfo(node_id) {
    return toggle_hidden(node_id, 'pkginfo');
}

function toggle_hidden(node_id, classname) {
    var node = document.getElementById(node_id);
    if (node) {
        var hidden = 'hidden ' + classname;
        node.className = (node.className == hidden) ? classname : hidden;
  //      alert('set to ' + node.className);
        return false;
    }
}

function enable_selected_next() {
    var next_node = document.getElementById('selected_next');
    if (next_node) {
        next_node.className = '';
    }
}

function submit_form(form_name) {
    document.forms[form_name].submit();
    return false;
}

function toggle_pkgconf_id(node_id) {
    return toggle_pkgconf( document.getElementById(node_id) );
}

function toggle_pkgconf(node) {
    if (node) {
        node.className = 
            (node.className == 'compact pkgconf')
                ? 'pkgconf' : 'compact pkgconf';
        return false;
    }
}

function open_close(node) {
    if (node) {
        node.className = 
            ( node.className.match(/^closed /)
            ? node.className.replace(/^closed /, '') 
            : 'closed ' + node.className );

        node.className = 
            ( node.className.match('closed warm') 
            ? node.className + ' wc'
            : node.className.replace(/ wc$/, '') );

//        alert('set name to ' + node.className);
        return false;
    }
}


function init_user_type() {
    var node = document.getElementById('usertype_select');
    if (node && node.selectedIndex) {
        select_user_type(node);
    }
}

function select_user_type(select_node) {
    var select_item  = select_node.selectedIndex;

    var select_value = select_item 
        ? select_node.options[select_item].value
        : '';

    switch(select_value) {
      case 'LTD':
      case 'PLC':
      case 'LLP':
      case 'IP':
      case 'SCH':
        show_optfield('company_number_display');
        hide_optfield('whois_opt_out_display');
        show_optfield('vat_number_display');
        break;
      case 'IND':
      case 'FIND':
        hide_optfield('company_number_display');
        hide_optfield('vat_number_display');
        show_optfield('whois_opt_out_display');
        break;
      default:
        hide_optfield('company_number_display');
        hide_optfield('whois_opt_out_display');
        show_optfield('vat_number_display');
    }
}

function show_optfield(node_id) {
    var node = document.getElementById(node_id);
    if (node) {
        node.className = 'optional field';
        return false;
    }
}

function hide_optfield(node_id) {
    var node = document.getElementById(node_id);
    if (node) {
        node.className = 'hidden optional field';
        return false;
    }
}
/*------------------------------------------------------------------------
 * create_request()
 * 
 * Create an XML HTTP Request object.
 *------------------------------------------------------------------------*/

function create_request() {
    var req;

    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
        req = false;
    }

    return req;
}


/*------------------------------------------------------------------------
 * request_HTML(url)
 * 
 * Fetch an HTML document.
 *------------------------------------------------------------------------*/

var http = create_request();

function request_HTML(url, handler, failure) {
    http.open('GET', url, true);
    http.onreadystatechange = function () {
        if (http.readyState == 4) {
            if (http.status == 200)
                handler(http.responseText);
            else if (failure)
                failure(http);
        }
    };
    http.send(null);
}


/*------------------------------------------------------------------------
 * request_XML(url)
 * 
 * Fetch an XML document.
 *------------------------------------------------------------------------*/

function request_XML(url, handler, failure) {
    http.open('GET', url, true);
    http.onreadystatechange = function () {
        if (http.readyState == 4) {
            if (http.status == 200)
                handler(http.responseXML.documentElement);
            else if (failure)
                failure(http);
        }
    };
    http.send(null);
}


/*------------------------------------------------------------------------
 * progressive_update(node_id, url)
 * 
 * Replace the content of an identified node with the text returned from  
 * an asynchronous HTTP request.
 *------------------------------------------------------------------------*/

function progressive_update(node_id, url) {
    var node = document.getElementById(node_id);
    if (node) {
        request_HTML(url, function(html) {
            node.innerHTML = html;
        });
    }
}

var update_count  = 12;        // maximum number of updates until we timeout
var update_delay  = 4 * 1000;  // 3 second delay between updates

function domain_search_update(node_id, url, ticket, repeat_id) {
    var node = document.getElementById(node_id);
    
    if (update_count-- > 0) {
        /* make request with callback function */
        request_HTML(url + '?ajax=1&ticket=' + ticket, function(html) {
            /* update target node content with HTML text returned */
            node.innerHTML = html;
            /* look for an element identified by repeat_id to indicate we need to keep going */
            if (repeat_id && document.getElementById(repeat_id)) {
                window.setTimeout(
                    function () {
                        domain_search_update(node_id, url, ticket, repeat_id);
                    },
                    update_delay
                );
            }
        });
    }
    else {
        var searching = document.getElementById('searching');
        searching.className = 'error';
        searching.innerHTML = '<div id="progress">Timeout</div>'
                            + '<div id="message">'
                            + '  <h3 class="title">Domain Search Timed Out</h3>'
                            + '  <p>The domain name search timed out.  Please try again.</p>'
                            + '</div>';
    }
}




window.onload   = page_load;
window.onunload = page_unload;


// page_onload('todaily()');
// window.setInterval(todaily, 1 * 60 * 1000);
