// invotex.js

var verbose = true;
var searchresults_open = false;
var tableWidget_okToSort = true;
var tableWidget_arraySort = new Array();
tableWidget_tableCounter = 1;
var activeColumn = new Array();
var currentColumn = false;
var miniwaiting = false;

function dbg(namespace, variable)
{
	var url = "lib/ajax_debug.php?ns=" + namespace + "&var=" + variable;
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(req) {
			new Insertion.Top('pageBody', '<div id="debugpanel" onclick="$(\'debugpanel\').remove();" style="border:1px solid #000; font-size:9px; font-family:Arial; position:absolute; top:0px; left:0px; text-align:left; z-index:250; background-color:#fff; padding:10px;">' + req.responseText + '</div>');
		}
	});
}

function SelectAllRecords(boolVal, r)
{
    var arr = new Array();

    // http://groups.google.com/group/prototype-scriptaculous/browse_thread/thread/4f6bd8f4d65b6301/298eb48eea28105d
    // states that you must wrap $A() around getElementsByClassName() for .each to work in some browsers (FF3+)
    var chex = $A($('tb_info').getElementsByClassName('TBL_CHKBX'));

    if (boolVal) {
        chex.each(function(s) {
            arr = s.id.split('_');
            var url = "lib/ajax_cart.php?action=addRecord&record=" + arr[1] + "&r=" + r;
    		new Ajax.Request(url, {
    			method: 'get',
    			onSuccess: function(req) {
    				eval(req.responseText);
    				s.checked = true;
    			}
    		});
        });
    } else {
        chex.each(function(s) {
            arr = s.id.split('_');
            var url = "lib/ajax_cart.php?action=removeRecord&record=" + arr[1] + "&r=" + r;
    		new Ajax.Request(url, {
    			method: 'get',
    			onSuccess: function(req) {
    				eval(req.responseText);
    				s.checked = false;
    			}
    		});
        });
    }
}

function addRecord(elem, record, r)
{
    if (elem.checked == true) {
		var url = "lib/ajax_cart.php?action=addRecord&record=" + record + "&r=" + r;
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(req) {
				eval(req.responseText);
			}
		});
    } else {
		var url = "lib/ajax_cart.php?action=removeRecord&record=" + record + "&r=" + r;
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(req) {
				eval(req.responseText);
			}
		});
    }
}


function emptyCart()
{

    input_box=confirm("Are you sure you would like to remove all the items from the Cart?\nClick OK to empty cart.");
    if (input_box==true) {
        var url = "lib/empty_cart.php";
        window.location = url;
    }
}


function removeRecordFromCart(record, r)
{

    input_box=confirm("Are you sure you would like to remove this item from the Cart?\nClick OK to remove item.");
    if (input_box==true) {
        var url = "lib/remove_cart.php?action=removeRecord&record=" + record + "&r=" + r + "&forward=cart.htm";
        window.location = url;
    }
}

function removeRecordFromPurchase(record, r)
{

    input_box=confirm("Are you sure you would like to remove this item from your purchase?\nClick OK to remove item.");
    if (input_box==true) {
         var url = "lib/remove_cart.php?action=removeRecord&record=" + record + "&r=" + r + "&forward=purchase.htm";
         window.location = url;
    }
}





function autocomplete (elem, div, evt)
{
	if ($R(48,57).include(evt.keyCode) || $R(65,90).include(evt.keyCode)) {
//		alphanumeric
		new Ajax.Autocompleter(elem, div, 'lib/ajax_search.php');
	}
}

function doKeywordSearch(textelem, r)
{

    wait('wait_searchresults');
	if (searchresults_open == false){
		new Effect.Appear('searchboxresults');
		searchresults_open = true;
		$('searchbox').setStyle({border:'none'});
	}
	var url = "lib/ajax_submitsearch.php?phrase=" + escape($F(textelem)) + "&r=" + r;
	new Ajax.Request(url, {
		method: 'post',
		onSuccess: function(req) {
			unwait('wait_searchresults');
			eval(req.responseText);
		},
		onFailure: function(req) {
			unwait('wait_searchresults');
			alert('There was a problem processing your request.');
		}
	});
}

function doKeywordSearch2(textelem, r)
{   var keyword = escape($F(textelem));
    if (keyword == ""){
		alert("Please enter a Keyword to search on.");
        return;
    }
    var url = "search_results.htm?phrase=" + keyword;
	window.location = url;
}

function showCart()
{
    var url = "cart.htm";
	window.location = url;
}

function wait(elem)
{
	Try.these(function() {$('searchresults_tbl').remove();}, function() {return true;});
	$(elem).ancestors()[0].setStyle({backgroundColor:'#f0f0f0'});
	$(elem).show();
}
function unwait(elem)
{
	$(elem).hide();
	$(elem).ancestors()[0].setStyle({backgroundColor:'#fff'});
	searchresults_open = false;
}


function validateAdvancedSearchForm(){
    document.body.style.cursor = 'wait';

    var testDate;
    var errorNotFound = true;
    var errorString = "";
    var licensor = document.advancedsearch.licensor.value;
    var property = document.advancedsearch.property.value;
    var patent = document.advancedsearch.patent.value;
    var beginDate = document.advancedsearch.beginDate.value;
    var endDate = document.advancedsearch.endDate.value;
    var sic = document.advancedsearch.elements['sic[]'].value;
    var naics = document.advancedsearch.elements['naics[]'].value;

    if (patent ==  "" && property == "" && licensor == "" && beginDate == "" && endDate == ""&& sic == "" && naics == ""){
        errorNotFound = false
        errorString = "Please enter at least 1 item to search.";
    }

    // validate begin date
    testDate = isDate(beginDate,true,"Begin Date");
    if (testDate!=true){
        document.advancedsearch.beginDate.focus()
        errorNotFound = false
        errorString = errorString + "\n"+ testDate;
    }

    // validate end date

    testDate = isDate(endDate,true,"End Date");
    if (testDate!=true){
        document.advancedsearch.endDate.focus()
        errorNotFound = false
        errorString = errorString + "\n"+ testDate;
    }


    if (errorNotFound == false) {
        alert(errorString);
        document.body.style.cursor = 'default';

    }
    return errorNotFound
}


function addTax() {
    var state = document.purchase.state.value;
    var sub = parseFloat(document.purchase.subtotal.value);
    if (state == "DC") {
        var tax = sub * .0575;
        //alert(tax);
        var total = (sub + tax);
        document.purchase.tax.value = tax;
        document.purchase.totamount.value = total;
        var taxhtml = document.getElementById("tax");
        taxhtml.innerHTML = "$" + addCommas(String(tax.toFixed(2)));
        var totprice = document.getElementById("totprice");
        totprice.innerHTML = "$" + addCommas(String(total.toFixed(2)));
    } else {
        document.purchase.tax.value = 0;
        document.purchase.totamount.value = sub;
        var taxhtml = document.getElementById("tax");
        taxhtml.innerHTML = "$" + 0.00
        var totprice = document.getElementById("totprice");
        totprice.innerHTML = "$" + addCommas(String(sub.toFixed(2)));

    }

}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}



function validatePurchaseForm(){
    document.body.style.cursor = 'wait';
    addTax();

    var errorNotFound = true;
    var errorString = "Please correct the following errors:";
    var fname = document.purchase.fname.value;
    var lname = document.purchase.lname.value;
    var ctype = document.purchase.ctype.value;
    var cnumber = document.purchase.cnumber.value;
    var expiration_year = document.purchase.expiration_year.value;
    var expiration_month = document.purchase.expiration_month.value;
    var cid = document.purchase.cid.value;
    var addr1 = document.purchase.addr1.value;
    var city = document.purchase.city.value;
    var zip = document.purchase.zip.value;
    var state = document.purchase.state.value;
    var country = document.purchase.country.value;
    var region = document.purchase.region.value;


    var termsagree = getCheckedValue(document.purchase.termsagree);


    if (termsagree != "yes") {
        alert("To continue, Please accept the terms & conditions");
        document.body.style.cursor = 'default';
        return false;
    }

    // validate first name
    if (fname == ""){
        document.purchase.fname.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please enter the first name on the card.";
    }

    // validate last name
    if (lname == ""){
        document.purchase.lname.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please enter the last name on the card.";
    }

    // validate card type
    if (ctype == "NULL"){
        document.purchase.ctype.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please select the type of card.";
    }

    // validate card number
   if (cnumber == ""){
        document.purchase.cnumber.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please enter the card number.";
    }

   // validate exp date
   if (expiration_month == ""){
        document.purchase.expiration_month.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please enter the card expiration month.";
    }

    // validate exp date
   if (expiration_year == ""){
        document.purchase.expiration_year.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please enter the card expiration year.";
    }

   // validate cid
   if (cid == ""){
        document.purchase.cid.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please enter the card cid number.";
    }

   // validate address 1
   if (addr1 == ""){
        document.purchase.addr1.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please enter the Billing Address";
    }

   // validate city
   if (city == ""){
        document.purchase.city.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please enter the Billing City";
    }

   // validate country
   if (country == ""){
        document.purchase.country.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please enter the Billing Country";
    }


   // validate state / country / region
   if (country == "United States"){
     if (state == ""){
           document.purchase.state.focus()
            errorNotFound = false
            errorString = errorString + "\n"+  "Please enter the Billing State";
     }
   } else  {
     if (region == ""){
           document.purchase.region.focus()
           errorNotFound = false
           errorString = errorString + "\n"+  "Please enter the Billing Region";
     }

   }

   // validate zip
   if (zip == ""){
        document.purchase.zip.focus()
        errorNotFound = false
        errorString = errorString + "\n"+  "Please enter the Billing Zip Code";
    }


    if (errorNotFound == false) {
        alert(errorString);
        document.body.style.cursor = 'default';

    }
    return errorNotFound;
}



function sortNumeric(a,b){
	a = a.replace(/,/,'.');
	b = b.replace(/,/,'.');
	a = a.replace(/[^\d\.\/]/g,'');
	b = b.replace(/[^\d\.\/]/g,'');
	if(a.indexOf('/')>=0)a = eval(a);
	if(b.indexOf('/')>=0)b = eval(b);
	return a/1 - b/1;
}


function sortString(a, b) {

  if ( a.toUpperCase() < b.toUpperCase() ) return -1;
  if ( a.toUpperCase() > b.toUpperCase() ) return 1;
  return 0;
}

function sortTable()
{
	if(!tableWidget_okToSort)return;
	tableWidget_okToSort = false;
	/* Getting index of current column */
	var obj = this;
	var indexThis = 0;
	while(obj.previousSibling){
		obj = obj.previousSibling;
		if(obj.tagName=='TD')indexThis++;
	}

	if(this.getAttribute('direction') || this.direction){
		direction = this.getAttribute('direction');
		if(navigator.userAgent.indexOf('Opera')>=0)direction = this.direction;
		if(direction=='ascending'){
			direction = 'descending';
			this.setAttribute('direction','descending');
			this.direction = 'descending';
		}else{
			direction = 'ascending';
			this.setAttribute('direction','ascending');
			this.direction = 'ascending';
		}
	}else{
		direction = 'ascending';
		this.setAttribute('direction','ascending');
		this.direction = 'ascending';
	}

	var tableObj = this.parentNode.parentNode.parentNode;
	var tBody = tableObj.getElementsByTagName('TBODY')[0];

	var widgetIndex = tableObj.getAttribute('tableIndex');
	if(!widgetIndex)widgetIndex = tableObj.tableIndex;

	if(currentColumn)currentColumn.className='';
	document.getElementById('col' + widgetIndex + '_' + (indexThis+1)).className='highlightedColumn';

	var coltag = 'col' + widgetIndex + '_' + (indexThis+1);
	currentColumn = document.getElementById(coltag);

	if ($('sortimg') != undefined) {
	    $('sortimg').remove();
	}
    var imgtd = coltag + '_td';
	var img = '<img style="margin-top:3px;" id="sortimg" src="images/icons/' + this.direction + '.gif" width="12px" height="12px" />';
    new Insertion.Bottom(imgtd, img);
	var sortMethod = tableWidget_arraySort[widgetIndex][indexThis]; // N = numeric, S = String
	if(activeColumn[widgetIndex] && activeColumn[widgetIndex]!=this){
		if(activeColumn[widgetIndex])activeColumn[widgetIndex].removeAttribute('direction');
	}

	activeColumn[widgetIndex] = this;

	var cellArray = new Array();
	var cellObjArray = new Array();
	for(var no=1;no<tableObj.rows.length;no++){
		var content= tableObj.rows[no].cells[indexThis].innerHTML+'';
		cellArray.push(content);
		cellObjArray.push(tableObj.rows[no].cells[indexThis]);
	}

	if(sortMethod=='N'){
		cellArray = cellArray.sort(sortNumeric);
	}else{
		cellArray = cellArray.sort(sortString);
	}

	if(direction=='descending'){
		for(var no=cellArray.length;no>=0;no--){
			for(var no2=0;no2<cellObjArray.length;no2++){
				if(cellObjArray[no2].innerHTML == cellArray[no] && !cellObjArray[no2].getAttribute('allreadySorted')){
					cellObjArray[no2].setAttribute('allreadySorted','1');
					tBody.appendChild(cellObjArray[no2].parentNode);
				}
			}
		}
	}else{
		for(var no=0;no<cellArray.length;no++){
			for(var no2=0;no2<cellObjArray.length;no2++){
				if(cellObjArray[no2].innerHTML == cellArray[no] && !cellObjArray[no2].getAttribute('allreadySorted')){
					cellObjArray[no2].setAttribute('allreadySorted','1');
					tBody.appendChild(cellObjArray[no2].parentNode);
				}
			}
		}
	}

	for(var no2=0;no2<cellObjArray.length;no2++){
		cellObjArray[no2].removeAttribute('allreadySorted');
	}

	tableWidget_okToSort = true;


}

function initSortTable(objId,sortArray)
{
	var obj = document.getElementById(objId);
	obj.setAttribute('tableIndex',tableWidget_tableCounter);
	obj.tableIndex = tableWidget_tableCounter;
	tableWidget_arraySort[tableWidget_tableCounter] = sortArray;
	var tHead = obj.getElementsByTagName('THEAD')[0];
	var cells = tHead.getElementsByTagName('TD');
	for(var no=0;no<cells.length;no++){
		if(sortArray[no]){
			cells[no].onclick = sortTable;
		}else{
			cells[no].style.cursor = 'default';
		}
	}
	for(var no2=0;no2<sortArray.length;no2++){	/* Right align numeric cells */
		if(sortArray[no2] && sortArray[no2]=='N')obj.rows[0].cells[no2].style.textAlign='right';
	}

	tableWidget_tableCounter++;
}

function submitSearchNow(event, r)
{
    if (event.keyCode == Event.KEY_RETURN) {
        doKeywordSearch2('searchbox_compact_txt', r);
    }
}

function sortAlpha(waitLoc, comboBox, r)
{
    miniwait(waitLoc);
	var url = "lib/ajax_sort.php?elem=" + comboBox + "&sort=alpha&r=" + r;
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(req) {
			eval(req.responseText);
			miniunwait();
		},
		onFailure: function(req) {
			miniunwait();
			alert('There was a problem processing your request.');
		}
	});
}

function sortNum(waitLoc, comboBox, r)
{
    miniwait(waitLoc);
	var url = "lib/ajax_sort.php?elem=" + comboBox + "&sort=numeric&r=" + r;
	new Ajax.Request(url, {
		method: 'get',
		onSuccess: function(req) {
			eval(req.responseText);
			miniunwait();
		},
		onFailure: function(req) {
			miniunwait();
			alert('There was a problem processing your request.');
		}
	});
}

function miniwait(elem)
{
    if (!miniwaiting) {
        new Insertion.After(elem, '<img id="wait_mov" src="images/loading.gif" height="10px" width="10px" />');
        miniwaiting = true;
    } else {
        miniunwait();
        miniwait(elem);
    }
}

function miniunwait()
{
    $('wait_mov').remove();
    miniwaiting = false;
}

function clearAdvancedSearch()
{
//	new Ajax.Request("lib/ajax_clear_advanced_search.php", {
//		method: 'get',
//		onSuccess: function(req) {
//		    eval(req.responseText);
//		}
//	});
}

function checkValidDate(elem)
{
    var year = new Date().getFullYear();
    var dateisvalid = false;
    var dt = elem.value;
    var sp = dt.split('/');
    if (sp.length == 3) {
        if ($R(1,12).include(Number(sp[0]))) {
            if ($R(1,31).include(Number(sp[1]))) {
                if ($R(1,year).include(Number(sp[2]))) {
                    dateisvalid = true;
                }
            }
        }
    }

    if (!dateisvalid && dt.length > 0) {
        new Effect.Highlight(elem);
        elem.clear();
        alert("Please choose a valid date on MM/DD/YYYY format");
    }
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function chkDupEml()
{
    if (!($F('email') == $F('email2'))) {
        alert('Your emails did not match.  Please re-enter.');
        return false;
    }
    if (!($F('password') == $F('repassword'))) {
        alert("Passwords do not match");
        return false;
    }
    return true;
}