/*------------------------------------------------------------------------
 * 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;
}


var weekdaily = new Array(7);
weekdaily[0] = "Sundaily"
weekdaily[1] = "Mondaily"
weekdaily[2] = "Tuesdaily"
weekdaily[3] = "Wednesdaily"
weekdaily[4] = "Thursdaily"
weekdaily[5] = "Fridaily"
weekdaily[6] = "Saturdaily"

var month = new Array(12);
month[0] = "Jan"
month[1] = "Feb"
month[2] = "March"
month[3] = "April"
month[4] = "May"
month[5] = "June"
month[6] = "July"
month[7] = "Aug"
month[8] = "Sep"
month[9] = "Oct"
month[10] = "Nov"
month[11] = "Dec"


function todaily() {
    var date = new Date();
    document.getElementById("day").innerHTML = weekdaily[date.getDay()];

    var day   = date.getDate();
    var mon   = month[date.getMonth()];
    var hours = date.getHours() % 12;
    var mins  = Math.floor(date.getMinutes() / 5) * 5;
    var ordinal;

    if (day == 1 || day == 21 || day == 31) {
        ordinal = 'st';
    }
    else if (day == 2 || day == 22) {
        ordinal = 'nd';
    }
    else if (day == 3 || day == 23) {
        ordinal = 'rd';
    }
    else {
        ordinal = 'th';
    }
    ordinal = '<span class="ordinal">' + ordinal + '</span>';
    document.getElementById("date").innerHTML = day + ordinal + ' ' + mon + ' ' + date.getFullYear();

    if (hours < 10)
        hours = '0' + hours;
    if (mins < 10)
        mins = '0' + mins; 

    var clock = 'images' + '/clock/time/' + hours + mins + '.gif'
//    alert('setting clock image to ' + clock);
    document.getElementById("time").src = clock;
}
/*------------------------------------------------------------------------
 * 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++)
        eval(onload_functions[i]);
}

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 ? '&#163;' + 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 ? '&#163;' + 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 ? '&#163;' + 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 = 
         '&#163;' + 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) {
    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 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;
}

/*------------------------------------------------------------------------
 * 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>';
    }
}

/*------------------------------------------------------------------------
 * load_style()
 * 
 * Initialises the stylesheet based on any cookie currently set.
 *------------------------------------------------------------------------*/


var style = "Daily";

function load_style() {
    if (style = get_cookie("stylesheet"))
        set_style(style);
}

/*------------------------------------------------------------------------
 * save_style()
 * 
 * Saves the stylesheet name back to a cookie
 *------------------------------------------------------------------------*/

function save_style() { 
    var style;
    if (style = get_style())
        set_cookie("stylesheet", style, 365);
}

/*------------------------------------------------------------------------
 * get_style()
 * 
 * Returns the title of the current active stylesheet.
 *------------------------------------------------------------------------*/

function get_style() {
  var elems = document.getElementsByTagName("link");
  var n, elem, title;

  for (n = 0; (elem = elems[n]); n++) {
     if (elem.getAttribute("rel").indexOf("style") != -1 
     && (title = elem.getAttribute("title"))
     && !elem.disabled)
       return title;
  }
  return null;
}

/*------------------------------------------------------------------------
 * set_style(title)
 * 
 * Set the active stylesheet by enabling the <link rel="style" ...> 
 * element that has a title attribute matching the title argument,
 * and disabling all others.
 *------------------------------------------------------------------------*/

function set_style(title) {
  var elems = document.getElementsByTagName("link");
  var n, elem, tattr;

  for (n = 0; n < elems.length; n++) {
    elem = elems[n];

    if (elem.getAttribute("rel").indexOf("style") != -1 
    && (tattr = elem.getAttribute("title"))) {
      elem.disabled = true;
      if (tattr == title) {
        elem.disabled = false;
        style = title;
        todaily();
      }
    }
  }
  return false;
}




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


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