// Application-specific Javascript for Aligni

Effect.SlideUpDown = function(element) {
	e = $(element);
	if (Element.visible(e)) {
		return new Effect.SlideUp(e);
	} else {
		return new Effect.SlideDown(e);
	}
}

Effect.BlindUpDown = function(element) {
	e = $(element);
	if (Element.visible(e)) {
		return new Effect.BlindUp(e);
	} else {
		return new Effect.BlindDown(e);
	}
}


function report_expand(id, newC) {
	var i=0;
	var obj;
	while (obj = document.getElementById(id+"_"+i)) {
		if (newC) { 
			obj.className = newC; 
		} else if (obj.className == 'show') { 
			obj.className = 'hide'; 
		} else if (obj.className == 'hide') { 
			obj.className = 'show';
		} else if (obj.className == 'tdown') { 
			obj.className = 'tup'; 
		} else if (obj.className == 'tup') { 
			obj.className = 'tdown'; 
		} else {
	       // If the other classes don't apply, let's just try to
	       // toggle visibility.
	       Element.toggle(id+"_"+i);
		}
		i++;
	}
}


// Removes borders from TD elements in a TR.  Done by setting
// the classname to "noborder" which then needs to be setup in CSS.
function remove_td_borders(rowid) {
	var col = $(rowid).firstChild;
	while (col) {
		if (col.nodeType == 1)
			col.className = "noborder";
		col = col.nextSibling;
	}
}
function add_td_borders(rowid) {
	var col = $(rowid).firstChild;
	while (col) {
		if (col.nodeType == 1)
			col.className = "";
		col = col.nextSibling;
	}
}


// For the use of tabs.  Iterates through and activates only one tab while
// deactivating the rest.
function pick_tab(prefix, active) {
	var i=0;
	var tab_obj, tab_contents_obj;
	while (tab_obj = $(prefix+"_"+i)) {
		if (i == active) { 
			tab_obj.addClassName('active'); 
			Element.show(prefix+'_contents_'+i);
		} else { 
			tab_obj.removeClassName('active');
			Element.hide(prefix+'_contents_'+i);
		}
		i++;
	}
}

function toggle_row_detail(prefix, qid) {
    var detail_row;
    detail_row = $(prefix + "_detail_" + qid);
    if (detail_row.style.display != 'none') {
        detail_row.style.display = 'none';
        add_td_borders(prefix + "_row_" + qid);
    } else {
        detail_row.style.display = '';
        remove_td_borders(prefix + "_row_" + qid);
    }
}


function validatePositive(fieldId, message) {
	var val = $(fieldId).value;
	if (isNaN(val) || (parseFloat(val) <= 0)) {
		alert(message);
		$(fieldId).focus();
		return false;
	} else {
		return true;
	}
}


function validateInventoryAdjust(fieldId, quantity, allow_fractional) {
	var val = $(fieldId).value;
	if (val == '') {
		return true;
	}
	if (allow_fractional == true) {
		if (!val.match(/^[+-]?\d+(\.\d+)?(e[-+]?\d+)?$/i)) {
			alert('Quantity must be a number.');
			$(fieldId).focus();
			return false;
		} else if (quantity+parseFloat(val) < 0) {
			alert('Adjustment exceeds quantity.');
			$(fieldId).focus();
			return false;
		}
	} else {
		if (!val.match(/^[+\-]?\d+$/)) {
			alert('Quantity must be an integer.');
			$(fieldId).focus();
			return false;
		} else if (quantity+parseInt(val) < 0) {
			alert('Adjustment exceeds quantity.');
			$(fieldId).focus();
			return false;
		}
	}
	return true;
}


function validateField(fieldId, message) {
	if ($(fieldId).value == "") {
		alert(message);
		$(fieldId).focus();
		return(false);
	} else {
		return(true);
	}
}


function selectAll(prefix, count) {
	for (i=0; i<count; i++) {
		$('rowvalid_'+i).checked = true;
	}
}


function unselectAll(prefix, count) {
	for (i=0; i<count; i++) {
		$('rowvalid_'+i).checked = false;
	}
}


var quotes = {
	ERRMSG: "An error occurred processing this request.\nPlease try again later.",
	contact_check: {
		add: function(rfq_id, id) {
			Element.show('cspin_' + id)
			new Ajax.Request(quotes.add_contact_url,
				{asynchronous:true, evalScripts:true, parameters:'id='+id,
				onFailure:function(request) { quotes.contact_check.addFail(request, id) }})
		},
		addFail: function(request, id) {
			Element.hide('cspin_' + id)
			$('contact_cb_' + id).checked = false
			alert(quotes.ERRMSG)
		},
		remove: function(rfq_id, id) {
			Element.show('cspin_' + id)
			new Ajax.Request(quotes.remove_contact_url,
				{asynchronous:true, evalScripts:true, parameters:'id='+id,
				onFailure:function(request) { quotes.contact_check.removeFail(request, id) }})
		},
		removeFail: function(request, id) {
			Element.hide('cspin_' + id)
			$('contact_cb_' + id).checked = false
			alert(quotes.ERRMSG)
		}
	},
    z_nothingness: false // last item doesn't get a comma
}


var notes = {
	toggleView: function(id) {
		if ($('note_viewrow_'+id).style.display == "none") {
			Element.hide('note_edit_'+id);
			Element.show('note_view_'+id);
			remove_td_borders('note_row_'+id);
		} else {
			add_td_borders('note_row_'+id);
		}
		Element.toggle('note_viewrow_'+id);
	},
	startEdit: function(id) {
		Element.hide('note_view_'+id);
		Element.hide('note_edit_'+id);
		remove_td_borders('note_row_'+id);
		Element.show('note_viewrow_'+id);
	},
	cancelEdit: function(id) {
		Element.hide('note_viewrow_'+id);
		add_td_borders('note_row_'+id);
		Element.hide('note_edit_'+id);
		Element.show('note_view_'+id);
	},
	validateNote: function(id) {
		if (false == validateField('note_title_'+id, "Title cannot be blank."))
			return(false);
		if (false == validateField('note_text_'+id, "Note text cannot be blank."))
			return(false);
		return(true);
	},
	validateURL: function(id) {
		if (false == validateField('note_title_'+id, "Title cannot be blank."))
			return(false);
		if (false == validateField('note_text_'+id, "URL cannot be blank."))
			return(false);
		return(true);
	},
	
    z_nothingness: false // last item doesn't get a comma
}


/* ------------------------------ */
/* - Functions related to parts - */
/* ------------------------------ */
var parts = {
	toggleInventoryMove: function(id) {
		Element.toggle('inventorymove_form_'+id)
		if ($('inventorymove_form_'+id).style.display != "none") {
			$('inventorymove_link_'+id).innerHTML = "Cancel"
			Field.focus('inventorymove_field_'+id);
			// Remove the border of the accompanying row.
			remove_td_borders('inventory_row_'+id);
		} else {
			$('inventorymove_link_'+id).innerHTML = "Move";
			// Add the border back to the row above.
			add_td_borders('inventory_row_'+id);
		}
	},
	
	toggleInventoryAdjust: function(id) {
		Element.toggle('inventoryadjust_form_'+id)
		if ($('inventoryadjust_form_'+id).style.display != "none") {
			$('inventoryadjust_link_'+id).innerHTML = "Cancel"
			Field.focus('inventoryadjust_field_'+id);
			// Remove the border of the accompanying row.
			remove_td_borders('inventory_row_'+id);
		} else {
			$('inventoryadjust_link_'+id).innerHTML = "Adjust";
			// Add the border back to the row above.
			add_td_borders('inventory_row_'+id);
		}
	},
	
	toggleInventoryAdd: function() {
		['newinventory_form', 'newinventory_link'].each(Element.toggle);
		$('inventory_unit_quantity').value = "";
		Field.focus('inventory_unit_quantity');
	},

	toggleVendorPN: function() {
		['newvpn_form','newvpn_link'].each(Element.toggle);
		$('vendor_partnumber_part_number').value = "";
		$('vendor_partnumber_comment').value = "";
	},

	toggleAltPart: function() {
		['newaltpart_form', 'newaltpart_link'].each(Element.toggle);
		$('post_manufacturerpn').value = "";
		$('parts_alt_part_comment').value = "";
		if ($('newaltpart_form').style.display != "none") Field.focus('post_manufacturerpn');
	},
    z_nothingness: false // last item doesn't get a comma
}


var DemoCountdown = {
	create: function (element, nsec) {
		this.startTime = new Date();
		this.nSec = nsec;
        this.counterid = document.getElementById(element);
		this.counterUpdate();
	},
	
	pad: function (n) {
		return( (n>9) ? n : "0"+n );
	},
	
	counterUpdate: function () {
        var msg = '';

		diff = new Date() - this.startTime;
		diff = this.nSec - diff/1000;
		if (diff <= 0) {
            msg = "The demo database has been reset.  Please reload this page."
    		this.counterid.innerHTML = msg;
            return;
        }

		var thh = Math.floor(diff/60/60);
		diff = diff - thh*60*60;
		var tmi = Math.floor(diff/60);
		diff = diff - tmi*60;
		var tss = Math.floor(diff);
		
		msg = "Demo database will reset in " + this.pad(thh) + ":" + this.pad(tmi) + ":" + this.pad(tss);
		this.counterid.innerHTML = msg;

        // Update in one second.
        setTimeout(this.counterUpdate.bind(this), 1000);
	}
}


/* Thesse scripts were taken from http://www.456bereastreet.com/archive/200505/transparent_custom_corners_and_borders/
 * Thanks for the border work!
 */
/*
addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
*/
function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

/*
createElement function found at http://simon.incutio.com/archive/2003/06/15/javascriptWithXML
*/
function createElement(element) {
	if (typeof document.createElementNS != 'undefined') {
		return document.createElementNS('http://www.w3.org/1999/xhtml', element);
	}
	if (typeof document.createElement != 'undefined') {
		return document.createElement(element);
	}
	return false;
}

function insertTop(obj) {
	// Create the two div elements needed for the top of the box
	d=createElement("div");
	d.className="bt"; // The outer div needs a class name
    d2=createElement("div");
    d.appendChild(d2);
	obj.insertBefore(d,obj.firstChild);
}

function insertBottom(obj) {
	// Create the two div elements needed for the bottom of the box
	d=createElement("div");
	d.className="bb"; // The outer div needs a class name
    d2=createElement("div");
    d.appendChild(d2);
	obj.appendChild(d);
}

function initCB()
{
	// Find all div elements
	var divs = document.getElementsByTagName('div');
	var cbDivs = [];
	for (var i = 0; i < divs.length; i++) {
	// Find all div elements with cbb in their class attribute while allowing for multiple class names
		if (/\bcbb\b/.test(divs[i].className))
			cbDivs[cbDivs.length] = divs[i];
	}
	// Loop through the found div elements
	var thediv, outer, i1, i2;
	for (var i = 0; i < cbDivs.length; i++) {
	// Save the original outer div for later
		thediv = cbDivs[i];
	// 	Create a new div, give it the original div's class attribute, and replace 'cbb' with 'cb'
		outer = createElement('div');
		outer.className = thediv.className;
		outer.className = thediv.className.replace('cbb', 'cb');
	// Change the original div's class name and replace it with the new div
		thediv.className = 'i3';
		thediv.parentNode.replaceChild(outer, thediv);
	// Create two new div elements and insert them into the outermost div
		i1 = createElement('div');
		i1.className = 'i1';
		outer.appendChild(i1);
		i2 = createElement('div');
		i2.className = 'i2';
		i1.appendChild(i2);
	// Insert the original div
		i2.appendChild(thediv);
	// Insert the top and bottom divs
		insertTop(outer);
		insertBottom(outer);
	}
}

if(document.getElementById && document.createTextNode)
{
	addEvent(window, 'load', initCB);
}
