/**
 * (c) 2007 Right Way Gate Inc, All Rights Reserved
 */

// UpdateInclude
// sends an update signal to an include indicating that it
// needs to be updated
//
// include_id  : id number of the include
// ajax_url    : URL to the ajax reciever
function UpdateInclude(include_id, ajax_url) {

	this.include_id					= include_id;
	this.ajax_url					= ajax_url;
	
	this.ajax 						= new AjaxConnection();
	this.ajax.base_tag 				= 'LiveCustomerSender';

	var t 							= this;
	this.ajax.processer 			= function(root_node, aj) { 
		t.finished(root_node); 
		t.doneCallback();
	} ;

	this.ajax.errorHandler			= function(error_msg, aj) {
		t.error(error_msg);
		t.doneCallback();
	};

	this.ajax.doneCallback			= function() { };

	// additional properties to pass to the 
	// finished function
	this.ajax.dom_version_cell		= document.getElementById('ver_' + include_id);
	this.ajax.dom_status_cell		= document.getElementById('done_' + include_id);
	
}

// Run the ajax connection
UpdateInclude.prototype.run = function() {
	this.ajax.Connect(this.ajax_url + '?include_id=' + escape(this.include_id) + '&r='  + escape(Math.random() * Date.parse(new Date())));	
}

// ajax loading has finished
// root_node    : XML Root Node
UpdateInclude.prototype.finished = function(root_node) {

	var url		= '';
	var pid		= 0;
	var inc_tit	= '';
	var inc_id	= 0;
	var version = '';

    for (var key = 0; key < root_node.childNodes.length; key++) {
		var node = root_node.childNodes[key];

		switch (node.nodeName) {

			case 'Version':
				murderChildren(this.ajax.dom_version_cell);
				version = node.firstChild.nodeValue;
				this.ajax.dom_version_cell.appendChild(
					document.createTextNode(node.firstChild.nodeValue)
				);
			break;

			case 'ProductURL':
				url		= node.firstChild.nodeValue;
			break;
			case 'ProductID':
				pid		= node.firstChild.nodeValue;
			break;
			case 'IncludeTitle':
				inc_tit = node.firstChild.nodeValue;
			break;
			case 'IncludeID':
				inc_id	= node.firstChild.nodeValue;
			break;

			case 'Error':
			case 'RemoteError':
			case 'LocalError':
				murderChildren(this.ajax.dom_status_cell);

				var code = node.attributes.getNamedItem('errorCode');

				if (code) {
					code 		= code.value;
				} else {
					code		= -1;
				}

				var msg  	= '';
				var title 	= '';
				var orig	= '';


			    for (var x = 0; x < node.childNodes.length; x++) {
					switch(node.childNodes[x].nodeName) {
						case 'OriginalMessage':
							orig = node.childNodes[x].firstChild.nodeValue;
						break;
						case 'Title':
							title = node.childNodes[x].firstChild.nodeValue;
						break;
						case 'Message':
							msg   = node.childNodes[x].firstChild.nodeValue;
						break;
						case '#cdata':
							msg    = node.nodeValue;
						break;

					}
				}

				displayUpdateError(code, title, msg, orig, pid, url, inc_id, inc_tit);

				this.ajax.dom_status_cell.appendChild(document.createTextNode(msg));
				
	
			break;
			case 'Okay':
				murderChildren(this.ajax.dom_status_cell);
				if (version.toLowerCase() == 'email') {
					this.ajax.dom_status_cell.appendChild(document.createTextNode(
						'Email Queued'
					));
				} else {
					this.ajax.dom_status_cell.appendChild(createImageDom('icon_check.gif', 'Done'));
				}
			break;
		}
	}
}

// there has been an error *snif*
// error_msg	: String error message
UpdateInclude.prototype.error = function(error_msg) {
	murderChildren(this.ajax.dom_version_cell);
	murderChildren(this.ajax.dom_status_cell);

	this.ajax.dom_status_cell.appendChild(document.createTextNode(error_msg));
	this.ajax.dom_status_cell.setAttribute('style', 'color: #ff0000');
}

//--

// UpdateList
// this function will take care of updating multiple dealies
//
function UpdateList() {
	this.items 	= new Array();
	this.completed  = 0;
	this.last_run 	= -1;
	this.running	= 0;
}

// Add an update include class to the list
// 
// updateInclude	: Instance of UpdateInclude
UpdateList.prototype.add = function(updateInclude) {
	var t = this;
	updateInclude.doneCallback = function() { t.includeDone(); } 
	this.items[this.items.length] = updateInclude;
}

// Run the update list
// 
// TODO: batch and all that BS
UpdateList.prototype.run = function() {

	for (var x = this.running; x < 5; x++) {
		if (this.last_run + 1 >= this.items.length) { 
			break;
		}
		this.items[this.last_run + 1].run();
		this.last_run ++;
		this.running++;
	}
}

UpdateList.prototype.eventOnLoad = function() {
    this.run();
}

UpdateList.prototype.includeDone = function() {
	this.completed ++;
	this.running --;
	this.run();

	var percent = Math.floor((this.completed / this.items.length) * 100);

	var green	= document.getElementById('progress_g');
	var empty	= document.getElementById('progress_d');
	var cont	= green.parentNode;

	green.style.visibility = 'visible';
	green.style.width = percent + '%';
	empty.style.width = (100 - percent) + '%';

	if (percent >= 100) {
		cont.removeChild(empty);
	}
}

// display an update error
//
// code		: error code
// title	: error title
// msg_text : message text
// ext_msg	: extended details
function displayUpdateError(code, title, msg_text, ext_msg, product_id, product_url, include_id, include_title) {

	var error_box 				= document.getElementById('error_box');
	error_box.style.visibility 	= 'visible';
	error_box.style.margin		= '0px auto 20px auto';
	error_box.style.width		= '50%';
	var ul		  				= null;

    for (var key = 0; key < error_box.childNodes.length; key++) {
		var c = error_box.childNodes[key];
		if (c.nodeName.toLowerCase() == 'ul') {
			ul = c;
			break;
		}
	}

	if (ul == null) {
		ul = document.createElement('ul');
		error_box.appendChild(ul);
	}

	var li = document.createElement('li');
	if (title != '') {

		var b = document.createElement('b');
		b.appendChild(document.createTextNode(title));
		li.appendChild(b);
		li.appendChild(document.createElement('br'));
	}

	if (product_url != '') {
		var sp2 = document.createElement('span');
		sp2.setAttribute('style', 'color: #666666; font-size: 7pt;');

		sp2.appendChild(document.createTextNode('Product: ' + product_url + ' (' + product_id + ') '));
		sp2.appendChild(document.createElement('br'));

		if (include_title != '') {			
			sp2.appendChild(document.createTextNode('Include: ' + include_title + ' (' + include_id + ')'));			
			sp2.appendChild(document.createElement('br'));
		}
		
		li.appendChild(sp2);

	}
	
	li.appendChild(document.createTextNode(msg_text));

	if (code >= 0) {
		var sp1 = document.createElement('span');
		sp1.setAttribute('style', 'color: #666666; font-style: italic');
		sp1.appendChild(document.createTextNode(' (Code: ' + code + ')'));
		sp1.appendChild(document.createElement('br'));
		sp1.appendChild(document.createTextNode(ext_msg));

		li.appendChild(sp1);
	} 

	ul.appendChild(li);
}
/**
 * This code is missing key parts, mainly because it is designed to be converted
 * to one file to make the fucker work. Use convert/compessjs.php to compress
 * all of the javascript files into one
 *
 * $Id: site.js.php,v 1.32 2008/05/14 22:11:20 bwilder Exp $
 */
 
/* ------------------------------------------------------------------------------- *
 *    PRODUCT ADVANCED SEARCH                                                        *
 * ------------------------------------------------------------------------------- */

// AdvancedSearch
// this object deals with advanced search 
function AdvancedSearch(prefix, search_box_dom, search_conf_xml) {
    this.prefix                     = prefix;
    this.search_container           = document.getElementById(search_box_dom);
    this.search_original_html       = this.search_container.innerHTML;
    this.search_open                = false;
    this.search_conf_file           = search_conf_xml;
    this.conf_loaded                = false;
    this.conf_loading               = false;
    this.searchTypes                = new Array();
    this.rowParent                  = false;
    this.rows                       = new Array();
    this.first_input_num            = 0;
    this.row_ct                     = 0;
    var l = this;
    this.onLoadFinish               = function() { 
        murderChildren(l.rowParent);
        l.createSearchRow(-1);
    };
    this.link_dom                   = '';
}

// data types for the 
var typeNumber      = 1;
var typeText        = 2;
var typeOther       = 3;
var typeDropDown    = 4;
var typeDropDownLink = 5;

function SearchField(typeId, title, data_type) {
    this.typeId         = typeId;
    this.title          = title;
    this.dataType       = data_type;
    this.dropDownItems  = '';
    this.src            = '';
}

function SearchRow(td1, td2, td3, type_sel, compare_sel) {
    this.td1            = td1;
    this.td2            = td2;
    this.td3            = td3;
    this.input_box      = null;
    this.type_select    = type_sel;
    this.compare_select = compare_sel;
    this.input_number   = 0;
    
    this.type_selected  = '';
    this.comp_selected  = '';
    this.value          = '';
}

// decides which search we are on, and create
// the serach box for that type of search
//
// link_dom        : DOM element for the open link
AdvancedSearch.prototype.displayAdvancedSearch = function(link_dom) {
    
    this.link_dom = link_dom;
    
    if (this.search_open == false) {
        /** -- BOX IS CLOSED, OPEN IT -- **/
        this.search_open = true;
        murderChildren(link_dom);
        link_dom.appendChild(document.createTextNode(' Simple Search > '));        
        
        this.createSearchTable();
        
    } else {
        /** -- BOX IS OPEN, CLOSE IT AND RESTORE SIMPLE PARAMS -- **/
        
        murderChildren(link_dom);
        link_dom.appendChild(document.createTextNode(' < Advanced Search '));
        this.search_open = false;
        
        this.saveRows();
        
        /** -- RESTORE THE ORIGINAL BOX -- **/
        murderChildren(document.getElementById('product_search_box'));
        document.getElementById('product_search_box').innerHTML = this.search_original_html;
    }    
}

// save the values of the rows
AdvancedSearch.prototype.saveRows = function() {
    
    for (key in this.rows) {
        var r = this.rows[key];
        if (r == false) { continue; }
        
        var type_id = r.type_select.options[r.type_select.selectedIndex].value;
        
        if (type_id == '') {
            continue;
        }
        var type = this.getType(type_id);

        if (r.input_box != null) {
            if (type.dataType != typeDropDown && type.dataType != typeDropDownLink) {
                r.value = r.input_box.value;
            } else {
                r.value = r.input_box.options[r.input_box.selectedIndex].value;
            }
        }        
        
        r.type_selected = type_id;
        r.comp_selected = r.compare_select.options[r.compare_select.selectedIndex].value;    
    }
}

// return the type from the type name
AdvancedSearch.prototype.getType = function(type_name) {
    for (key in this.searchTypes) {
        var type = this.searchTypes[key];
        
        if (type.typeId == type_name) {
            return type;
        }
    }
    return null;
}

AdvancedSearch.prototype.addRow = function(type_id, comp, value) {
    var r = new SearchRow();
    r.type_selected = type_id;
    r.comp_selected = comp;
    r.value         = value;
    if (this.conf_loaded     == false) {
        this.loadConfiguration();
    }
    r.input_number  = this.rows.length;

    this.rows[this.rows.length] = r;
    this.row_ct ++;
}    

AdvancedSearch.prototype.removeRow = function(row_node) {
    
    var tr = row_node.td1.parentNode;
    
    this.rowParent.removeChild(tr);
    this.rows[row_node.input_number] = false;
    this.row_ct --;
    
    if (this.row_ct <= 0) {
        this.displayAdvancedSearch(this.link_dom);
    }
}

// Load the advanced search configuration
// 
AdvancedSearch.prototype.loadConfiguration = function() {
    
    if (this.config_loading == true) {
        return;
    }
    
    this.config_loading = true;

    // load the configuration
    var ajax            = new AjaxConnection();
    ajax.base_tag       = 'TLASearchConfig';
    var l               = this; // (hack so we can call our own members)
    ajax.processer      = function(root_node, aj) { l.loadConfigFinished(root_node, aj); }

    ajax.Connect(this.search_conf_file);
    
}

// XML configuration has finished loading
// root_node        : the ROOT XML Node
// ajax             : the ajax class
AdvancedSearch.prototype.loadConfigFinished = function(root_node, ajax) {
    this.config_loading = false;
    
    for (var key = 0; key < root_node.childNodes.length; key++) {
        var node = root_node.childNodes[key];
        
        switch (node.nodeName) {
            case 'Types':
                this.loadConfigTypes(node);
            break;
        }
    }
    
    this.conf_loaded = true;
    
    this.onLoadFinish();
    
}

// Load the XML Type field
// 
// type_node - the <Type> node
AdvancedSearch.prototype.loadConfigTypes = function(type_node) {
    for (var key = 0; key < type_node.childNodes.length; key++) {
        var node = type_node.childNodes[key];
        
        if (node.nodeName == 'Field') {
            this.loadConfigFieldNode(node);
        }
    }
}

// Load the XML Field node
//
// field_node the <Field> Node
AdvancedSearch.prototype.loadConfigFieldNode = function(field_node) {

    // field_values
    var field = new SearchField();    
    field.typeId        = field_node.attributes.getNamedItem('typeId').value;
    var field_title     = '';
    var field_type      = typeOther;

    for (var key = 0; key < field_node.childNodes.length; key++) {
        var node = field_node.childNodes[key];
        
        switch (node.nodeName) {
            case 'Name':
                field.title         = node.firstChild.nodeValue;
            break;
            case 'Number':
                field.dataType      = typeNumber;
            break;
            case 'Text':
                field.dataType      = typeText;
            break;
            case 'DropDown':
                field.dataType      = typeDropDown;
                field.dropDownMenu  = new DropDownMenu;
                field.dropDownMenu.setFromXML(node);
            break;
            case 'DropDownLink':
                field.dataType      = typeDropDownLink;
                field.src           = node.attributes.getNamedItem('src').value;
            break;
        }
    }
    

    
    
    this.searchTypes[this.searchTypes.length] = field;
}

// Advanced Search
// create the advanced search box with one field
AdvancedSearch.prototype.createSearchTable = function() {


    murderChildren(this.search_container);
    
    // <table>
    var table = document.createElement('table');
    table.setAttribute('style', 'margin-left: auto');
    setCss(table, 'advanced_search');
    
    // <tbody>
    var tbody1 = document.createElement('tbody');
    this.rowParent = tbody1;
    table.appendChild(tbody1);
    
    // second tbody for the buttons
    var tbody2 = document.createElement('tbody');
    

    var tr = document.createElement('tr');
    var td1 = document.createElement('td');
    td1.colSpan = 2;
    td1.setAttribute('colspan', '2');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');

    // link which adds more fields
    var sp = document.createElement('span');
    var listener = this;
    sp.onclick = function() { listener.createSearchRow(-1) }    
    setCss(sp, 'fakelink');
    sp.appendChild(document.createTextNode(' One More Field '));
    td1.setAttribute('align', 'center');
    td1.appendChild(sp);

    // submit button
    var input = document.createElement('input');
    input.setAttribute('type', 'submit');
    input.setAttribute('value', 'Search');
    setCss(input, 'search_box');
    td2.setAttribute('align', 'center');
    td2.appendChild(input);
    
    // submit button
    var input2 = document.createElement('input');
    input2.setAttribute('type', 'submit');
    input2.setAttribute('value', 'Clear');
    input2.setAttribute('name', 'adv_clear');
    setCss(input2, 'cancel_button');
    td3.setAttribute('align', 'center');
    td3.appendChild(input2);    
    
    // finish
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);
    tbody2.appendChild(tr);
    table.appendChild(tbody2);

    this.search_container.appendChild(table);
    
    // load the configuration
    if (this.conf_loaded     == false) {
        loadingRow(this.rowParent);
        this.loadConfiguration();
    } else {
        if (this.row_ct <= 0) {
            this.createSearchRow(-1);
        } else {
            for (key in this.rows) {
                if (this.rows[key] != false) {
                    this.createSearchRow(key);
                }
            }
        }
    }
}

// Create a search row with the configured types
//
AdvancedSearch.prototype.createSearchRow = function(row_id) {
    
    var tr = document.createElement('tr');
    var td0 = document.createElement('td');
    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');             

    if (row_id < 0) {
        var row_node = new SearchRow(td1, td2, td3, '', '');    
        row_node.input_number = this.rows.length;
    } else {
        var row_node = this.rows[row_id];
        row_node.td3 = td3;
        row_node.td2 = td2;
        row_node.td1 = td1;
    } 

    // CREATE the type dropdown menu
    var dd = new DropDownMenu();
    
    dd.addItem('', '--SELECT TYPE--');
            
    for (key in this.searchTypes) {
        var type = this.searchTypes[key];
        dd.addItem(type.typeId, type.title);
    }
    
    dd.name = 'adv_type[' + row_node.input_number + ']';    
    
    dd.selectByValue(row_node.type_selected);

    type_select = dd.createDom();    
    row_node.type_select = type_select;

    var t = this;
    
    type_select.onchange = function () {
        t.typeDropDownChange(row_node);
    }
    
    var sp = document.createElement('span');
    setCss(sp, 'fakelink');
    sp.appendChild(document.createTextNode('- '));
    sp.onclick = function() {
        t.removeRow(row_node);
    }
    td0.appendChild(sp);
    
    td1.appendChild(type_select);      
      
    tr.appendChild(td0);
    tr.appendChild(td1);    
    tr.appendChild(td2);
    tr.appendChild(td3);    
    
    this.rowParent.appendChild(tr);

    if (row_id < 0) {        
        this.rows[this.rows.length] = row_node;
        this.row_ct++;
    } else {
        this.typeDropDownChange(row_node);
    }
}

// Changed type drop down
//
// row_node = instance of SearchRow
AdvancedSearch.prototype.typeDropDownChange = function(row_node) {

    var type_id = row_node.type_select.options[row_node.type_select.selectedIndex].value;

    if (type_id == '') {
        if (row_node.compare_select != '') {
            murderChildren(row_node.compare_select);
        }
        murderChildren(row_node.td3);
        return;
    }
    
    var type_node = this.getType(
        type_id
    );    
    
    if (type_node == null) {
        alert('Invalid Type');
        return null;
    }
    
    if (type_id != row_node.type_selected) {
        row_node.value = '';
    }
    
    switch (type_node.dataType) {
        case typeNumber:
            this.numberRow(row_node, type_node);
        break;
        case typeDropDown:
            this.dropDownRow(row_node, type_node);
        break;
        case typeText:
            this.textRow(row_node, type_node);
        break;
        case typeDropDownLink:
            this.dropDownLinkRow(row_node, type_node);
        break;
    }

}

// row_node -- instance of SearchRow
AdvancedSearch.prototype.numberRow = function (row_node, type_node) {

    
    var dd = new DropDownMenu('adv_comp[' + row_node.input_number + ']');
    
    dd.addItem('eq', 'Is');
    dd.addItem('not', 'Is Not');                    
    dd.addItem('gt', '>');
    dd.addItem('lt', '<');
    dd.addItem('gte', '>=');
    dd.addItem('lte', '<=');

    dd.selectByValue(row_node.comp_selected);
    
    murderChildren(row_node.td2);
    row_node.compare_select = dd.createDom();
    row_node.td2.appendChild(row_node.compare_select);                      

    
    murderChildren(row_node.td3);
    var input = createInputBox('adv_value[' + row_node.input_number + ']',row_node.value);
    row_node.td3.appendChild(input);
    row_node.input_box = input;
}

// drop down row
AdvancedSearch.prototype.dropDownRow = function(row_node, type_node) {
    
    var dd = new DropDownMenu('adv_comp[' + row_node.input_number + ']');
    dd.addItem('eq', 'Is');
    dd.addItem('not', 'Is Not');   
    dd.selectByValue(row_node.comp_selected);
    murderChildren(row_node.td2);
    row_node.compare_select = dd.createDom();
    row_node.td2.appendChild(row_node.compare_select);                      
                  

    murderChildren(row_node.td3);
    type_node.dropDownMenu.name = 'adv_value[' + row_node.input_number + ']';
    type_node.dropDownMenu.selectByValue(row_node.value);
    var sel = type_node.dropDownMenu.createDom();
    row_node.input_box = sel;
    row_node.td3.appendChild(sel);
}

// drop down link row
AdvancedSearch.prototype.dropDownLinkRow = function(row_node, type_node) {
    
    var dd = new DropDownMenu('adv_comp[' + row_node.input_number + ']');
    dd.addItem('eq', 'Is');
    dd.addItem('not', 'Is Not');  
    dd.selectByValue(row_node.comp_selected);
    murderChildren(row_node.td2);
    row_node.compare_select = dd.createDom();
    row_node.td2.appendChild(row_node.compare_select);                      

    murderChildren(row_node.td3);
    
    var ajax = new AjaxConnection;
    ajax.base_tag = 'TLAAdmin';
    ajax.processer = drop_down_link_finish;
    ajax.container = row_node.td3;
    ajax.row_node  = row_node;
    ajax.select_name = 'adv_value[' + row_node.input_number + ']';
    ajax.Connect('/' + type_node.src);
    
}

function drop_down_link_finish(root_node, ajax) {
    var dd = new DropDownMenu(ajax.select_name);
    
    for (var key = 0; key < root_node.childNodes.length; key++) {
        var n = root_node.childNodes[key];
        if (n.nodeName == 'DropDown') {
            dd.setFromXML(n);
        }    
    }
    dd.selectByValue(ajax.row_node.value);
    
    ajax.container.appendChild(dd.createDom());
}


// row_node -- instance of SearchRow
AdvancedSearch.prototype.textRow = function (row_node, type_node) {
    
    var dd = new DropDownMenu('adv_comp[' + row_node.input_number + ']');    
    dd.addItem('all', 'Contains All Words');
    dd.addItem('any', 'Contains Any Word');       
    dd.addItem('eq', 'Exactly Equal');    
    dd.addItem('not', 'Does Not Contain');
    dd.selectByValue(row_node.comp_selected);    
    murderChildren(row_node.td2);
    row_node.compare_select = dd.createDom();
    row_node.td2.appendChild(row_node.compare_select);          
    
    murderChildren(row_node.td3);
    var input = createInputBox('adv_value[' + row_node.input_number + ']',row_node.value);
    row_node.td3.appendChild(input);
    row_node.input_box = input;
}/**
 * $Id: site.js.php,v 1.32 2008/05/14 22:11:20 bwilder Exp $
 */

var cursor = {x:0, y:0};
var onload_queue = new Array();

function page_load() { 
//  if (window.Event) {
//    document.captureEvents(Event.MOUSEMOVE);
//  }
  document.onmousemove = getXY;
  for (key in onload_queue) {
    var c = onload_queue[key]
    c.eventOnLoad();
  }
}

function addOnLoadQueue(item) {
    onload_queue[onload_queue.length] = item;
}

function getXY(e) {
    e = e || window.event;

    if (window.Event) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }

}

var search_clicked = false;
var hold_next_click = false;
/**
 * clears the search box if it is 
 * click for the first time
 */
function search_click(element) {
    if (search_clicked == false) {
        element.setAttribute('value', '');
        element.setAttribute('style', 'color: #000000; ');
        search_clicked = true;
    }
}

function holdClick() {
    hold_next_click = true;
} 

function releaseClick() {
    hold_next_click  = false;
}

function change_form_postto(form_dom_id, new_url) {
    var f = document.getElementById(form_dom_id);
    f.action = new_url;
}


/**
 * in the add/edit vendor page, populate the company
 * field from the first and last name
 */
function vendor_set_company() {
    var f_name_i = document.getElementById('first_name');
    var l_name_i = document.getElementById('last_name');
    var company_i = document.getElementById('company');
    
    
    var c_n = f_name_i.value + ' ' + l_name_i.value;
    company_i.value = c_n;         
}

/**
 * text next to a check box clicked, so check or uncheck it
 */
function check_box_text_clicked(dom_id) {

    var c = document.getElementById(dom_id);
    if (c) {
        c.checked = !c.checked;
    }
    if (c.onchange) {
        c.onchange();
    }
}

// class that holds the sorting optiosn
function product_sort_opts(vendor, pr, alexa, bl, cat, place, index, buy, sell, status) {
    this.vendor = vendor;
    this.pr        = pr;
    this.alexa    = alexa;
    this.bl        = bl;
    this.cat    = cat;
    this.index  = index;
    this.place    = place;
    this.buy    = buy;
    this.sell    = sell;
    this.status  = status;
}

function link_disable_change(element, url) {
    if (element.checked == true) {
        document.location.href = url + '?show_disabled=1';
    } else {
        document.location.href = url;
    }
}

function check_all(prefix, max) {
    for (var x = 0; x <= max; x++) {
        var c = document.getElementById(prefix + '_' + x);
        if (c) {
            c.checked = true;
        }
    }
}

function uncheck_all(prefix, max) {
    for (var x = 0; x <= max; x++) {
        var c = document.getElementById(prefix + '_' + x);
        if (c) {
            c.checked = false;
        }
    }
}


// Create a simple text box and return
// the created DOM
//
// name - name
// value - value
function createInputBox(name, value) {
    var input = document.createElement('input');
    setCss(input, 'text_box');
    
    input.setAttribute('type', 'text');
    input.setAttribute('size', 20);
    input.setAttribute('maxlength', 255);
    input.setAttribute('value', value);
    input.setAttribute('name', name);
    
    return input;
}


// set the CSS for the inputed dom node
// to the inputted CSS class
//
// dom: dom node
// css: CSS class name
function setCss(dom, css) {
    dom.setAttribute('class', css);
    dom.setAttribute('className', css);
}

// in the order screen the checkbox is selected
// for overriding pricing
function pricing_override(check_box, input_dom_id) {
    var input_box = document.getElementById(input_dom_id);
    if (!input_box) {
        alert('Error: ' + input_dom_id + ' dom id doesnt exist');
        return;
    }
    
    if (check_box.checked == true) {
        input_box.disabled = false;
        setCss(input_box, 'text_box');
    } else {
        input_box.disabled = true;
        setCss(input_box, 'blank_input');        
    }
}

function select_place_hover(id, direction) {
    var ids = new Array('link_row_' + id + '_a', 'link_row_' + id + '_b');
    
    for (var key = 0; key < ids.length; key++) {
        var c = document.getElementById(ids[key]);
        setCss(c, direction == true ? 'hover_item' : 'border_table');
    }
}


/* ------------------------------------------------------------------------------- *
 *    DROP DOWN MENU CREATER                                                       *
 * ------------------------------------------------------------------------------- */

function DropDownMenu(name) {
    this.name = name;
    this.options = new Array();
    this.selected = -1;
}

function DropDownOption(value, title) {
    this.value = value;
    this.title = title;
}

DropDownMenu.prototype.addItem = function(value, title) {
   this.options[this.options.length] = new DropDownOption(value, title);
}


DropDownMenu.prototype.setFromXML = function(drop_node) { 

    for (var key = 0; key < drop_node.childNodes.length; key++) {
        if (drop_node.childNodes[key].nodeName == 'DropDownItem') {
            this.setNodeFromXML(drop_node.childNodes[key]);
        }
    }
}


DropDownMenu.prototype.setNodeFromXML = function(node) {
    var title;
    var value;
    
    for (var key = 0; key < node.childNodes.length; key++) {
        var n = node.childNodes[key];    
        switch (n.nodeName) {
            case 'Name':
                title = n.firstChild.nodeValue;
            break;
            case 'Value':
                value = n.firstChild.nodeValue;
            break;
        }        
    }
    
    this.addItem(value, title);
}

DropDownMenu.prototype.selectByValue = function(value) {
    for (var key = 0; key < this.options.length; key++) {
        if (this.options[key].value == value) {
            this.selected = key;
        }
    }
}

DropDownMenu.prototype.createDom = function() {
    var select = document.createElement('select');
    select.setAttribute('name', this.name);
    
    for (var key = 0; key < this.options.length; key++) {    
        var o = createSelectOption(this.options[key].value, this.options[key].title);
        if (this.selected == key) {
            o.setAttribute('selected', 'selected');
        }
        select.appendChild(o);
    }
    
    return select;
}


// add an option field to a select box
//
// value
// text
function createSelectOption(value, text) {
    var o = document.createElement('option');
    o.setAttribute('value', value);
    o.appendChild(document.createTextNode(text));
    return o;
}

function createImageDom(src, alt) {
    var i = document.createElement('img');
    i.setAttribute('src', '/html/images/' + src);
    i.setAttribute('alt', alt);
    return i;
}

/* ------------------------------------------------------------------------------- *
 *    EXPAND CHILD PRODUCTS                                                          *
 * ------------------------------------------------------------------------------- */
var child_opened = new Array();
var child_rows = new Array();

function expand_child_products(product_id, base_url, image, check_box_name) {

    if (child_opened[product_id] == 1) {
        var close = true;
        child_opened[product_id] = 2;
    } else {
        var close = false;        
        child_opened[product_id] = 1;
    }
    

    if (close == false) {
        
        var ajax = new AjaxConnection;
        ajax.base_tag = 'TLAAdmin';
        ajax.processer = expand_child_html_done;
        ajax.product_id = product_id;
        ajax.base_script_url = base_url;
        
        child_rows[product_id] = new Array();
        
        ajax.loading_row     = loadingRow(document.getElementById('product_row_' + product_id));
        ajax.check_box_name  = check_box_name;
        
        ajax.Connect(base_url + '/ajax/child_products.php?parent_id=' + product_id + '&save_exp=true&respond_html=fart' +
                     (check_box_name != false ? '&check_box_name=' + escape(check_box_name) : ''));
        var s = image.getAttribute('src');
        image.setAttribute('src', s.replace(/plus\.gif$/, 'minus.gif'));
        
    } else {
        var ajax = new AjaxConnection;
        ajax.base_tag = 'TLAAdmin';
        ajax.Connect(base_url + '/ajax/product_unexp.php?parent_id=' + product_id);

        var cont = document.getElementById('product_children_' + product_id);
        var s = image.getAttribute('src');
        image.setAttribute('src', s.replace(/minus\.gif$/, 'plus.gif'));
        if (child_rows[product_id]) {
            var parent_row = document.getElementById('product_row_' + product_id);
            var td_ctr = 0;
        
            var tbody = parent_row.parentNode;
            for (var x = 0; x < child_rows[product_id].length; x++) {
                tbody.removeChild(child_rows[product_id][x]);
            }
            child_rows[product_id] = new Array();
        }
    }
    
}

function loadingRow(add_after_element) {

    if (add_after_element.nodeName.toLowerCase() == 'tbody') {
        var tbody = add_after_element;
    } else {
        var tbody = add_after_element.parentNode;
    }
    
    var col_count = 0;
    
    for (var x = 0; x < add_after_element.childNodes.length; x++) {
        var c = add_after_element.childNodes[x];
        if (c.nodeName.toLowerCase() == 'td' || c.nodeName.toLowerCase() == 'th') {
            if (c.colspan > 1) {
                col_count += c.colspan;
            } else {
                col_count++;
            }
        }
    }
    
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    
    if (col_count > 0) {
        td.setAttribute('colspan', col_count);
        td.colSpan = col_count;
    }
    
    setCss(td, 'loading_row');
    td.setAttribute('style', 'color: #777777');
    s = document.createElement('span');
    s.appendChild(document.createTextNode('Loading...'));
    td.appendChild(s);
    tr.appendChild(td);
    
    if (add_after_element.nodeName.toLowerCase() == 'tbody') {
        tbody.appendChild(tr);
    } else {
        var insert_before = add_after_element.nextSibling;
        tbody.insertBefore(tr, insert_before);
    }
    return tr;
    
}

function expand_child_html_done(root_node, ajax) {

    var parent_row = document.getElementById('product_row_' + ajax.product_id);
    var tbody = parent_row.parentNode;
    if (ajax.loading_row) {
        tbody.removeChild(ajax.loading_row);
    }

    var td_ctr = 0;

    var insert_before_node = parent_row.nextSibling;
    
    // change the row spans for the parent nodes
    for (var x = 0; x < parent_row.childNodes.length; x++) {
        if (parent_row.childNodes[x].nodeName.toLowerCase() == 'td') {

            if (td_ctr < 2 + (productSort.vendor == true ? 1 : 0)) {
                setCss(parent_row.childNodes[x], 'top_product_border');
            }
            td_ctr++;
        }
    }
    
    
    var html = '';
    for (var key = 0; key < root_node.childNodes.length; key++) {
        var c = root_node.childNodes[key];
        
        if (c.nodeName == 'html') {
            html = c;
            break;
        }
    }    
    
    for (var key = 0; key < html.childNodes.length; key++) {
        var c = html.childNodes[key];
        if (c.nodeName == 'tr') {
            var row = convertXmlToHTMLDom(c);
            tbody.insertBefore(
                row,
                insert_before_node                    
            );               
            child_rows[ajax.product_id][child_rows[ajax.product_id].length] = row;

        }
    }    
}

function convertXmlToHTMLDom(node) {
    
    return xmlToDom(null, node, null);
    /*
    var d_n = document.createElement(node.nodeName);
    // attributes
    for (var key = 0; key < node.attributes.length; key++) {
        if (node.attributes[key].name == 'class') {
            setCss(d_n, node.attributes[key].value);    
        } else if (node.attributes[key].name == 'colspan') {
            d_n.colSpan = node.attributes[key].value;
        } else {
            d_n.setAttribute(node.attributes[key].name, node.attributes[key].value);
        }
    }   
    
    // kids
    for (var key = 0; key < node.childNodes.length; key++) {
        var c = node.childNodes[key];

        if (c.nodeType == 3 || c.nodeType == 4) {
            d_n.appendChild(document.createTextNode(c.nodeValue));
        } else {
            d_n.appendChild(convertXmlToHTMLDom(c));
        }

    }
    return d_n;
    */
}

/**
 * xmlToDom
 * convert an XML document tree to an HTML document by appending it
 * to the inputted dom node
 *
 * parent_node  :   the DOM node to add the XML information to
 * xml_node     :   the XML node to take the information from
 * insert_after :   if specified, it will be added after this
 *                  child node of parent_node, instead of the end
 */
function xmlToDom(parent_node, xml_node, insert_after) {
    var dom = null;
    var inserted = false;
    
    // parse the PHP error node to add the error to the error list
    if (xml_node.nodeName == 'PHPError') {
        if (aj_error_handler) {
            aj_error_handler.addPostVar("msg[]", xml_node.firstChild.nodeValue);
            show_error_box(error_box_dom_id);
        }
        return;
    }
    
    // replace the inputted DOM id with the 
    // contents of this node
    if (xml_node.nodeName == 'ReplaceDOM') {
        replaceDOM(xml_node);
        return;
    }
    
    if (xml_node.nodeName == 'ClosePopup') {
        closePopup();
        return;
    }
    
    if (xml_node.nodeName == 'RefreshBoxLoader') {
        if (active_box_loader && active_box_loader.loadBox) {
            active_box_loader.loadBox(null);
        }
        return;
    }
    
    if (xml_node.nodeName == 'ReloadPage') {
        window.location.reload();
    }
    
    // script node? evaluate it's contents
    // NOTE: vars are considered local to the eval, so if you need the value
    // somewhere that is not in this script block, you are SOL.
    if (xml_node.nodeName == 'script') {
        // assume script has only 1 cdata field
        if (xml_node.firstChild) {
            eval(xml_node.firstChild.nodeValue);
        }
        return;
    }
    
    if (xml_node.nodeName != 'RequireRow' && xml_node.nodeName != 'DomainAdmin') {
        // Create the actual node, if it is not one of these ignored node names       
        dom = document.createElement(xml_node.nodeName);
        
        dom.event_eval = new Array();
        var attr_ct = xml_node.attributes.length;
        for (var x = 0; x < attr_ct; x++) {
                        
            var name  = xml_node.attributes[x].name.toLowerCase(); 
            var value = xml_node.attributes[x].value;
            
            // This switch is for attributes that Internet Explorer's 
            // stupid ass not compliant JScript garbage doesn't do correctly
            switch (name) {
                case 'class':
                    setCss(dom, value);
                break;
                
                // Fix IE not liking setAttribute to do events
                case 'onclick':
                case 'onchange':
                case 'onmousedown':
                case 'onmouseup':
                case 'onmouseover':
                case 'onmouseout':
                case 'onmousemove':
                case 'onreset':
                case 'onselect':
                case 'onsubmit':
                case 'onunload':
                case 'onload':
                case 'onkeydown':
                case 'onkeyup':
                case 'onkeypress':
                case 'onfocus':
                case 'onerror':
                case 'ondblclick':
                case 'onblur':
                case 'onabort':
                    eval("dom." + name + " = function() { eval('" + value.replace(/\'/g, "\\'")  + "'); };");
                break;
                
                case 'run':
                    eval(value.replace(/this/g, 'dom'));
                break;
                
                case 'checked':
                    dom.checked = true;
                break;
                
                case 'colspan':xml_node.attributes.length
                    dom.setAttribute(xml_node.attributes[x].name, value);
                    dom.colSpan = parseInt(value);
                break;
                
                case 'style':
                    dom.setAttribute(xml_node.attributes[x].name, value);
                    dom.style.cssText = value;
                break;

                default:                    
                    dom.setAttribute(xml_node.attributes[x].name, value);
                break;                    
            }
        }
        
        if (parent_node) {
            if (insert_after) {
                var next_node = insert_after.nextSibling;
                if (next_node) { // verify that the next sibling is for reals
                    parent_node.insertBefore(dom, next_node);
                    inserted    = true;
                } else {
                    parent_node.appendChild(dom);
                }
            } else {
                parent_node.appendChild(dom);
            } 
        }
        
    } else {
        dom = parent_node;
    }
    
    for (var x = 0; x < xml_node.childNodes.length; x++) {
        var c = xml_node.childNodes[x];
        
        if (c.nodeType == 3 || c.nodeType == 4) {
            dom.appendChild(document.createTextNode(c.nodeValue));
        } else {
            if (inserted == false) {
                xmlToDom(dom, c, insert_after);
            } else {
                xmlToDom(dom, c, null);     // override insert_after because it has already been used
            }
        }
    }
    
    return dom;
}


function expand_child_done(root_node, ajax) {

    var parent_row = document.getElementById('product_row_' + ajax.product_id);
    var tbody = parent_row.parentNode;
    if (ajax.loading_row) {
        tbody.removeChild(ajax.loading_row);
    }

    var td_ctr = 0;

    var insert_before_node = parent_row.nextSibling;

    // change the row spans for the parent nodes
    for (var x = 0; x < parent_row.childNodes.length; x++) {
        if (parent_row.childNodes[x].nodeName.toLowerCase() == 'td') {

            if (td_ctr < 2 + (productSort.vendor == true ? 1 : 0)) {
                setCss(parent_row.childNodes[x], 'top_product_border');
            }
            td_ctr++;
        }
    }
    
    child_rows[ajax.product_id] = new Array();

    // go through the xml
    for (var x = 0; x < root_node.childNodes.length; x++) {
        var c = root_node.childNodes[x];
        switch (c.nodeName) {
            case 'Error':
                cont.appendChild(document.createTextNode(c.firstChild.nodeValue));
            break;
            case 'Product':

                
                var parent_class = parent_row.getAttribute('class');
                if (!parent_class) {
                    parent_class = parent_row.getAttribute('className');
                }
                var row = productXmlNode(c, x == root_node.childNodes.length - 1 ? true : false, parent_class, ajax.base_script_url, ajax.check_box_name);    
                if (parent_class) {
                    setCss(row, parent_class);
                }                 
                tbody.insertBefore(
                    row, 
                    insert_before_node                    
                );
                
                child_rows[ajax.product_id][child_rows[ajax.product_id].length] = row;
            break;
        }
    }
    hold_next_click = false;
}

function productXmlNode(node, last, parent_class, base_url, check_box_name) {
    var product_id;
    var url;
    var vendor_name;
    var buy_price;
    var sell_price;
    var place;
    var category = '';
    var indexed;
    var google;
    var alexa;
    var bl;
    var status;
    var category = new Array();
    
    for (var x = 0; x < node.childNodes.length; x++) {
        var c = node.childNodes[x];
        switch (c.nodeName) {
            case 'ProductID':
                product_id = c.firstChild.nodeValue;
            break;
            case 'Url':
                url = c.firstChild.nodeValue;
            break;
            case 'VendorName':
                vendor_name = c.firstChild.nodeValue;
            break;
            case 'BuyPrice':
                buy_price = c.firstChild.nodeValue;
            break;
            case 'SellPrice':
                sell_price = c.firstChild.nodeValue;
            break;
            case 'Placement':
                place = c.firstChild.nodeValue;
            break;
            case 'IndexedPages':
                indexed = c.firstChild.nodeValue;
            break;
            case 'GoogleRank':
                google = c.firstChild.nodeValue;
            break;
            case 'AlexaRank':
                alexa = c.firstChild.nodeValue;
            break;
            case 'BacklinkCount':
                bl = c.firstChild.nodeValue;
            break;
            case 'Category':
                category [ category.length ] = c.firstChild.nodeValue;
            break;
            case 'Status':
                status = parseInt(c.firstChild.nodeValue);
            break;
        }
    }

    var tr = document.createElement('tr');
    
    if (!check_box_name) {
        tr.onclick = function() {
            if (!hold_next_click) {
                document.location.href = base_url + '/index.php/product/view/' + product_id;
            }
        }
    }
    tr.style.cursor = 'pointer';
    tr.setAttribute('style', 'cursor: pointer');
    
    var td1 = document.createElement('td');
    var td2 = document.createElement('td');

    setCss(td1, 'top_product_border');
    if (check_box_name != false) {
        var pcb = document.createElement('input');
        pcb.setAttribute('type', 'checkbox');
        pcb.setAttribute('name', check_box_name);
        pcb.setAttribute('value', product_id);
        pcb.name = check_box_name;
        td1.appendChild(pcb);
    }
    td1.appendChild(document.createTextNode(' ' + product_id));

    if (last) {
        setCss(td2, 'child_table_bottom' + (parent_class != 'border_table_mo' ? '_alter' : ''));
    } else {
        setCss(td2, 'child_table_join' + (parent_class != 'border_table_mo' ? '_alter' : ''));
    }   
    
    td2.appendChild(document.createTextNode(url));

    tr.appendChild(td1);
    tr.appendChild(td2);
    
    if (productSort.status) {
        var td21 = document.createElement('td');
        var text = '';
        switch (status) {
            case  0:          text = 'Active'; break;
            case  1:         text = 'Pending'; break;
            case  2:        text = 'Disabled'; break;
            case  3:     text = 'Place Holder'; break;
        }
        td21.appendChild(document.createTextNode(text));
        tr.appendChild(td21);
    }
    
    if (productSort.vendor) {
        var td3 = document.createElement('td');   
        td3.appendChild(document.createTextNode(vendor_name));                 
        tr.appendChild(td3);
    }
    if (productSort.pr) {
        tr.appendChild(statNode(google));
    }
    if (productSort.alexa) {
        tr.appendChild(statNode(alexa));
    }
    if (productSort.bl) {
         tr.appendChild(statNode(bl));
    }
    if (productSort.index) {
           tr.appendChild(statNode(indexed));   
    }
    if (productSort.cat) {
        var td71 = document.createElement('td');
        
        for (var key = 0; key < category.length; key++) {
            if (key > 0) {
                td71.appendChild(document.createElement('br'));
            }
            td71.appendChild(document.createTextNode(category[key]));
        }
        tr.appendChild(td71);
    }
    if (productSort.place) {
        var td8 = document.createElement('td');
        td8.setAttribute('align', 'center');
        td8.appendChild(document.createTextNode(place));
        tr.appendChild(td8);
    }
    if (productSort.buy) {
        var td9 = document.createElement('td');
        td9.setAttribute('align', 'center');
        td9.appendChild(document.createTextNode(buy_price));
        tr.appendChild(td9);
    }
    if (productSort.sell) {
        var td10= document.createElement('td');
        td10.setAttribute('align', 'center');
        td10.appendChild(document.createTextNode(sell_price));
        tr.appendChild(td10);
    }
    return tr;
}

function statNode(value) {
    var td = document.createElement('td');             
    td.setAttribute('align', 'center');
    if (value >= 0) { 
        td.appendChild(document.createTextNode(value));      
    } else {
        var sp = document.createElement('span');
        sp.setAttribute('style', 'color: #999999');
        sp.appendChild(document.createTextNode('N/A'));
        td.appendChild(sp);
    }
    return td;
}

/* ------------------------------------------------------------------------------- *
 *    PRICING USER INTERFACE FUNCTIONS                                               *
 * ------------------------------------------------------------------------------- */

var old_sell_price = 0;

function sell_price_focus(element) {
    old_sell_price = parseFloat(element.value);
    if (isNaN(old_sell_price)) {
        old_sell_price = 0;
        element.value = '0.00';
    }
}

function sell_price_blur(element, one_mo_dom_id, three_mo_dom_id, six_mo_dom_id) {
    var price_1mo_i = document.getElementById(one_mo_dom_id);

    var sell_price    = parseFloat(element.value);
    
    if (isNaN(sell_price) || sell_price == 'NaN') {
        sell_price = 0;
    }    
    
    element.value = sell_price.toFixed(2);
    
    var price_1mo = parseFloat(price_1mo_i.value);
    
    if (price_1mo <= 0.0 || price_1mo == old_sell_price ) {
        price_1mo_i.value = sell_price.toFixed(2);
        price_1mo_blur(price_1mo_i, three_mo_dom_id, six_mo_dom_id);
    }
    
    old_sell_price = sell_price;    
}

function price_blur(element) {
    var float_val = parseFloat(element.value);
    if (isNaN(float_val) || float_val == 'NaN') {
        element.value = '0.00';
        return;
    }
    element.value = float_val.toFixed(2);
}

function sell_monthly_auto(check_box, month_dom_id, one_mo_dom_id, duration) {
    
    var edit = document.getElementById(month_dom_id);
    var sell_price = document.getElementById(one_mo_dom_id).value;
    sell_price = parseFloat(sell_price);
    
    if (isNaN(sell_price)) {
        sell_price = 0;
        document.getElementById('sell_1mo').value = '0.00';
    }
    
    if (check_box.checked == true) {
        setCss(edit, 'blank_input');
        edit.disabled = true;
    } else {
        setCss(edit, 'text_box');
        edit.disabled = false;
    }
    
    calculate_monthly(sell_price, edit, duration);
}

function calculate_monthly(sell_price, edit, duration) {
    if (duration == 3) {
        var d = sell_price * 3 * 0.9;
        edit.value = d.toFixed(2);
    } else if (duration == 6) {
        var d = sell_price * 6 * 0.85;
        edit.value = d.toFixed(2);
    }
}

function price_1mo_blur(element, three_mo_dom_id, six_mo_dom_id) {
    price_blur(element);
    var float_val = parseFloat(element.value);
    
    var price3mo = document.getElementById(three_mo_dom_id);
    var price6mo = document.getElementById(six_mo_dom_id);
    
    if (price3mo.disabled == true) {
        calculate_monthly(float_val, price3mo, 3);
    }
    if (price6mo.disabled == true) {
        calculate_monthly(float_val, price6mo, 6);    
    }
}

// the N/A box next to a ranking paremeter was
// clicked
//
// element:         checkbox element
// edit_dom_id :    the dom id for the edit box
function stat_na_clicked(element, edit_dom_id) {

    var edit = document.getElementById(edit_dom_id);

    if (edit.disabled == false) {
        setCss(edit, 'blank_input');
    } else {
        setCss(edit, 'text_box');
    }
    edit.disabled = !edit.disabled;

}

// check all 
function TCheckAll () {
    this.box_dom_ids = new Array();
}

TCheckAll.prototype.addDomId = function(dom_id) {
    this.box_dom_ids[this.box_dom_ids.length] = dom_id;
}

TCheckAll.prototype.checkAll = function () {
    for (var key = 0; key < this.box_dom_ids.length; key++) {
        var c = document.getElementById(this.box_dom_ids[key]);
        c.checked = true;
    }
}

TCheckAll.prototype.uncheckAll = function () {
    for (var key = 0; key < this.box_dom_ids; key++) {
        var c = document.getElementById(this.box_dom_ids[key]);
        c.checked = false;
    }
}

/**********************************************************
 * CALENDAR CLASS
 *
 * show/hide the calendar and populate an edit box
 **********************************************************/
 
// calendar constructor
//
// box_dom_id: Id of an input box who's value will
//             be populated with the date 
function Calendar(box_dom_id) {
    this.id                 = box_dom_id;
    this.frame              = document.getElementById('calframe');
    this.calendarClosed     = true;
    this.month              = 2;
    this.day                = 5;
    this.year               = 2012;
}

// the calendar button was clicked, open or
// close it
Calendar.prototype.calendarClicked = function() {

    this.frame.style.width     = "200px";
    this.frame.style.height    = "200px";

    var boxX                   = cursor.x;
    var boxY                   = cursor.y;

    this.frame.style.top            = Math.abs(boxY) + "px";
    this.frame.style.left           = boxX + "px";
    this.frame.style.visibility     = (this.calendarClosed ? "visible" : "hidden");

    this.calendarClosed        = !this.calendarClosed;

    this.calendarRefresh();
}

// refresh the calendar with the PHP file to
// create a new calendar
Calendar.prototype.calendarRefresh = function() {

    if (this.month < 1) {
        this.month += 12;
        this.year--;
    }
    
    if (this.month > 12) {
        this.month -= 12;
        this.year++;
    }

    var ajax = new AjaxPlainHTML('', '/ajax/cal.php?month=' + this.month + '&year=' + this.year);
    var t = this;
    ajax.display = function(text) { t.displayCalendar(text); }
    ajax.Send();   
}

Calendar.prototype.displayCalendar = function(calendar_html) {

    murderChildren(this.frame);
    this.frame.innerHTML = calendar_html.toString();
    
    var t = this;
    
    // okay now set the click callbacks
    
    /** -- BUTTONS -- **/
    var next = document.getElementById('cal_next');
    next.onclick = function() {
        t.month ++;
        t.calendarRefresh();
    }
    var prev = document.getElementById('cal_prev');
    prev.onclick = function() {
        t.month --;
        t.calendarRefresh();
    }
    var close = document.getElementById('cal_close');
    close.onclick = function() { t.calendarClicked(); }
    
    var day_arr = new Array();
    
    /** -- DAY BUTTONS -- **/ 
    for (var x = 1; x <= 31; x++) {
        var d = document.getElementById('cal_day_' + x);

        if (d) {
            d.onclick = function() { t.dayClicked(this); } 
        }
    }
}

Calendar.prototype.dayClicked = function(day_element) {
    var day        = parseInt(day_element.innerHTML);

    var value      = padLeadingZeros(this.year, 4) + '-' + padLeadingZeros(this.month, 2) + '-' + padLeadingZeros(day, 2);
    var element    = document.getElementById(this.id);
    element.value  = value;
    this.calendarClicked();
}

function padLeadingZeros(value, number) {

    value = value.toString();
    var new_value = '';
    
    for (var x = value.length; x < number; x++) {
        new_value += '0';
    }
    new_value += value;
    return new_value;
}

/**
 Show billing information
 **/
function show_billing(billing_id) {
    var frame              = document.getElementById('calframe');
    frame.style.width     = "200px";
    frame.style.height    = "30px";

    var boxX                   = cursor.x;
    var boxY                   = cursor.y;

    frame.style.top            = Math.abs(boxY) + "px";
    frame.style.left           = boxX + "px";
    frame.style.visibility     = "visible";
    
    murderChildren(frame);
    
    var table = document.createElement('table');
    var tbody = document.createElement('tbody');
    var tr    = document.createElement('tr');
    
    // label
    var td1    = document.createElement('td');
    td1.setAttribute('style', 'font-size: 7pt; font-weight: bold; ');
    td1.appendChild(document.createTextNode('Key: '));    
    tr.appendChild(td1);
    
    // input box
    var td2    = document.createElement('td');    
    var key_in = createInputBox('key', '');
    key_in.setAttribute('size', '5');
    key_in.setAttribute('maxlength', '8');
    td2.appendChild(key_in);    
    tr.appendChild(td2);
    
    // submit button
    var td3    = document.createElement('td');
    var submit = document.createElement('input');
    submit.setAttribute('type', 'button');
    submit.setAttribute('value', 'Show');
    
    // submit the billing
    submit.onclick = function() {
        var ajax = new AjaxConnection;
        ajax.base_tag = 'TLAAdmin';
        ajax.processer = show_billing_done;
        ajax.billing_id = billing_id;
        ajax.request_type = 'post';
        ajax.addPostVar('billing_id', billing_id);
        ajax.addPostVar('key', key_in.value);
        ajax.Connect('/ajax/billing_numbers.php');
        frame.style.visibility = 'hidden';
    }
    
    setCss(submit, 'okay_button');
    td3.appendChild(submit);
    tr.appendChild(td3);
    
    // cancel button
    var td4    = document.createElement('td');
    var cancel = document.createElement('input');
    cancel.setAttribute('type', 'button');
    cancel.setAttribute('value', 'x');
    
    // close the window
    cancel.onclick = function() {
        frame.style.visibility = 'hidden';
    }
    
    setCss(cancel, 'cancel_button');
    td4.appendChild(cancel);
    tr.appendChild(td4);    
    
    tbody.appendChild(tr);
    table.appendChild(tbody);
    frame.appendChild(table);
}

function show_billing_done(root_node, ajax) {
    var num = '';
    var exp = '';
    for (var key = 0; key < root_node.childNodes.length; key++) {
        switch (root_node.childNodes[key].nodeName) {
            case 'Number':
                num = root_node.childNodes[key].firstChild.nodeValue;
            break;
            case 'Exp':
                exp = root_node.childNodes[key].firstChild.nodeValue;
            break;
        }
    }
    
    var td_number = document.getElementById('billing_number_' + ajax.billing_id);
    var td_expr   = document.getElementById('billing_expr_'   + ajax.billing_id);
    
    if (td_number) {
        murderChildren(td_number);
        td_number.appendChild(document.createTextNode(num));
    }
    
    if (td_expr) {
        murderChildren(td_expr);
        
        if (exp == '0000-00-00') {
            var s = document.createElement('span');
            s.setAttribute('style', 'color: #666666');
            s.appendChild(document.createTextNode('--'));
            td_expr.appendChild(s);
        } else {
            td_expr.appendChild(document.createTextNode(exp));
        }
    }

}

/***********************************************************************************
 * SearchFit Order Headers
 *
 * Display the searchfit order headers
 **********************************************************************************/
function SFOrderHeaders(tbody_dom, cart_id) {
    this.tbody_dom          = tbody_dom;
    this.cart_id            = cart_id;
    this.prev_dom           = null;
    this.next_dom           = null;
    this.alter              = false;
    this.per_page           = 15;
    this.current_shown      = 0;
}

SFOrderHeaders.prototype.setPageNav = function(prev_dom, next_dom) {
    this.prev_dom = prev_dom;
    this.next_dom = next_dom;
}

SFOrderHeaders.prototype.pageLinks = function() {
    if (this.prev_dom == null) return;
    var t = this;
    
    murderChildren(this.prev_dom);
    murderChildren(this.next_dom);

    if (this.page > 1) {
        
        var s = document.createElement('span');
        setCss(s, 'fakelink');
        s.onclick = function() { t.getPage(t.page - 1); } 
        s.appendChild(document.createTextNode('< Prev'));
        this.prev_dom.appendChild(s);  
    } 
    
    if (this.current_shown >= this.per_page) {
        var s2 = document.createElement('span');
        setCss(s2, 'fakelink');
        s2.onclick = function() { t.getPage(t.page + 1); } 
        s2.appendChild(document.createTextNode('Next >'));
        this.next_dom.appendChild(s2);  
    }
    
}

SFOrderHeaders.prototype.rowSpacing = function(count) {
    for (var x = 0; x < count; x++) {
        var tr = document.createElement('tr');
        if (this.alter) {
            setCss(tr, 'border_table_alter');
        }
        this.alter = !this.alter;
        for (var y = 0; y < 7; y++) {
            var td = document.createElement('td');
            var i = createImageDom('empty.gif', 'e');
            i.setAttribute('style', 'width: 20px; height: 14px');
            td.appendChild(i);
            tr.appendChild(td);
        }
        this.tbody_dom.appendChild(tr);
    }
}

SFOrderHeaders.prototype.getPage = function(page) {
    var loading = loadingRow(this.tbody_dom);
    murderChildren(this.tbody_dom);
    this.tbody_dom.appendChild(loading);
    
    this.rowSpacing(this.per_page - 1);
    
    var ajax        = new AjaxConnection;
    ajax.base_tag   = 'TLAAdmin';
    var t           = this;
    this.ajax       = ajax;
    this.page       = page;

    this.current_shown = 0;
    
    ajax.processer = function(root_node, ajax) { t.finished(root_node); }
    ajax.Connect("/ajax/sf-headers.php?" 
                 + (this.cart_id > 0 ? "cart_id=" + this.cart_id + "&" : '') 
                 + 'page=' + page + '&per_page' + this.per_page);  
}

SFOrderHeaders.prototype.eventOnLoad = function() {
    this.getPage(1);
}

SFOrderHeaders.prototype.finished = function(root_node) {
    var order_header_ret = null;
    var order_headers    = new Array();
    for (var key = 0; key < root_node.childNodes.length; key++) {
        if (root_node.childNodes[key].nodeName == 'OrderHeaderRet') {
            order_headers[order_headers.length] = root_node.childNodes[key];
        }
    }
    
    murderChildren(this.tbody_dom);
    this.alter = false;
    
    for (key in order_headers) {
        var order_header_ret = order_headers[key];
        for (var key = 0; key < order_header_ret.childNodes.length; key++) {
            var c = order_header_ret.childNodes[key];
            if (c.nodeName == 'OrderHeader') {
                this.createTableRow(
                    c, 
                    order_header_ret.attributes.getNamedItem('cartId').value,
                    order_header_ret.attributes.getNamedItem('cartName').value
                );
                this.current_shown ++;
            }
        }
    }
    this.rowSpacing(this.per_page - this.current_shown);
    this.pageLinks();
}

SFOrderHeaders.prototype.createTableRow = function(order_header, cart_id, cart_name) {
    
    var paid            = false;
    var status_level    = 0;
    
    var options = new Array ();
    options['ID']               = '';
    options['SearchFitOrderID'] = '';
    options['FirstName']        = '';
    options['LastName']         = '';
    options['Email']            = '';
    options['OrderDate']        = '';
    options['Total']            = 0.00;
    
    for (var key = 0; key < order_header.childNodes.length; key++) {
        var c = order_header.childNodes[key];
        if (c.nodeName == 'Paid') {
            paid = true;
        } else if (c.nodeName == 'OrderStatus') {
            status_level = c.attributes.getNamedItem('level').value;
        } else {
                
            if (c.firstChild) {
                if (c.nodeName == 'Total') {
                    var v = parseFloat(c.firstChild.nodeValue);
                    options[c.nodeName] = v.toFixed(2);
                } else {
                    options[c.nodeName] = c.firstChild.nodeValue;
                }
                
            }
        }
    }
    
    var tr  = document.createElement('tr');
    
    if (this.alter == true) {
        setCss(tr, 'border_table_alter');
    }
    this.alter = !this.alter;
    
    tr.setAttribute('style', 'cursor: pointer;');
    tr.onclick = function () {
        document.location.href = '/index.php/order/import/?sf_id=' + options['ID']
                                + '&cart_id=' + cart_id;
    }
    
    
    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');
    var td4 = document.createElement('td');
    var td5 = document.createElement('td');
    var td6 = document.createElement('td');
    var td7 = document.createElement('td');
    
    td1.setAttribute('align', 'center');
    td2.setAttribute('align', 'center');
    td3.setAttribute('align', 'center');
    
    td1.appendChild(document.createTextNode(options['SearchFitOrderID']));    
    td2.appendChild(document.createTextNode(options['OrderDate']));
    td3.appendChild(document.createTextNode(cart_name));
    td4.appendChild(document.createTextNode(options['FirstName'] + ' ' + options['LastName']));

    if (paid == false) {
        td5.appendChild(createImageDom('icon_paid_gray.gif', 'Not Paid'));
    } else {
        td5.appendChild(createImageDom('icon_paid.gif', 'Paid'));
    }
    td5.setAttribute('align', 'center');
    td6.setAttribute('align', 'center');
    td6.appendChild(createImageDom('status_level_' + status_level + '_icon.gif', 'Status'));
    
    td7.appendChild(document.createTextNode(options['Total']));
    
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);
    tr.appendChild(td4);
    tr.appendChild(td5);
    tr.appendChild(td6);
    tr.appendChild(td7);
    
    this.tbody_dom.appendChild(tr);
}

/**
 send update request to modern bill
 **/
function updateMBOrder(order_id, key, loading_dom) {
    this.order_id = order_id;
    this.key      = key;
    this.loading_dom = loading_dom;
    
    var t         = this;
    
    murderChildren(this.loading_dom);
    loadingRow(loading_dom);

    var ajax = new AjaxConnection;
    ajax.base_tag = 'TLAAdmin';
    ajax.processer = function(root_node, a) { t.doneUpdating(root_node); }
    ajax.request_type = 'post';
    ajax.addPostVar('order_id', order_id);
    ajax.addPostVar('key', key);
    ajax.Connect('/ajax/mb-sync-order.php');
    this.ajax   = ajax;
}

updateMBOrder.prototype.doneUpdating = function(root_node) {
    murderChildren(this.loading_dom);
    
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    td.setAttribute('align', 'center');
    td.setAttribute('style', 'background-color: #eeffee; border: 1px solid #999999');
    td.appendChild(createImageDom('icon_check.gif', 'Done'));
    td.appendChild(document.createTextNode(' Finished'));
    tr.appendChild(td);
    
    this.loading_dom.appendChild(tr);
}

function updateMBInvoice(invoice_id, loading_dom) {
    this.invoice_id = invoice_id;
    this.loading_dom = loading_dom;
    
    var t         = this;
    
    murderChildren(this.loading_dom);
    loadingRow(loading_dom);

    var ajax = new AjaxConnection;
    ajax.base_tag = 'TLAAdmin';
    ajax.processer = function(root_node, a) { t.doneUpdating(root_node); }
    ajax.request_type = 'post';
    ajax.addPostVar('invoice_id', invoice_id);
    ajax.Connect('/ajax/mb-sync-invoice.php');
    this.ajax   = ajax;
}

updateMBInvoice.prototype.doneUpdating = function(root_node) {
    murderChildren(this.loading_dom);
    
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    td.setAttribute('align', 'center');
    td.setAttribute('style', 'background-color: #eeffee; border: 1px solid #999999');
    td.appendChild(createImageDom('icon_check.gif', 'Done'));
    td.appendChild(document.createTextNode(' Finished'));
    tr.appendChild(td);
    
    this.loading_dom.appendChild(tr);
}

/**
 Link checker
 **/
 
function linkCheckList() {
    this.checkers = new Array();
    this.cur      = 0;
    this.status_okay = 0;
    this.status_failed = 0;
    this.status_dom_id = null;
}
linkCheckList.prototype.add = function(placement_id, dom) {    
    var lc = new linkChecker(placement_id, dom);
    this.addObj(lc);
}

linkCheckList.prototype.addObj = function(ob) {
    this.checkers[this.checkers.length ] = ob;
    var t = this;
    ob.completed = function() { t.checkList(); };
    ob.statusOkay = function() { t.statusOkay(); };
    ob.statusFail = function() { t.statusFail(); };
}

linkCheckList.prototype.statusOkay = function() {
    this.status_okay ++;
}

linkCheckList.prototype.statusFail = function() {
    this.status_failed ++;
}


linkCheckList.prototype.checkList = function() {       
    
    if (this.cur == 0) {
        for(var x = 0; x < this.checkers.length; x++) {
            murderChildren(this.checkers[x].response_dom);
        }
    }
    
    if (this.cur >= this.checkers.length) { 
        this.cur = 0;
        if (this.status_dom_id != null) {
            var c = document.getElementById(this.status_dom_id);
            if (c) {
                murderChildren(c);
                if (this.status_failed > 0) {
                    c.appendChild(createImageDom('icon_fail.gif', 'Failed'));
                    c.appendChild(document.createTextNode(' ' + this.status_failed + ' Failed'));
                } else {
                    c.appendChild(createImageDom('icon_check.gif', 'Success'));
                }                
            }
        }

        return; 
    } 
    this.checkers[this.cur].run();
    
    this.cur++;

    // status
    if (this.status_dom_id != null) {
        var c = document.getElementById(this.status_dom_id);
        if (c) {
            murderChildren(c);
            c.appendChild(createImageDom('loading.gif', 'loading'));
            c.appendChild(document.createTextNode(
                ' Checking ' + this.cur + ' of ' + this.checkers.length
            ));
        }
    }
}

linkCheckList.prototype.eventOnLoad = function () {
    this.checkList();
}
 
function linkChecker(placement_id, response_dom) {
    this.placement_id = placement_id;
    this.response_dom = response_dom;
    this.custom_prod  = false;
    this.custom_link  = false;
    this.custom_text  = false;
    this.completed    = function() { };
    this.statusOkay   = function() { };
    this.statusFail   = function() { };
    var ajax          = new AjaxConnection;
    var t             = this;
    this.ajax         = ajax;
    ajax.processer    = function(root_node, ajax) { t.done(root_node, false); };
    ajax.errorHandler = function(t, a) { t.errorHandler(t); } 
    ajax.base_tag     = 'TLAAdmin';
    this.css          = '';
    
}

linkChecker.prototype.errorHandler = function(text) {
    this.done(null, text);
}

linkChecker.prototype.custom = function(p_url, l_url, l_text) {
    this.custom_prod = p_url;
    this.custom_link = l_url;
    this.custom_text = l_text;
}

linkChecker.prototype.run = function() {
    murderChildren(this.response_dom);
    this.response_dom.appendChild(createImageDom('loading.gif', 'loading'));
    
    var parent = this.response_dom.parentNode;
    this.css    = parent.getAttribute('class');
    if (!this.css) {
        this.css = parent.getAttribute('className');
    }
    setCss(parent, 'loading_color');
    
    if (this.custom_prod != false) {
        this.ajax.Connect('/ajax/link_checker.php?product_url=' + 
                          escape(this.custom_prod) + '&link=' + escape(this.custom_link) +
                          '&text=' + escape(this.custom_text));
    } else {
        this.ajax.Connect('/ajax/link_checker.php?placement_id=' + this.placement_id);
    }
}

linkChecker.prototype.done = function(root_node, error_text) {
    
    var link_match  = false;
    var dom_match   = false;
    var path_match  = false;
    var text_match  = false;
    var title_match = false;
    var http_error  = false;
    var remote_error= false;
    var nofollow    = false;
    
    if (error_text != false) {
        remote_error = error_text;
    } else {
        for (var key = 0; key < root_node.childNodes.length; key++) {
            switch (root_node.childNodes[key].nodeName) {
                case 'LinkMatch': link_match = true; break;
                case 'LinkDomainMatch': dom_match = true; break;
                case 'LinkPathMatch': path_match = true; break;
                case 'LinkTextMatch': text_match = true; break;
                case 'LinkTitleMatch': title_match = true; break;
                case 'HTTPError': http_error = root_node.childNodes[key].firstChild.nodeValue; break;
                case 'RemoteError': remote_error = root_node.childNodes[key].firstChild.nodeValue; break;
                case 'LinkNoFollow': nofollow = true ; break;
            }
        }
    }
    
    murderChildren(this.response_dom);
    var parent = this.response_dom.parentNode;
    if (this.css) {
        setCss(parent, this.css);
    } else {
        parent.removeAttribute('class');
        parent.removeAttribute('className');
    }
        
    parent.setAttribute('style', '');
    var text = '';
    
    if (link_match == true && dom_match == true && path_match == true && text_match == true && title_match == true && nofollow == false) {
        this.response_dom.appendChild(createImageDom('icon_check.gif', 'Okay'));
        this.statusOkay();
        text = 'Okay';
    } else {
        this.statusFail();
        // something is bad
        if (link_match == true || dom_match == true || path_match == true || text_match == true) {
            img = createImageDom('icon_exclamation.gif', 'Error');
            text = 'Partial Match';
        } else {
            img = createImageDom('icon_fail.gif', 'FAIL');
            text = 'No Match';
        }

        var t = this;
        img.onmouseover = function() {
            t.showFailWindow(link_match ,dom_match, path_match,text_match,title_match, http_error, remote_error, nofollow);
        }
        img.onmouseout = function() {
            var cal = document.getElementById('calframe');
            cal.style.visibility = 'hidden';
        }

        this.response_dom.appendChild(img);
        
    }
    var s = document.createElement('span');
    s.setAttribute('style', 'visibility: hidden; display: none');
    s.appendChild(document.createTextNode(text));
    this.response_dom.appendChild(s);
    
    this.completed();
}

linkChecker.prototype.showFailWindow = function(link_match ,dom_match, path_match,text_match,title_match, http_error, remote_error, no_follow) {
    var frame = document.getElementById('calframe');
    
    if (frame.style.visibility != 'visible') {
        frame.style.width     = "300px";
        frame.style.height    = "150px";
    
        var boxX                   = cursor.x ;
        var boxY                   = cursor.y;
    
        frame.style.top            = Math.abs(boxY) + "px";
        frame.style.left           = boxX + "px";
        frame.style.visibility    = 'visible';
        
        murderChildren(frame);
        
        var ul = document.createElement('ul');

        if (remote_error != false) {
            var l = document.createElement('li');
            l.appendChild(document.createTextNode('Error: ' + remote_error));
            ul.appendChild(l);        
        } else if (http_error != false) {
            var l = document.createElement('li');
            l.appendChild(document.createTextNode('HTTP Error Code: ' + http_error));
            ul.appendChild(l);
        } else {        

            if (no_follow) {
                var l = document.createElement('li');
                l.appendChild(document.createTextNode(
                    'NoFollow exists in the page, check the links'
                ));
                ul.appendChild(l);
            }
            
            if (!link_match) {
                var l = document.createElement('li');
                l.appendChild(document.createTextNode('Full Link does not match'));
                ul.appendChild(l);
            }
            if (!dom_match) {
                var l = document.createElement('li');
                l.appendChild(document.createTextNode('Domain Name in the link does not match.'));
                ul.appendChild(l);
            }
            if (!path_match) {
                var l = document.createElement('li');
                l.appendChild(document.createTextNode('Path in the link does not match.'));
                ul.appendChild(l);
            }
            if (!text_match) {
                var l = document.createElement('li');
                l.appendChild(document.createTextNode('Link text does not match'));
                ul.appendChild(l);
            }
            if (!title_match) {
                var l = document.createElement('li');
                l.appendChild(document.createTextNode('Title parameter does not match'));
                ul.appendChild(l);
            }
        }
        frame.appendChild(ul);
    }
}


/** -- LINK EXPANSION -- **/
function showLinkPlacements(image_dom, link_id, row_dom_id) {
    
    this.row_dom_id = row_dom_id;
    this.link_id    = link_id;
    this.opened     = false;
    this.rows       = new Array();
    this.finishedLoading = function() { };
    this.image_dom  = image_dom;

    var t = this;
    image_dom.show_link_placements = this;
    image_dom.onclick = function() { t.open(); }         
}

showLinkPlacements.prototype.open = function() {
    if (this.opened == false) {
        var ajax = new AjaxConnection;
        var t = this;
        ajax.processer = function(root_node, aj) { t.done(root_node); } 
        ajax.base_tag = 'TLAAdmin';
        ajax.errorHandler = function(text, aj) { t.finishedLoading(); } 
        this.lr = loadingRow(document.getElementById(this.row_dom_id));
        ajax.Connect('/ajax/link-placements.php?link_id=' + this.link_id);
        this.image_dom.onclick = function() { t.close(); };
    } else {
        this.finishedLoading();
    }
}

showLinkPlacements.prototype.close = function() {
    for (key in this.rows) {
        var parent = this.rows[key].parentNode;
        parent.removeChild(this.rows[key]);
    }
    this.opened = false;
    this.rows = new Array();
    this.image_dom.setAttribute('src', '/html/images/plus.gif');
    var t = this;
    this.image_dom.onclick = function() { t.open(); };
    this.finishedLoading();
}

showLinkPlacements.prototype.done = function(root_node) {
    this.opened = true;
    
    var link_row = document.getElementById(this.row_dom_id);
    var tbody = link_row.parentNode;
    
    if (this.lr != null) {
        tbody.removeChild(this.lr);
        this.lr = null;
    }    
    this.image_dom.setAttribute('src', '/html/images/minus.gif');
    
    
    for (var x = 0; x < root_node.childNodes.length; x++) {
        var c = root_node.childNodes[x];
        switch (c.nodeName) {
            case 'Placement':
                this.placementRow(c);
            break;
        }
    }
    this.finishedLoading();
}

showLinkPlacements.prototype.placementRow = function(node) {

    var product_url = '';
    var status      = '';
    var activation  = '';
    var expiration  = '';
    var product_id  = '';
    
    var link_row = document.getElementById(this.row_dom_id);
    var tbody = link_row.parentNode;
    
    var next = link_row.nextSibling;
    for (var x = 0; x < node.childNodes.length; x++) {
        var c = node.childNodes[x];
        
        switch (c.nodeName) {
            case 'ProductURL': product_url = c.firstChild.nodeValue; break;
            case 'Status': status = c.firstChild.nodeValue; break;
            case 'Activation': activation = c.firstChild.nodeValue;break;
            case 'Expiration': expiration = c.firstChild.nodeValue; break;
            case 'ProductID': product_id = c.firstChild.nodeValue; break;
        }    
    }
    
    var tr = document.createElement('tr');

    setCss(tr, 'noborder');
    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');
    var td4 = document.createElement('td');
    var td5 = document.createElement('td');
    var td6 = document.createElement('td');
    
    if (product_id != '') {
        td4.onclick = function() { 
            document.location.href = '/index.php/product/view/' + product_id;
        };
        td4.style.cursor = 'pointer';
        
        td4.onmouseover = function () {
            this.style.color = '#0000ff';
            
        };
        td4.onmouseout = function () {
            this.style.color = '#000000';
        };
        
    }    
    
    tr.setAttribute('style', 'font-size: 8pt; background-color: #eaeaea');
    
    td1.appendChild(createImageDom('line.gif', 'line'));
    td6.appendChild(document.createTextNode(status));
    td4.appendChild(document.createTextNode(product_url));
    td5.appendChild(document.createTextNode(activation + ' / ' + expiration));
    tr.appendChild(td1);
    tr.appendChild(td2);
    tr.appendChild(td3);
    tr.appendChild(td4);
    tr.appendChild(td5);
    tr.appendChild(td6);
    td6.setAttribute('align', 'center');
    
    if (next) {
        tbody.insertBefore(tr, next);
    } else {
        tbody.appendChild(tr);
    }
    
    this.rows[this.rows.length] = tr;
}

/** DNS RESOLVER **/
function resolveDNS(product_id) {
    this.response_dom_id = response_dom_id;
    this.product_id      = product_id;
}

resolveDNS.prototype.eventOnLoad = function() {
    var img = createDomImage('loading.gif', 'loading');
    this.showFrame(img);
    var t    = this;
    
    img.onload = function() { 
        var ajax = new AjaxConnection;
        ajax.base_tag = 'TLAAdmin';
        ajax.processer = function(root_node, a) { t.done(root_node); }
        ajax.Connect('/ajax/resolve.php?product_id=' + this.product_id);
    }
}

resolveDNS.prototype.showFrame = function(dom) {
    var frame = document.getElementById('calframe');
    
    frame.style.width     = "200px";
    frame.style.height    = "150px";

    var boxX                   = cursor.x ;
    var boxY                   = cursor.y;

    frame.style.top            = Math.abs(boxY) + "px";
    frame.style.left           = boxX + "px";
    frame.style.visibility    = 'visible';
    
    murderChildren(frame);
    frame.appendChild(dom);
    var t = this;
    frame.onclick = function() { t.hideFrame(); }  
}

resolveDNS.prototype.hideFrame = function() {
    var frame = document.getElementById('calframe');
    frame.style.visibility    = 'hidden';
}

resolveDNS.prototype.done = function(root_node) {
    var text = '';
    for (var x = 0; x < root_node.childNodes.length; x++) {
        var c = root_node.childNodes[x];
        switch (c.nodeName) {
            case 'Address': 
                text =  c.firstChild.nodeValue;
            break;
            case 'ResolveFailed':
                text = 'Resolve Failed';
            break;
        }
    }
    this.showFrame(document.createTextNode(text));
}

/** -- EXPAND ALL -- **/
function ExpandAll(button_dom_id, close_dom_id) {
    this.items = new Array();
    this.ctr   = 0;
    this.button_dom_id = button_dom_id;
    this.close_dom_id = close_dom_id;
    this.stop = false;
}

ExpandAll.prototype.add = function(o) {
    this.items[this.items.length] = o;    
}

ExpandAll.prototype.expandAll = function() {     
    var cur = this.ctr;
    this.ctr++;
    var t = this;
    if (cur >= this.items.length || this.stop == true) {
        this.ctr = 0;
        if (this.parent) {
            murderChildren(this.parent);
            this.parent.appendChild(this.button_dom);
        }
        if (cur > 0) {
            this.items[cur - 1].finishedLoading = function() { };
        }
        var collapse = document.getElementById(this.close_dom_id);
        collapse.disabled = false;
        this.stop = false;
        return;
    }    
    if (cur == 0) {
        if (!this.button_dom) {
            this.button_dom = document.getElementById(this.button_dom_id);
        }   
        this.parent = this.button_dom.parentNode;             
        murderChildren(this.parent);
        this.parent.appendChild(createImageDom('loading.gif', 'Loading'));
        
        var stop_dom = createImageDom('icon_fail.gif', 'Stop');
        stop_dom.onclick = function() { t.stopLoading(); } 
        
        this.parent.appendChild(stop_dom);
        
        var collapse = document.getElementById(this.close_dom_id);
        collapse.disabled = true;
    }    
    if (cur > 0) {
        this.items[cur - 1].finishedLoading = function() { };
    }
    
    this.items[cur].finishedLoading = function() { t.expandAll(); }
    this.items[cur].open();
}

ExpandAll.prototype.collapseAll = function() {
    for (key in this.items) {
        this.items[key].close();
    }
}

ExpandAll.prototype.stopLoading = function() {
    this.stop = true;
}

/**********************************************************
 * Ajax Connection and callback functions
 **********************************************************/
function AjaxConnection() {
    this.http_request           = null;
    this.processer              = function (root_node, ajax) {};
    this.base_tag               = "bts";
    this.not_ready_callback     = function(response_code, aj) { };
    this.errorHandler           = function (text, aj) { alert(text); };
    this.errorTag               = "Error";
    this.request_type           = 'get';
    this.post_vars              = new Array();
};

/**********************************************************
AjaxConnection::addPostVar

Add a variable to post (if we are posting)
***********************************************************/

AjaxConnection.prototype.addPostVar = function(name, value) {
    this.post_vars[this.post_vars.length] = encodeURIComponent(name) + '=' + encodeURIComponent(value);
}


/**********************************************************
AjaxConnection::CreateAjax

Create the XMLHttpRequest class, with the evil evil switch
to see if IE supports it.
***********************************************************/
AjaxConnection.prototype.CreateAjax = function() {
    /*@cc_on @*/
    
    /*@if (@_jscript_version >= 5)
    try {
        this.http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            this.http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            this.http_request = null;
        }
    }
    @end @*/
    
    if (!this.http_request && typeof XMLHttpRequest != 'undefined') {
        this.http_request = new XMLHttpRequest();
    }

    if (!this.http_request) {
        this.errorHandler('Fatal Error: couldn\'t create AJAX request, old browser?, IE with ActiveX disabled?', this);
        return;
    }
    return this.http_request;
}

/**********************************************************
AjaxConnection::Connect

Connect to the inputted URL
***********************************************************/
AjaxConnection.prototype.Connect = function(url) {
    this.CreateAjax();
    if (this.http_request) {
        var listener = this;
        this.http_request.onreadystatechange = function() { listener.readyChange(); };
        
        this.http_request.open(this.request_type.toUpperCase(), url, true);
        
        if (this.request_type.toLowerCase() == 'post') {
            this.http_request.setRequestHeader('Content-Type', "application/x-www-form-urlencoded; charset=UTF-8");
            this.http_request.send(this.post_vars.join('&'));
        } else {
            this.http_request.send(null);
        }    
    }
}


/**********************************************************
AjaxConnection::handleEvent

Handles the onreadystatechange event
***********************************************************/
AjaxConnection.prototype.readyChange = function() {
    if (!this.http_request) {
        alert("request is still false");
        return;
    }

    if (this.http_request.readyState == 4) {
        if (this.http_request.status == 200) {
            var xmldoc = this.http_request.responseXML;            
            var root_node;
            
            if (!xmldoc || !xmldoc.firstChild) {
                this.errorHandler("Failed parsing XML Document", this);
                return;
            }
            
            // this works in mozilla, need to find the IE version
            root_node = xmldoc.firstChild;
            if (root_node.nodeName == "parsererror") {
                this.errorHandler(root_node.nodeName + "\n\n" + this.http_request.responseText, this);
                return;
            }
            
            // okay lets find out who we are supposed to contact
            
            root_node = xmldoc.getElementsByTagName(this.base_tag).item(0);

            if (!this.checkBtsAjaxError(root_node)) {
                return;
            }

            this.processer(root_node, this); 
            
        } else {
            this.errorHandler("Error connecting to Ajax, Reason: " + this.http_request.status, this);
        }
    } else {
        this.not_ready_callback(this.http_request.readyState, this);
    }    
}

/**********************************************************
AjaxConnection::checkBtsAjaxError

Checks and sees if there has been an error in the processing
of the command
***********************************************************/
AjaxConnection.prototype.checkBtsAjaxError = function(root_node) {
    if (!root_node) {
        this.errorHandler("Root Node Is Not Defined", this);
        return false;
    }
    
    var error = root_node.getElementsByTagName(this.errorTag).item(0);
    
    if (error && error.nodeName == this.errorTag) {
        if (error.firstChild) {
            this.errorHandler(error.firstChild.nodeValue, this);
        } else {
            this.errorHandler('error was sent by the ajax processor, but had no content', this);
        }
        return false;
    }
    
    var nologin = root_node.getElementsByTagName("nologin").item(0);
    
    if (nologin) {
        window.location.href = 'index.php';
        return false;
    }
    return true;
}

function AjaxPlainHTML(box_id, url) {
    this.box_id                 = box_id;
    var ajax                    = new AjaxConnection();
    this.a                      = ajax.CreateAjax();
    var listener                = this;
    this.a.onreadystatechange   = function() { listener.AjaxPlainHTMLDone() };
    this.url                    = url;    
    
    // standard display function, may be changed
    this.display                = function(text) {
        var frame = document.getElementById(listener.box_id);
        if (frame) {
            frame.innerHTML = text;
        }
    }    
}

AjaxPlainHTML.prototype.Send = function() { 
    this.a.open('GET', this.url, true);
    this.a.send(null);        
}

AjaxPlainHTML.prototype.AjaxPlainHTMLDone = function() {
    if (this.a.readyState == 4) {
        this.display(this.a.responseText);
    }
}

function murderChildren(element) {
    while (element.childNodes[0]) {
        element.removeChild(element.childNodes[0]);
    }
}
/***
 * product change all
 */
 
function ChangeAllInput () {    
    this.init();
}

ChangeAllInput.prototype = {
    STATUS:   "status",
    PR:       "google_rank",
    AL:       "alexa_rank",
    SELL:     "sell",
    IDX:      "indexed_pages",
    BL:       "backlink_count",
    SELL:     "sell",
    BUY:      "buy",
    elements: [ ],
    show_box: null,
    
    init:   function() { 
        
    },   
    
    register:    function(type, element) {
        if (!this.elements[type]) {
            this.elements[type]  = new Array;
        }
        this.elements[type].push(element); 
    },
    
    show:       function(type) {
        
        this.show_box = document.createElement('div');
        this.show_box.className         = 'calframe';
        document.body.appendChild(this.show_box);
        this.show_box.style.visibility  = 'visible';
        this.show_box.style.top         = cursor.y + "px";
        this.show_box.style.left        = cursor.x + "px";
        this.show_box.style.width       = "300px";
        this.show_box.style.height      = "300px";
     
        var ajax = new AjaxConnection;
        ajax.base_tag = 'TLAAdmin';
        var t    = this;
        
        ajax.processer = function(root_node, aj) {
            t.showDone(root_node); 
        }
        ajax.Connect('/ajax/box_contents_' + type + '.xml');   
        
    },
    
    showDone:   function (root_node) {
        if (root_node.attributes.getNamedItem('width')) {
            this.show_box.style.width = root_node.attributes.getNamedItem('width').value;
        }
        if (root_node.attributes.getNamedItem('height')) {
            this.show_box.style.height = root_node.attributes.getNamedItem('height').value;
        }

    
        xmlToDom(this.show_box, root_node, null);
        
    },
    
    makeChanges:    function(type, input_element) {
        
    }
    
};

var change_all_input = new ChangeAllInput;
/**
 * $Id: site.js.php,v 1.32 2008/05/14 22:11:20 bwilder Exp $
 */

function exportCSV(table_dom) {
    this.headings  = new Array();
    this.data      = new Array();    
}

exportCSV.prototype.run = function(dom) {
    for (var key = 0; key < dom.childNodes.length; key++) {
        var n = dom.childNodes[key];
        
        if (n.nodeName) {
            switch (n.nodeName.toLowerCase()) {
                case 'thead':
                    this.parseHeading(n);
                break;
                case 'tbody':
                    this.parseBody(n);
                break;
            }
        }
    }
	this.saveExport();
}

exportCSV.prototype.saveExport = function() {
	var ajax = new AjaxConnection;
	ajax.request_type = 'post';
	for (key in this.headings) {
		ajax.addPostVar('heading[]', this.headings[key]);
	}
	for (key in this.data) {
		ajax.addPostVar('row[]', this.data[key]);
	}
	ajax.base_tag  = 'TLAAdmin';
	var t = this;
	ajax.processer = function(root_node, ajax) { t.done_saving(root_node); } 
	ajax.Connect('/ajax/export.php');	
}
exportCSV.prototype.done_saving = function(root_node) {
	var ikey = '';
	for (var key = 0; key < root_node.childNodes.length; key++) {
		var c = root_node.childNodes[key];
		if (c.nodeName == 'Okay') {
			ikey = c.attributes.getNamedItem('key').value;
		}
	}
	window.location = '/ajax/get_export.php?key=' + ikey;
}

exportCSV.prototype.parseHeading = function(node) {  
    if (node.no_show_csv == true) return '';
    for (var key = 0; key < node.childNodes.length; key++) {
        var n = node.childNodes[key];
        if (n.nodeName) {
            switch (n.nodeName.toLowerCase()) {
                case 'tr':
                    this.headings[this.headings.length] = this.parseRow(n);
                break;
            } 
        }
    }

}

exportCSV.prototype.parseBody = function(node) {
    if (node.no_show_csv == true) return '';
    for (var key = 0; key < node.childNodes.length; key++) {
        var n = node.childNodes[key];
        if (n.nodeName) {
            switch (n.nodeName.toLowerCase()) {
                case 'tr':
                    this.data[this.data.length] = this.parseRow(n);
                break;
            } 
        }
    }
}

exportCSV.prototype.parseRow = function(node) {  
    var row = '';
    if (node.no_show_csv == true) return '';
    for (var key = 0; key < node.childNodes.length; key++) {
        var n = node.childNodes[key];
        if (n.nodeName) {
            switch (n.nodeName.toLowerCase()) {
                case 'td':
                case 'th':
                    row += this.childString(n) + ',';
                break;
            } 
        }
    }
    return row;
}

exportCSV.prototype.childString = function(node) {
    var text = '';
    if (node.no_show_csv == true) return '';
    for (var key = 0; key < node.childNodes.length; key++) {
        var c = node.childNodes[key];
        if (c.nodeType == 1) {
			if (c.nodeName.toLowerCase() == 'script') continue;
			
            text += this.childString(c);
        } else if (c.nodeType == 3 || c.nodeType == 4) {
            
            text += c.data;
        }
    }
    return text;
}
var curinstance;

function AjaxProgressBar(callback_url, parent_dom, image_path, width, height) {
    curinstance         = this;
    this.url            = callback_url;
    this.parent_dom     = parent_dom;
    this.width          = width;
    this.height         = height;
    this.image_path     = image_path;
    this.style          = 'border:1px solid black;height:' + height + 'px;width:' + width + 'px;text-align:left;background-color:#ffffff';
}

AjaxProgressBar.prototype = {
    
    interval_id:    null,
    check_every_ms: 1000, // 500 MS
    loading:        false,
    div:            null,
    image:          null,
    loading_img:    null,
    loading_img_box: null,
   
    onFinish:   function() {},
    
    ajax_loaded: function(root) {
         
        for (var x = 0; x < root.childNodes.length; x++) {
            var cur = root.childNodes[x];
            
            if (cur.nodeName == 'Done') {
                curinstance.done();
            } else if (cur.nodeName == 'Progress') {
                curinstance.update(cur.attributes.getNamedItem('percent').value);
            } else if (cur.nodeName == 'Exec') {
                // Execute Javascript Code
                var code = '';
                var jsn  = null;
                for (var y = 0; y < cur.childNodes.length; y++) {
                    jsn = cur.childNodes[y];
                    // text nodes only
                    if (jsn.nodeType == 3 || jsn.nodeType == 4) {
                        code += jsn.nodeValue;
                    }
                }
                // execute the passed code
                if (code != '') {
                    eval(code);
                }
            }     
        }
    },    
    
    done:       function() {
        this.update(100);
        clearInterval(this.interval_id);
        this.loading = false;
        if (this.loading_img && this.loading_img.src) {
            this.loading_img.src = this.image_path + '/icon_check.gif';
        }
        this.onFinish();
    },
    
    start:      function() {
        var t = this;
        this.update(0);
        this.interval_id = setInterval(function() { t.tick(); }, this.check_every_ms);
    },
    
    tick:       function() {
        if (this.loading == true) { return; }
        this.loading = true;
        var new_url = this.url;
        if (this.url.match(/\?/)) {
            new_url += '&' + (new Date).getTime();
        } else {
            new_url += '?' + (new Date).getTime();
        }
        
        var ajax = new AjaxConnection;
        ajax.base_tag = 'Bar';
        ajax.processer = this.ajax_loaded;
        ajax.Connect(new_url);
           
    }, 
    
    update:     function(percent) {
        if (this.div == null) {
            if (document.createElementNS && document.body.namespaceURI) {
                this.div = document.createElementNS(document.body.namespaceURI, 'html:div');
            } else {
                this.div = document.createElement('div');
            }
            this.div.style.cssText = this.style;
            this.parent_dom.appendChild(this.div);
        }
        
        if (this.loading_img == null && this.loading_img_box != null) {
            if (document.createElementNS && document.body.namespaceURI) {
                this.loading_img = document.createElementNS(document.body.namespaceURI, 'html:img');
            } else {
                this.loading_img = document.createElement('img');
            }
            this.loading_img.src = this.image_path + 'anim_indicator_small.gif';
            this.loading_img_box.appendChild(this.loading_img);
        } else {
            this.loading_img.src = this.image_path + 'anim_indicator_small.gif';
        }
        
        if (this.img == null) {
            if (document.createElementNS && document.body.namespaceURI) {
                this.img = document.createElementNS(document.body.namespaceURI, 'html:img');
            } else {
                this.img = document.createElement('img');
            }
            this.img.style.height = this.height + 'px';
            this.img.src = this.image_path + 'anna_progress.gif';
            this.div.appendChild(this.img);
        }
        
        this.loading = false;
        this.img.style.width = Math.floor((percent / 100) * this.width) + 'px';
    } 
};

