var updateQtyTimeout;

function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	} else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	} else {
		elm['on' + evType] = fn;
	}
}

function removeEvent(obj, evt, fn) {
	if(obj.removeEventListener)
		obj.removeEventListener(evt,fn,false);
	else if (obj.detachEvent)
		obj.detachEvent('on'+evt,fn);
	else
		obj['on'+evt] = null;
}


function addItemToQuickList( item, qty ) {
	var url='quicklistAdd.php?productID=' + item + '&qty=' + qty;
	var x = window.open( url, 'QuickWindow', 'width=400,height=400,scrollbars=no');
}

function validateUSNumber( item ) {
	var CleanedString="";
	var index = 0;
	var LimitCheck;
	var InitialString = item.value

	if (item.value == '') return true;
	//Get the length of the inputted string, to know how many characters to check
	LimitCheck = InitialString.length;

	//Walk through the inputted string and collect only number characters, appending them to CleanedString
	while (index != LimitCheck) {
		if (isNaN(parseInt(InitialString.charAt(index)))) { }
		else { CleanedString = CleanedString + InitialString.charAt(index); }
		index = index + 1;
	}

	//If CleanedString is exactly 10 digits long, then format it and allow form submission
	if (CleanedString.length == 10) {
		item.value = CleanedString.substring(0,3) + "-" + CleanedString.substring(3,6) + "-" + CleanedString.substring(6,10);
	}
	//If CleanedString is not 10 digits longs, show an alert and cancel form submission
	else {
		CleanedString = InitialString;
		alert("Please enter only your ten digit phone number.");
		if (document.all) {
			item.focus();
			item.select();
		}
		return false
	}
}

//
function viewOrder( type, options, orderid ) {
	var url=BaseURL+'viewOrder.php?type=' + type + '&options=' + options + '&orderid=' + orderid;
	var x = window.open( url, 'orderWindow', 'width=800,height=550,scrollbars=1,resizable=1');
}

function viewReturnsPolicy() {
	var url=BaseURL+'returns.php#return';
	var x = window.open( url, 'orderWindow', 'width=800,height=550,scrollbars=1,resizable=1');
}

function viewTerms() {
	var url=BaseURL+'terms.php';
	var x = window.open( url, 'orderWindow', 'width=800,height=550,scrollbars=1,resizable=1');
}

function removeItem( id ) {
	if (confirm('Really remove this category from the database?')) {
		document.rmItemForm.remove.value = "Remove";
		document.rmItemForm.submit();
	} else {
		return false;
	}
}

/* used in changeorder.html */
function check() {
	if (document.changeorderform.reqdate.value == '') {
		alert("Please enter a request date.");
		return false;
	} else {
		return true;
	}
}

/* provides hover support for li elements in lists */
function startList(listID) {
	if (document.all&&document.getElementById(listID)) {
		navRoot = document.getElementById(listID);
		for (i=0; i<navRoot.childNodes.length; i++) {
			node = navRoot.childNodes[i];
			if (node.nodeName=="LI") {
				node.onmouseover=function() {
					this.className+=" hover";
				}
				node.onmouseout=function() {
					this.className=this.className.replace(" hover", "");
				}
			}
		}
	}
}

function startLists() {
	startList("categorylisting");
}

//REGISTER PAGE EVENTS
addEvent(window,"load",startLists);

// SETUP CART FUNCTIONALITY FOR AJAX BASED CART
function startProductForms(){
//	alert("Starting Product Forms");
	if(document.createElement && document.getElementsByTagName){
		orderForms = document.getElementsByClassName("orderQty");
		for(i=0; i < orderForms.length; i++){
			if(orderForms[i].nodeName == 'TD'){
				button = orderForms[i].getElementsByTagName("BUTTON");
				if(button[0]){button[0].style.display = "none"};
				button = orderForms[i].getElementsByTagName("A");
				if(button[0]){button[0].style.display = "none"};
				qty = orderForms[i].getElementsByTagName("INPUT");
				for(j=0; j < qty.length; j++){
					if(qty[j].className == "text"){
						addEvent(qty[j],"keyup", updateQuantity);
						addEvent(qty[j],"click", autoSelect);
					}
				}
			}
		}
		downloadCheckboxes = document.getElementsByClassName("orderDownload");
		for(i=0; i < downloadCheckboxes.length; i++){
			var checkboxes = downloadCheckboxes[i].getElementsByTagName("INPUT");
			for(j=0; j < checkboxes.length; j++){
				var checkbox = checkboxes[j];
				if(checkbox.type == "checkbox"){
					addEvent(checkbox, "click", updateDownload);
				}
			}
		}
	}
}

function startProductRow(productID){
	if(document.createElement && document.getElementsByTagName){
		orderForm = document.getElementById("orderCell_" + productID);;
		if(orderForm.nodeName == 'TD'){
			button = orderForm.getElementsByTagName("BUTTON");
			if(button[0]){button[0].style.display = "none"};
			button = orderForm.getElementsByTagName("A");
			if(button[0]){button[0].style.display = "none"};
			qty = orderForm.getElementsByTagName("INPUT");
			for(j=0; j < qty.length; j++){
				if(qty[j].className == "text"){
					addEvent(qty[j],"keyup", updateQuantity);
					addEvent(qty[j],"click", autoSelect);
				}
			}
		}
		downloadCheckbox = document.getElementById("downloadCell_" + productID);
			var checkboxes = downloadCheckbox.getElementsByTagName("INPUT");
			for(j=0; j < checkboxes.length; j++){
				var checkbox = checkboxes[j];
				if(checkbox.type == "checkbox"){
					addEvent(checkbox, "click", updateDownload);
				}
			}
	}
}

function updateQuantity(e){
		var evt = e || window.event;
		var evtTarget = evt.target || evt.srcElement;
		productID = evtTarget.id.substring(evtTarget.id.indexOf("[")+1, evtTarget.id.indexOf("]"));
		var runningTest = evtTarget.parentNode.getElementsByTagName("SPAN");
		if(runningTest && runningTest[0] && runningTest[0].firstChild.nodeValue == "Updating"){
			//ajax is running, disable the text input ?
			
		}else
//		if(!evtTarget.nextSibling || evtTarget.nextSibling.id != productID){
//			//Show update button to allow user to manually update cart
//			var upBtn = document.createElement('BUTTON');
//			upBtn.id = productID;
//			upBtn.value = 'Update';
//			upBtn.innerHTML = 'Update';
//			upBtn.style.fontSize = '10px';
//			upBtn.onclick = function() {sendAjaxRequest(this.id); this.parentNode.removeChild(this); return false;}
//			evtTarget.parentNode.insertBefore(upBtn,evtTarget.nextSibling);
//		}
		
		// Delay execution of Ajax request 300 milliseconds to allow typing of multiple keys
		// removeEvent(evtTarget,"keyup", updateQuantity);
		clearTimeout(updateQtyTimeout);
		updateQtyTimeout = setTimeout("sendAjaxRequest(\"" + productID + "\")", 700);
}

function updateDownload(e){
		var evt = e || window.event;
		var evtTarget = evt.target || evt.srcElement;
		var productID = evtTarget.id.substring(evtTarget.id.indexOf("_")+1, evtTarget.id.length);
		var qtyNode = document.getElementById("productp[" + productID + "][qty]");
		removeEvent(qtyNode,"keyup", updateQuantity);		
		if(evtTarget.checked){
			$('d'+productID).value = 'Y';
			$('productp['+productID+'][options][download]').value = 'Y';
			qtyNode.value = "1";
		}else{
			$('d'+productID).value = 'N';
			$('productp['+productID+'][options][download]').value = 'N';
		}
		var downloadMsg = evtTarget.parentNode.getElementsByTagName("SPAN");
		if(!downloadMsg[0]){
			downloadMsg = document.createElement('span');
			var downloadMsgText = document.createTextNode('');
			downloadMsg.className = 'incart';
			downloadMsg.style.color = "#666666";
			downloadMsg.appendChild(downloadMsgText);
			evtTarget.parentNode.appendChild(downloadMsg);			
		}else{
			downloadMsg[0].firstChild.nodeValue = "";
		}
		sendAjaxRequest(productID);
}

function sendAjaxRequest(productID){
		/* Find form element that started the action */
		evtTarget = $("productp[" + productID + "][qty]");
		//if blank, consider it 0
		if(evtTarget.value === '') evtTarget.value = '0';

		/* Update display to let people know the call has started */
		var inCart = evtTarget.parentNode.getElementsByTagName("SPAN");
		if(inCart[0]){
		inCart[0].firstChild.nodeValue = "Updating";
		}else{
			var inCart = document.createElement('span');
			var inCartText = document.createTextNode('Updating');
			inCart.className = 'incart';
			inCart.style.color = "#ff0000";
			inCart.appendChild(inCartText);
			evtTarget.parentNode.appendChild(inCart);			
		}
		// disable more text input updates
		evtTarget.readOnly = 'true';
		evtTarget.up('td').removeClassName('active');
		evtTarget.up('td').addClassName('updating');
		if(evtTarget.value != 1 && $('d'+productID).value == 'Y'){
			$('d'+productID).value = 'N';
			$('productp['+productID+'][options][download]').value = 'N';
			var dwnld = $('dwnld_'+productID);
			dwnld.checked = false;
			var downloadMsg = dwnld.parentNode.getElementsByTagName("SPAN");
			if(downloadMsg[0]){
				downloadMsg[0].firstChild.nodeValue = "";
			}
		}
		node = $(productID);
		if(node){node.value = evtTarget.value};

		/* Reattach key listener and send Ajax call */
		//addEvent(evtTarget,"keyup",updateQuantity);
		new Ajax.Request('viewcart.php', {parameters: Form.serialize(evtTarget.form.id)+"&ajax=true&ajaxID="+productID, 
					 onSuccess: function(transport){
						// add productPrice to this evaled text
					 	cartInfo = eval("(" + transport.responseText + ")");
						updateCartInfo(cartInfo);
					 }
					 });
}


function autoSelect(e){
		var evt = e || window.event;
		var evtTarget = evt.target || evt.srcElement;
		evtTarget.select();
}

function updateCartInfo(cartInfo){
	/* cartInfo contains: productID, productPrice, titleCount, productTotal, shipEst, taxAmt, shipmsg, subtotal, error */
	var qty = $("productp[" + cartInfo.productID + "][qty]");
	var download = $("dwnld_" + cartInfo.productID);
	var miniCart = $("headercart");
	
	var displayPrice = $("productp[" + cartInfo.productID + "][displayPrice]");
	
	if (cartInfo.productPrice) {
		displayPrice.innerHTML = '$' + Math.round(cartInfo.productPrice*Math.pow(10, 2))/Math.pow(10, 2); //.toFixed(2);
	} else {
		// don't change the price, leave it where it was
		// displayPrice.innerHTML = "--";
	}
	
	/* Update cell's in cart span */
	if(cartInfo.productCount){
		qty.value = cartInfo.productCount;
	}else{
		qty.value = 0;
	}
	var inCart = qty.parentNode.getElementsByTagName("SPAN");
	if(inCart[0]){
		inCart[0].parentNode.removeChild(inCart[0]);
	}
	var qtyCell = qty.up('td');
	qtyCell.removeClassName('updating');
	qty.readOnly = '';
	if(qty.value != 0){
		qty.up('td').addClassName('active');
	}

	/* Update Minicart Display */
	var cartNodes = miniCart.getElementsByTagName("SPAN");
	for(i=0; i<cartNodes.length; i++){
		if(cartNodes[i].className == "incart"){
			cartNodes[i].firstChild.nodeValue = "(" + cartInfo.titleCount + " titles)";
		}else{
			cartNodes[i].firstChild.nodeValue = "   Total: $" + cartInfo.productTotal;
		}
	}
	
	// Update Totals for cart page
	var lineTotal = document.getElementById("ttl_" + cartInfo.productID);
	if(lineTotal){
		lineTotal.firstChild.nodeValue = "$" + cartInfo.linetotal
	}
	var subtotal = document.getElementById("crt_subtotal");
	if(subtotal){
		subtotal.firstChild.nodeValue = "$" + cartInfo.productTotal;
	}
	var tax = document.getElementById("crt_tax");
	if(tax){
		tax.firstChild.nodeValue = "$" + cartInfo.taxAmt;
	}
	var ship = document.getElementById("crt_ship");
	if(ship){
		ship.firstChild.nodeValue = "$" + cartInfo.shipEst
	}
	var total = document.getElementById("crt_total");
	if(total){
		total.firstChild.nodeValue = "$" + cartInfo.subtotal
	}
	
	/* Update download cell's message */
	if(download){
		var downloadMsg = download.parentNode.getElementsByTagName("SPAN");
		if(cartInfo.download){
			download.checked = true;
			downloadMsg[0].firstChild.nodeValue = "Will be downloaded"
		}else{
			download.checked = false;
			downloadMsg[0].firstChild.nodeValue = "Will be delivered"
		}
	}
	
}


//addEvent(window,"load",startProductForms);

// Start Volume Discount Popup Links

function startVolumeDiscountLinks(){
	discountLinks = document.getElementsByClassName('volumeDiscountLink');
	for(i=0; i < discountLinks.length; i++){
		currentLink = discountLinks[i];
		currentLink.href = "javascript:;";
		addEvent(currentLink, "click", openVolumeDiscount);
	}
	discountLinks = document.getElementsByClassName('legendlink');
	for(i=0; i < discountLinks.length; i++){
		currentLink = discountLinks[i];
		currentLink.href = "javascript:;";
		addEvent(currentLink, "click", openVolumeDiscount);
	}	
}

function openVolumeDiscount(){
	window.open('volumeDisc.php','authorWindow','width=500,height=550,scrollbars=yes,resizable=yes');
};
addEvent(window,"load",startVolumeDiscountLinks);

//Define function and establish listener to convert textareas to htmlarea
function getHTMLEditors() {
	var editors = document.getElementsByClassName("htmleditor");
	if(editors.length>0) {
//		includeJavascript(BaseURL+"script/htmlarea/htmlarea.js");
//		includeJavascript(BaseURL+"script/htmlarea/htmlareaconfig_test.js");
	} else {
		return false;
	}
}
addEvent(window, "load", getHTMLEditors);

//this code allows you to dynamically add scripts to the page
function includeJavascript(url) {
	var e = document.createElement("script");
	e.src = url;
	e.type="text/javascript";
	document.getElementsByTagName("head")[0].appendChild(e);
}

function stripeList() {
    var categories = $('licategories').getElementsByTagName('li');
    for (i=0;i<categories.length;i++) {
        if (i%2) { 
            Element.addClassName(categories[i],'even');
            Element.removeClassName(categories[i],'odd');
        } else {
            Element.addClassName(categories[i],'odd');
            Element.removeClassName(categories[i],'even');
        }
    }
}

function setOrder(element) {
    var getstring = Sortable.serialize(element.id) + '&topBarCat=' + topBarCat;
    var url = BaseURL+'admin/setCatOrder.php';
    var myAjax = new Ajax.Request( url, { method: 'get', parameters: getstring}); // , onComplete: showResponse
    stripeList();
}

var myrules = {
	'#licategories' : function(element){
        Sortable.create(element,{ dropOnEmpty:true,constraint:false,onUpdate:function(){setOrder(element);} } );
	},
	'#licategories ul' : function(element){
        Sortable.create(element,{ dropOnEmpty:true,constraint:false,onUpdate:function(){setOrder(element);} } );
	}
}

Behaviour.register(myrules);

function showResponse(originalRequest) {
		alert(originalRequest.responseText);
	}
	
function createWindow(cUrl) {
var cName='authorWindow';
var cFeatures='width=435,height=250,scrollbars=yes,resizable=yes';

var xWin = window.open(BaseURL+cUrl,cName,cFeatures);
}