var newwin ='';
var old_amount = '0.00'; 

/*
 *
 * Sets/unsets the pointer in browse mode
 *
 * @param   object   the table row
 * @param   object   the color to use for this row
 *
 * @return  boolean  whether pointer is set or not
 */
 
function setPointer(theRow, thePointerColor)
{
    if (typeof(theRow.style) == 'undefined' || typeof(theRow.cells) == 'undefined') {
    	return false;
    }

    var row_cells_cnt           = theRow.cells.length;
    for (var c = 0; c < row_cells_cnt; c++) {
        	theRow.cells[c].bgColor = thePointerColor;
    }

    return true;
} // end of the 'setPointer()' function


function setPointer2(theRow,classn)
{
	if (typeof(theRow.style) == 'undefined') {
        return false;
    }
    
    /*
    if (typeof(theRow.style) == 'undefined' || typeof(theRow.cells) == 'undefined') {
        return false;
    }

    var row_cells_cnt           = theRow.cells.length;
    for (var c = 0; c < row_cells_cnt; c++) {
        	theRow.cells[c].bgColor = thePointerColor;
    }*/
    
    theRow.className = classn;
}

function sure()
{
	return confirm('Are you sure you would like to remove this?');
}
function newWd(mode,company) {
	var hide_search = 0;
	
	if (newWd.arguments.length == 3) {
		hide_search = newWd.arguments[2];
	}
	
    newwin = window.open('search.php?mode='+mode+'&search='+company+'&hide_search='+hide_search, 'Search', 'screenX=20,screenY=20,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=500,height=350'); 
	newwin.focus();
} 
function addContact(company_id) {
	var hide_search = 0;
	
	if (addContact.arguments.length == 3) {
		hide_search = addContact.arguments[2];
	}
	
    newwin = window.open('q_contacts.php?action=add&company_id=' +company_id + '&hide_menu=true&pop_up=1','Add', 'screenX=20,screenY=20,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=500,height=350'); 
	newwin.focus();
} 


function newPDFWd(id,type)
{	
	if (type == 'quote'){
		if(confirm('Have you remembered to add installation, taxes, promotions, and service charges?')){
    		newwin = window.open('q_pdf.php?id='+id+'&action=show','pdf'); 
    		newwin.focus();
		}
	}
	else if (type == 'order'){
    		newwin = window.open('q_pdf.php?id='+id+'&action=show_order','pdf'); 
    		newwin.focus();
		}
	
	return;
}

function exportCSV(id)
{

	if(confirm('Have you remembered to add installation, taxes, promotions, and service charges?')){
   		newwin = window.open('q_pdf.php?id='+id+'&action=export_to_csv','csv'); 
   		newwin.focus();
	}
	else
		return false;


}

function fillDateRange(range)
{
	if (range.value=='today'){
		document.searchFrm.start_date.value = document.searchFrm.tod.value;
		document.searchFrm.end_date.value = document.searchFrm.tod.value;
	}
	if (range.value=='yesterday'){
		document.searchFrm.start_date.value = document.searchFrm.yes.value;
		document.searchFrm.end_date.value = document.searchFrm.yes.value;
	}
	if (range.value=='last_7'){
		document.searchFrm.start_date.value = document.searchFrm.lst7.value;
		document.searchFrm.end_date.value = document.searchFrm.tod.value;
	}	
	if (range.value=='month'){
		document.searchFrm.start_date.value = document.searchFrm.mnth.value;
		document.searchFrm.end_date.value = document.searchFrm.tod.value;
	}	
	if (range.value=='last_month'){
		document.searchFrm.start_date.value = document.searchFrm.start_last_month.value;
		document.searchFrm.end_date.value = document.searchFrm.end_last_month.value;
	}
	if (range.value=='all'){
		document.searchFrm.start_date.value = '';
		document.searchFrm.end_date.value = '';
	}
	return;
}
function checkAndSet(frmFld,type)
{	
	if(type =='tax_%' )
		places = 3;
	if(type =='tax_$' )
		places = 2;
	if(type =='discount_%' )
		places = 3;
	if(type =='discount_$' )
		places = 2;

	if (checkAmount(frmFld,places))
		setDiscount(type);
}

function setDiscount(type)
{
	if(type =='tax_%' )
		document.quoteform['info[tax_amount]'].value = '0.00';
	if(type =='tax_$' )
		document.quoteform['info[sales_tax_pct]'].value = '0.00';	
	if(type =='discount_%' )
		document.quoteform['info[discount_amount]'].value = '0.00';
	if(type =='discount_$' )
		document.quoteform['info[discount_pct]'].value = '0.00';	
		
}

function checkAmount(frmFld)
{	

	var places = 2;
	if(checkAmount.arguments.length > 1)
		places = checkAmount.arguments[1];
	if (!validateDollars(frmFld.value)) {
		frmFld.value = '0.00';
		alert("Invalid Amount");
		return false;
	}
	else {
		frmFld.value = dollars(frmFld.value,places);
		if ((frmFld.name.indexOf('[US1]') > 0 ||
			frmFld.name.indexOf('[MSRP]') > 0 ||
			frmFld.name.indexOf('[toss_rebate]') > 0 ||
			frmFld.name.indexOf('[discount]') > 0 ||
			frmFld.name.indexOf('[markup]') > 0) &&
			frmFld.name.indexOf('new_details') < 0 &&
			frmFld.name.indexOf('info') < 0
			
			) {
			
			var frm = frmFld.form;
			var formulaFld = frm[frmFld.name.replace(/US1|MSRP|toss_rebate|discount|markup/g,"formula")];
			
			var fieldPrefix = 'details';
			
			var line_no = formulaFld.name.substr(fieldPrefix.length + 1);
			line_no = line_no.substr(0,line_no.indexOf(']'));
			
			fieldPrefix += '[' + line_no + ']';
			
			//alert(fieldPrefix);
			var netPriceFld = frm[fieldPrefix + '[net_price]'];
			
			var msrp = frm[fieldPrefix + '[MSRP]'].value;
			var us1 = frm[fieldPrefix + '[US1]'].value;
			var discount = frm[fieldPrefix + '[discount]'].value;
			var toss_rebate = frm[fieldPrefix + '[toss_rebate]'].value;
			var markup = frm[fieldPrefix + '[markup]'].value;
			
			var netPrice = 0;
			
			switch (formulaFld.selectedIndex) {
				case 0: // MSRP
					netPrice = getNetPrice('msrp',msrp,us1,discount,toss_rebate,markup);
					break;
				case 1: // US1
					netPrice = getNetPrice('us1',msrp,us1,discount,toss_rebate,markup);
					break;
			}
			
			netPriceFld.value = netPrice;
			checkAmount(netPriceFld);
		}
		
		return true;
	}
}

// round to 2 decimal places
function dollars(x) 
{	
	var places = 2;
	var zeroes='';
	var amount;
	var roundto;
	if(dollars.arguments.length > 1)
		places = dollars.arguments[1];
	for(var i=0; i < places ;i++){
		zeroes +='0' 
	}
	roundto = parseInt(1 + zeroes);
	// round number
	amount = Math.round(x*roundto)/roundto;
	// convert to string
	amount = amount.toString();
	// get position of decimal
	dPlace = amount.indexOf('.',0);
	

	if (dPlace == -1)  // no decimal found
		return amount + '.' + zeroes;
		//return amount + '.00';
	else {
		decimals = amount.substring(dPlace+1,amount.length);	
		if (decimals.length == places)
			return amount;
		else
			return amount + '0';
	}
}

function validateDollars(string) 
{
    if (!string) return false;
    var chars = "0123456789.";
    
    for (var i = 0; i < string.length; i++) {
       if (chars.indexOf(string.charAt(i)) == -1)
          return false;
    }
    return true;
}

function submit_detail_form(action)
{
	var submit_bool;
	document.details_form.action.value = action;
	if (action == 'delete_request')
		submit_bool = confirm('By clicking "OK" you will delete this RFQ from your list, if you do not want to delete this RFQ please click "CANCEL".');
	if (action == 'update_request_details')
		submit_bool = confirm('Click OK to update all line items for the quote or click CANCEL to go back. Keep in mind that by clicking OK a new request will be issued and it will not delete your old RFQ, you may delete past RFQs at a later point');
	if (submit_bool)
		document.details_form.submit();	
	else return false;	
}

function fillDiscount(param_markup,param_us1,param_rebate,param_net)
{
	
	//var markup = ((parseFloat(document.detailform['info[markup]'].value)/100)+1);
	//var us1 = parseFloat(document.detailform['info[US1]'].value);
	//var toss_rebate = parseFloat(document.detailform['info[toss_rebate]'].value);

	var markup = ((parseFloat(param_markup.value)/100));
	var us1 = parseFloat(param_us1.value);
	var toss_rebate = parseFloat(param_rebate.value);

	
	
	
	param_net.value = dollars(((us1 - toss_rebate)*markup) + (us1 - toss_rebate));

	
	if (param_net.value < 0){
		alert('The Net Price can not be a negative dollar value');
		param_rebate.value = '0.00';
		param_net.value = dollars(((markup)*us1) + us1);
	}
}

function checkPassword(){
	if(document.contactform['info[password]'].value==document.contactform.password.value)
		return true;
	else{
		alert('password confirmation does not match ');
		return false;
	}		
}

function setQuantity(row){
	if(document.prodFrm['details['+row+'][quantity]'].value < 1 && document.prodFrm['details['+row+'][selected]'].checked)
		document.prodFrm['details['+row+'][quantity]'].value = 1;
	if(!document.prodFrm['details['+row+'][selected]'].checked )
		document.prodFrm['details['+row+'][quantity]'].value = 0;
}
function selectLine(row){
	if(document.prodFrm['details['+row+'][quantity]'].value > 0 )
		document.prodFrm['details['+row+'][selected]'].checked = true;
	if(document.prodFrm['details['+row+'][quantity]'].value < 1){
		document.prodFrm['details['+row+'][selected]'].checked = false;
		document.prodFrm['details['+row+'][quantity]'].value = 0;
	}
}
function checkQuote(frm)
{
	if (frm['info[employee_id]'].value == 0){
		alert('You must asign a sales rep to the quote');
		return false;
	}


}

function fillFields(){
        opener.addform['info[company]'].value = 'look';
        opener.addform['info[contact]'].value = 'look';
        //opener.addform['info[]'].value = 'look';
        window.close();
}

function showPhone(phone,phone2) {
	var putItThere = null; 
	var chasm = screen.availWidth;
	var mount = screen.availHeight;
	var w = 0;
	var h = 0;

	newwin = window.open('', 'BigPic', 'screenX=20,screenY=20,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=300,height=85,left=' + ((chasm - w - 10) * .5) + ',top=' + ((mount - h - 30) * .5)); 
	newwin.document.write('<center><span style="font-family:Verdana,Arial;font-size:32px;">'+phone+'</span><br><span style="font-family:Verdana,Arial;font-size:8px;"><a href="#" onClick="window.close();return false;">CLOSE WINDOW</a></span></center>');
	
	// check for flash 5
	
	if ( (navigator.appName == "Microsoft Internet Explorer" &&
              navigator.appVersion.indexOf("3.1") == -1) ||                      
     		 (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]  && 
     		  navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin && 
     		  navigator.plugins && navigator.plugins["Shockwave Flash"]) )
    {
		newwin.document.write('<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0" WIDTH=5 HEIGHT=5 id="phone" ALIGN="">');
		newwin.document.write('<PARAM NAME=movie VALUE="phone.swf?phone=1'+phone2+'"><EMBED src="phone.swf?phone=1'+phone2+'" WIDTH=5 HEIGHT=5 NAME="phone" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>');
	}
	
	newwin.focus();
}

function checkBeforePublish(frm){
	if (frm['info[employee_id]'].value == 0){
		alert('You must asign a sales rep to the quote');
		return false;
	}
	return confirmExtras();
}
function confirmExtras(){
	return confirm('Have you remembered to add installation, taxes, promotions, and service charges?');
}



function showUpdater(){
	if (document.all) {
		message.style.visibility = "visible";
		message1.style.visibility = "visible";
	} else if (document.getElementById) {
		document.getElementById("message").style.visibility = "visible";
		document.getElementById("message1").style.visibility = "visible";
	}
}



function setPoQuantities(frm,total,detail_id,field)
{
		
	inputed_total =  parseInt(frm['quantity1['+detail_id+']'].value) + parseInt(frm['quantity2['+detail_id+']'].value) + parseInt(frm['quantity3['+detail_id+']'].value);
	frm['remaining_quantity['+detail_id+']'].value = total - inputed_total;
	
	if (inputed_total > total){
		alert('The total is to high please go back and fix');	
		field.value = 0;
		frm['remaining_quantity['+detail_id+']'].value = total - (parseInt(frm['quantity1['+detail_id+']'].value) + parseInt(frm['quantity2['+detail_id+']'].value) + parseInt(frm['quantity3['+detail_id+']'].value));
	}

}


function checkPoFrm(frm){
	
	var i;
	
	for (i=0; i < ids_array.length; i++){
		if (frm['vendor1['+ids_array[i]+']'].value == 0 && frm['quantity1['+ids_array[i]+']'].value > 0){
			alert ('Please assign a vendor to all quantities chosen');			
			return false;
		}
		if (frm['vendor2['+ids_array[i]+']'].value == 0 && frm['quantity2['+ids_array[i]+']'].value > 0){
			alert ('Please assign a vendor to all quantities chosen');			
			return false;
		}
		if (frm['vendor3['+ids_array[i]+']'].value == 0 && frm['quantity3['+ids_array[i]+']'].value > 0){
			alert ('Please assign a vendor to all quantities chosen');			
			return false;
		}
		
	}
	
	for (i=0; i < ids_array.length; i++){
		if (frm['remaining_quantity['+ids_array[i]+']'].value != 0){
			alert ('Please fix values all remainig quantities should be zero');			
			return false;
		}
	}
	return true;
}

function updateDisabled(prefix,row_no)
{
	var frm = document.quoteFrm;
	
	frm[prefix + '[' + row_no + '][toss_rebate]'].disabled = true;
	frm[prefix + '[' + row_no + '][discount]'].disabled = true;
	frm[prefix + '[' + row_no + '][markup]'].disabled = true;
			
	switch (frm[prefix + '[' + row_no + '][formula]'].selectedIndex) {
		case 0: // MSRP
			frm[prefix + '[' + row_no + '][discount]'].disabled = false;
			break;
		case 1: // US1
			frm[prefix + '[' + row_no + '][toss_rebate]'].disabled = false;
			frm[prefix + '[' + row_no + '][markup]'].disabled = false;
			break;
	}
}

function toggleBlock(id)
{
	if (_getElement(id).style.display == 'none') {
		_getElement(id).style.display = 'block';
		_getElement(id+'pic').src = '/pics/dtable.opened.png';
	}
	else {
		_getElement(id).style.display = 'none';
		_getElement(id+'pic').src = '/pics/dtable.closed.png';
	}
}

function _getElement(id)
{
	if (document.getElementById && document.getElementById(id)) {
		return document.getElementById(id);
	}
	else if (document.all && document.all[id]) {
		return document.all[id];
	}
	else {
		return false;
	}
}