/*
 * briz@glyphix.com 20040616
 *
 * Added onload event handler to:
 * -- place cursor in the first form field
 * -- auto-submit form when Enter key is pressed
 */

//iceInit=function() {
    //// setAutoSubmit(); // can't do this one because of the login form
    //focusForm();
//}
//window.onload=iceInit;


function setAutoSubmit(){
    if(document.forms.length){
		for(i=0;i<document.forms.length;i++){
		    document.forms[i].onkeypress=function(){
			if(event.keyCode==13){this.submit()}
		    }
		}
    }
}

function focusForm(){
    if(document.forms[0]){
		var FieldList=document.forms[0];
		for(i=0;i<FieldList.length;i++){
		    if((FieldList.elements[i].type=="text") || (FieldList.elements[i].type=="textarea")){
				document.forms[0].elements[i].select();
				break;
		    }else if(FieldList.elements[i].type.toString().charAt(0)=="s"){
				document.forms[0].elements[i].focus();
				break;
		    }
		}
    }
}

function execSelect(target){
    if(target){
		eval(target);
    }else{
		return false;
    }
}

function toggleDesc(DivID){
	$('#' + DivID)
		.filter(':visible')
			.hide('slow')
			.end()
		.filter(':hidden')
			.show('fast')
			.end();
}

function toggleItem(DivID){
	return toggleDesc(DivID);
}

function togglePanel(DivID){
	$.get("/?Realm=My&Action=TogglePanel&Name=" + DivID.replace("Body",""));
	return toggleDesc(DivID);
}

function toggleFilter(DivID){
	$.get("/?Realm=My&Action=ToggleFilter&Name=" + DivID.replace("Body",""));
	return toggleDesc(DivID);
}

function callProcess(MyRealm,MyAction,ToName,ToID){
	var CallMe="/index.php?Realm=" + MyRealm + "&Action=" + MyAction;
	if(ToName && ToID){
		CallMe=CallMe + "&" + ToName + "=" + ToID;
	}
	loadXML(CallMe,tossXML);	
	return true;
}

function loginSubmit(){
    FormObj = document.getElementById("form");
    if(FormObj.Pass.value && FormObj.Salt.value){
		var Hashed = MD5(FormObj.Pass.value + FormObj.Salt.value);
		URL = "/?Realm=Login&Action=Auth&u=" + MD5(FormObj.Login.value) + "&p=" + Hashed + "&s=" + FormObj.Salt.value;
		document.location.href = URL;
    }else{
		alert("Please enter a username and a password.");
    }
    return 1;
}

function toggleAccessoryOption(Type){
    var Name="Accessories_" + Type;
    var Other="Other_" + Type;
    if(document.getElementById(Name).value){
		return document.getElementById(Other).value="";
    }else{
		return document.getElementById(Other).disabled=false;
    }
}

function toggleSelector(ID){
    if(document.getElementById("Selector_" + ID).checked){
		document.getElementById("Selector_" + ID + "_Row").style.backgroundColor="green";
    }else{
		document.getElementById("Selector_" + ID + "_Row").style.backgroundColor="white";
    }
    return 1;
}

/*
 * ToggleID is the id of the field which will be overridden by the form block.
 * BlockID is the id of the element containing the form block fields.
 */
function ToggleFormBlock(ToggleID,BlockID){
    toggleDisabled(ToggleID);
    if(document.getElementById(ToggleID).disabled){
		if(document.getElementById(BlockID)){
		    document.getElementById(BlockID).style.display='block';
		    setBlockFormElementsState(BlockID,"Enable");
		}
    }else{
		if(document.getElementById(BlockID)){
		    setBlockFormElementsState(BlockID,"Disable");
		    document.getElementById(BlockID).style.display='none';
		}
    }
}

function setBlockFormElementsState(BlockID,Action){
    if(!Action){
		Action="Enable";
    }
    if(Action=="Enable"){
		DisabledValue=0;
    }else{
		DisabledValue='true';
    }
    Block=document.getElementById(BlockID);
    if(Block){
		FormStuff=Block.getElementsByTagName("*");
		for(i=0;i<FormStuff.length;i++){
		    if(FormStuff.item(i).nodeName=="INPUT"
		    || FormStuff.item(i).nodeName=="SELECT"
		    || FormStuff.item(i).nodeName=="TEXTAREA"
		    || FormStuff.item(i).nodeName=="BUTTON"){
			FormStuff.item(i).disabled=DisabledValue;
		    }
		}
    }
}

function toggleDisabled(ID){
    if(document.getElementById(ID).disabled){
		document.getElementById(ID).disabled=0;
    }else{
		document.getElementById(ID).disabled="true";
    }
}

function toggleElementVisibility(ID){
    if(document.getElementById(ID).style.display!="none"){
		document.getElementById(ID).style.display="none";
    }else{
		document.getElementById(ID).style.display!="block"
    }
}

function toggleInput(Tracker){
    Controller="Controller_" + Tracker;
    Controlled="Input_" + Tracker;
    if(document.getElementById(Controller).checked){
		document.getElementById(Controlled).disabled=0;
		document.getElementById(Controlled).enabled="true";
    }else if(!document.getElementById(Controller).checked){
		document.getElementById(Controlled).disabled="true";
    }
    return true;
}

function addInventoryToCart(InventoryID){
    Price=window.prompt("How much for this Item?");
    location.href="/?Realm=Inventory&Action=AddToCart&InventoryID=" + InventoryID + "&Price=" + Price;
    return 1;
}

function addPaymentToInventory(InvoiceID){
    Amount=window.prompt("How much would you like to apply to this Invoice?");
    location.href="/?Realm=Accounting&Action=ApplyPayment&InvoiceID=" + InvoiceID + "&Amount=" + Amount;
    return 1;
}

var LastShippingZipCode=0;

function checkShippingLocation(ZipCode){
    if(LastShippingZipCode.length>1){
		if(LastShippingZipCode!=ZipCode){
			alert("Please do not add Items in different zipcodes to the same shipment.");
		}
    }
    LastShippingZipCode=ZipCode;
    return 1;
}

/*
"Realm"=>null,
"WizardConf"=>"AddInventory",
"Step"=>null,
"Args"=>null,
"ProductID"=>null
*/


function startWizard(Realm,Action,LinkType,LinkID){
    var URL="/index.php?Realm=" + Realm + "&Action=" + Action + "&" + LinkType + "=" + LinkID;
	var Name=Action + '_Wizard';
	var Options='location=no,toolbar=no,scrollbars=yes,menubar=no,scrolling=yes,status=no,resize=yes,resizable=yes';
	Options+=",width=800,height=600";
	var MyHeight=screen.availHeight;
//	alert("My Height - " + MyHeight);
/*
	switch(true) {
		case(MyHeight>1140):
			Options+=",width=800,height=600";
			break;
		case(MyHeight>1020):
			Options+=",width=700,height=500";
			break;
		case(MyHeight>840):
			Options+=",width=600,height=400";
			break;
		default:
			// FU, get a bigger monitor you t00l
			Options+=",width=320,height=240";
			break;
	}
//	alert(Options);
*/
	Wizard=window.open(URL,Name,Options);
//	Wizard.focus();
}

function win2top(new_URL,Name,attributes) {
    var urlOfNewWindow=new_URL;
    oldWindow=window.open(urlOfNewWindow,Name,attributes);
    oldWindow.focus();
}

function setMorsel(Morsel){
    document.Paging.Morsel.value=Morsel;
    doPaging();
}

function setChunk(Chunk){
    document.Paging.Morsel.value="0";
    document.Paging.Chunk.value=Chunk;
    doPaging();
}

function doPaging(){
    if(document.Paging){
		document.Filter.Chunk.value=document.Paging.Chunk.value;
		document.Filter.Morsel.value=document.Paging.Morsel.value;
    }
    document.Filter.submit();
}

function doSort(Column){
    if(Column.length && document.Filter){
		if(document.Filter.SortMe.value==Column){
		    if(document.Filter.SortOrder.value=='0'){
				document.Filter.SortOrder.value=1;
		    }else{
				document.Filter.SortOrder.value=0;
		    }
		}else{
		    document.Filter.SortOrder.value=1;
		    document.Filter.SortMe.value=Column;
		}
		document.Filter.submit();
    }
}

function popupWizard(URL){
    win2top(URL,"popup","width=700,height=500,location=no,toolbar=no,scrollbars=yes,menubar=no,scrolling=yes,status=no,resize=yes,resizable=yes");
}

/*
 * This function parses comma-separated name=value argument pairs from
 * the query string of the URL. It stores the name=value pairs in
 * properties of an object and returns that object.
 */
function getArgs() {
    var args = new Object();
    var query = location.search.substring(1);  		// Get query string.
    var pairs = query.split(",");              		// Break at comma.
    for(var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');       		// Look for "name=value".
		if (pos == -1) continue;               		// If not found, skip.
		var argname = pairs[i].substring(0,pos);  	// Extract the name.
		var value = pairs[i].substring(pos+1); 		// Extract the value.
		args[argname] = unescape(value);          	// Store as a property.
    }
    return args;                               		// Return the object.
}

/*
 * Recurse up DOM, testing visibility in node tree.
 * If an element does not have a style.display attribute, return false.
 * An element must have its style.display explicitly set to 'none' to return false.
 */
function elementIsVisible(Obj){
    /*
     * briz@glyphix.com 20041221
     * For some reason, this function behaves differently when it's operating on client-side XML vs. client-side HTML.
     * When in HTML mode, it gets a lot of "Obj has no properties" errors.
     */
    if(!Obj){
		return true;
    }
    // if body, we're at the top of the tree, return true
    if(Obj.nodeName=="body"){
		return true;
    }else{
		if(Obj.style){
		    if(Obj.style.display.toLowerCase()=="none"){
				return false;
		    }else{
				return elementIsVisible(Obj.parentNode);
		    }
		}else{
		    return elementIsVisible(Obj.parentNode);
		}
    }
}

function checkForm(){
    var BodyList;
    var DocBody;
    var InputBlocks;
    var CurItem;
    var i=0;
    var ErrorList=0;
    BodyList=document.getElementsByTagName("body");
    DocBody=BodyList[0];
    InputBlocks=DocBody.getElementsByTagName("li");
    if(InputBlocks.length){
		for(i=0;i<InputBlocks.length;i++){
		    CurItem=InputBlocks.item(i);
		    /*
		    if(InputBlocks.item(i).className){
			alert('elementIsVisible(' + InputBlocks.item(i).className + '): ' + (elementIsVisible(InputBlocks.item(i))));
		    }
		    */
		    if(
				CurItem.id.toLowerCase()=="input"
				&& (CurItem.parentNode.className.toLowerCase()=="required" || CurItem.parentNode.className.toLowerCase()=="error")
				&& elementIsVisible(InputBlocks.item(i))
		    ){
				CurItem.parentNode.className="Required";
				if(!oneFieldHasValue(CurItem)){
				    CurItem.parentNode.className="Error";
				    ErrorList++;
				}
		    }
		}
		if(ErrorList){
		    alert("Please enter all required information. Missing fields have been marked in red.");
		    return false;
		}else{
		    return true;
		}
    }else{
		return true;
    }
}

function oneFieldHasValue(Obj){
    var i=0;
    var FieldList=Obj.getElementsByTagName("*");
    var FoundField=false;
    if(FieldList.length>0){
		for(i=0;i<FieldList.length;i++){
		    if(FieldList.item(i).nodeName.toLowerCase()=="input" || FieldList.item(i).nodeName.toLowerCase()=="select" || FieldList.item(i).nodeName.toLowerCase()=="textarea"){
				// if it's visible and it's not a hidden field
				if(FieldList.item(i).type.toLowerCase()!="hidden" && FieldList.item(i).type.toLowerCase()!="button"){
				    if(elementIsVisible(FieldList.item(i))){
						FoundField=true;
						if(FieldList.item(i).type.toLowerCase()=="radio" || FieldList.item(i).type.toLowerCase()=="checkbox"){
						    if(FieldList.item(i).checked){
								return true;
						    }
						}else if(FieldList.item(i).nodeName.toLowerCase()=="select"){
						    if(FieldList.item(i).disabled){
								return true;
						    }
						    if(FieldList.item(i).options.length > 0){
								if(FieldList.item(i).options[FieldList.item(i).selectedIndex].value.length>0 
									&& FieldList.item(i).options[FieldList.item(i).selectedIndex].value.toLowerCase()!='null'){
								    return true;
								}
						    }
						}else{
						    if(FieldList.item(i).value){
								return true;
						    }
						}
				    }else{
						continue;
				    }
				}else{
				    continue
				}
		    }else{
				continue;
		    }
		}
		// if it made it this far, there's a required field without a value
		if(FoundField){
		    return false;
		}else{
		    // found a required field, but it had no value
		    return true;
		}
    }else{
	// no fields, return true to not flag as error
	return true;
    }
}

function isEmpty(elementID,formID){
    if(!formID){
		theForm=document.forms[0];
    }else{
		theForm=document.getElementById(formID);
    }
    for(e=0;e<theForm.elements.length;e++){
		if(theForm.elements[e].id==elementID){
		    theElement=theForm.elements[e];
		    if(theElement.type=="radio" || theElement.type=="checkbox"){
			if(theElement.checked){
			    return false;
			}
		    }else{
			if(theElement.value){
			    return false;
			}
		    }
		}
    }
    return true;
}

function isBadEmail(elementID){
    checkString=document.getElementById(elementID).value;
    if(checkString.indexOf("@")<0){
		return true;
    }
    if(checkString.indexOf(".")<0){
		return true;
    }
    if(checkString.indexOf(" ") > -1){
		return true;
    }
    var dotParts = checkString.split(".");
    var tld = dotParts.pop();
    if(tld.length < 2){
		return true;
    }
    /* check for invalid characters */
    for(var i = 0; i < checkString.length; i++){
        ch = checkString.substring(i, i + 1);
        if(!(
		    (ch >= "A" && ch <= "Z")
		    || (ch >= "a" && ch <= "z")
		    || (ch == "@")
		    || (ch == ".")
		    || (ch == "_")
		    || (ch == "-")
		    || (ch >= "0" && ch <= "9")
		)){
		    return true;
		}
    }
    return false;
}

function CurrencyFormatted(amount){
    var i = parseFloat(amount);
    if(isNaN(i)){
		i = 0.00;
    }
    var minus = "";
    if(i < 0) {
		minus = "-";
    }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf(".") < 0) {
		s += ".00";
    }
    if(s.indexOf(".") == (s.length - 2)) {
		s += "0";
    }
    s = minus + s;
    return s;
}

function totalize(ItemBaseID,NumItems,DestinationID){
    var TotalValue=0;
    var CurVal=0;
    for(i=1;i<=NumItems;i++){
		CurVal=parseFloat(document.getElementById(ItemBaseID+i).value);
		TotalValue+=CurVal;
    }
    document.getElementById(DestinationID).value=CurrencyFormatted(TotalValue);
}

function distributeAmount(SourceID,ItemBaseID,NumItems,DestinationID,Direction,Type){
	var SourceValue=0;
    var Even=0;
    var CurVal=0;
    var NewVal=0;
    if(!Direction){
		Direction="down";
    }
    SourceValue=parseFloat(document.getElementById(SourceID).value);
    if(!SourceValue){
		alert("Please enter an adjustment amount.");
		return false;
    }
    Even=parseFloat(SourceValue/NumItems);
    for(i=1;i<=NumItems;i++){
		CurVal=parseFloat(document.getElementById(ItemBaseID+i).value);
		if(Type=='Dollars'){
			if(Direction=="up"){
				NewVal=CurVal+Even;
			}else{
				NewVal=CurVal-Even;
				if(NewVal<0){
					NewVal=0;
				}
			}
		}else if(Type=='Percent'){
			var Adjustment=(CurVal*(SourceValue/100));
			if(Direction=="up"){
				NewVal=CurVal+Adjustment;
			}else{
				NewVal=CurVal-Adjustment;
				if(NewVal<0){
					NewVal=0;
				}
			}
		}
		document.getElementById(ItemBaseID+i).value=CurrencyFormatted(NewVal);
    }
    totalize(ItemBaseID,NumItems,DestinationID);
}

function divideAndConquer(SourceID,ElementName,NumElements){
    var FirstElement=ElementName+"1";
    if(document.getElementById(SourceID) && document.getElementById(FirstElement)){
		SourceValue=document.getElementById(SourceID).value;
		Even=CurrencyFormatted(SourceValue/NumElements);
		for(i=1;i<=NumElements;i++){
		    document.getElementById(ElementName+i).value=Even;
		}
		/*
		 * Try to correct rounding errors...
		 * Error should be less than the number of items in cents.
		 * JavaScript has horrible problems with maintaining fixed decimals.
		 * Multiply by 100 then divide by 100 to correct.
		 */
		ReverseEven=CurrencyFormatted(Even * NumElements);
		Delta=Math.abs(CurrencyFormatted(SourceValue - ReverseEven));
		NumOff=Delta * 100;
		if(ReverseEven < SourceValue){
		    AdjustValue=1;
		}else{
		    AdjustValue=-1;
		}
		if(NumOff < NumElements){
		    for(i=0;i<NumOff;i++){
				ElementValue=document.getElementById(ElementName+(i+1)).value;
				document.getElementById(ElementName+(i+1)).value=((ElementValue * 100) + AdjustValue) / 100;
		    }
		}else{
		    alert("Rounding errors too big, cannot correct.");
		}
    }
}

function selectRow(Obj,StatusClass){
    if(Obj.checked){
		Obj.parentNode.parentNode.className+=" Selected";
    }else{
		Obj.parentNode.parentNode.className=StatusClass;
    }
}

function toggleAllRows(Obj,EnclosingObj){
    var Checks;
    var PagingObj;
    if(EnclosingObj){
		EnclosingID=EnclosingObj;
    }else{
		EnclosingID="Paging";
    }
    PagingObj=document.getElementById(EnclosingID);
    if(!PagingObj){
		alert("This page does not allow for this function.");
		return false;
    }
    if(PagingObj){
		Checks=PagingObj.getElementsByTagName("input");
		if(Checks.length){
		    for(i=0;i<Checks.length;i++){
				if(Checks[i].type=="checkbox"){
				    Checks[i].click();
				}
		    }
		}else{
		    alert("No rows can be checked.");
		    return false;
		}
    }
    Obj.blur();
}

function processMultipleRecords(Realm,Action){
    var Checks;
    var ControlObj=document.getElementById("MultiSelectControl");
    var PagingObj=document.getElementById("Paging");
    var RecordChecked=false;
    if(!ControlObj || !PagingObj){
        alert("This page does not allow for this function.");
        return false;
    }
    if(ControlObj && PagingObj){
        Checks=PagingObj.getElementsByTagName("input");
        if(Checks.length){
            for(i=0;i<Checks.length;i++){
                if(Checks[i].type=="checkbox" && Checks[i].checked){
                    RecordChecked=true;
                    break;
                }
            }
            if(!RecordChecked){
                alert("No records are selected.\nPlease check at least one record from the list first.");
                return false;
            }else{
                PagingObj.action="/?Realm="+Realm+"&Action="+Action+"&r="+Math.round(Math.random()*100);
//				alert(PagingObj.action);
                PagingObj.submit();
            }
            return false;
        }else{
            alert("This page does not allow for this function.");
            return false;
        }
    }
}

function confirmScrubInventory(InventoryID,UserID){
    if(confirm("Are you sure? This will completely delete all information about this Inventory Unit. Press OK to delete.")){
		document.location="/?Realm=Inventory&Action=Scrub&InventoryID="+InventoryID+"&UserID="+UserID;
    }
}

function confirmScrubInvoice(InvoiceID,UserID){
    if(confirm("Are you sure? This will completely delete this invoice. This cannot be undone. Press OK to delete.")){
		 if(confirm("Seriously. This invoice will be gone. Forever. No way to get it back. You Sure?")){
			document.location="/?Realm=Accounting&Action=DeleteInvoice&InvoiceID="+InvoiceID+"&UserID="+UserID+"&Force=1";
		}
    }
}

function toggleShipping(Obj,Value){
	var List=Obj.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('select');
	for(var i=0;i<List.length;i++){
		List[i].value=Value;
	}
}

function doStaleDealAction(){
	var List=document.getElementsByTagName('tr');
	for(var i=0;i<List.length;i++){
		if(List[i].getAttribute("class")=="PendingApproval"){
			var CurID=List[i].getElementsByTagName('td')[2].getAttribute("id");
			window.setTimeout('isDealStale(' + CurID + ')', 100);
//			isDealStale(CurID);
		}
	}
}


function processLinkDealDeposit(DealID,DealName,PanelID){
	var URL='?Realm=Accounting&Action=LinkDealToPayment&DealID=' + DealID;
	$.get(URL,'',function(data){				
		var Status=data.getElementsByTagName('Success')[0].firstChild.data;
		if(Status=="Yes"){
			$("#" + PanelID).append('<h3>Deals Attached</h3><table class="List"><tr><td>'
				+ '<a href="javascript:void(0)" onClick="document.location=\'?Realm=Deal&Action=Detail&DealID=' + DealID + '\'">' + DealName + '</a></td></tr></table>');
		}else{
			alert(data.getElementsByTagName('Message')[0].firstChild.data);
		}
	});
}



function drawStaleDeal(DealID,Status){
	if(Status>0){
		document.getElementById(DealID).parentNode.style.backgroundColor="red";
	}
}

function confirmKillDeal(DealID){
	if(confirm('Are you sure you want to delete this deal?')){
		document.location='/?Realm=Deal&Action=KillDeal&DealID=' + DealID;
	}
}

function PrintLabel(InventoryID){
	var URL='/index.php?Realm=Inventory&Action=PrintBarcodeLabel&InventoryID=' + InventoryID;
	var Options='location=no,toolbar=no,scrollbars=yes,menubar=no,scrolling=yes,status=no,resize=yes,resizable=yes';
	Options+=",width=320,height=240";
	BarcodeWindow=window.open(URL,'BarcodeWindow',Options);
	BarcodeWindow.onload="window.print()";
//	BarcodeWindow.close();
}

/*
 * System Message Fun!
 */
function showSystemMessage(data){
	$('#SystemMessage').empty();
	try{
		if(data.getElementsByTagName('Message').length==0){
			$('#SystemMessage').filter(":visible").fadeOut('fast');
			return false;
		}else{
			var Result=RT_TransformXMLFragment(data,'/XSL/messages.xsl');
			$('#SystemMessage').append(Result);
			$('#SystemMessage').filter(":hidden").fadeIn('slow');
		}
	}catch(err){
		// No messages, do nothing
		return false;
	}
}


function RT_TransformXMLFragment(data,StyleSheet){
	if (window.ActiveXObject){
		try {
			XSL = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (othermicrosoft) {
			try {
				XSL = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (failed) {
				alert('Your version of Internet Explorer is incompatible with this site.');
				XSL = false;
			}
		}
		// code for IE
		var XSL = new ActiveXObject("Microsoft.XMLDOM");
		XSL.async = false;
		XSL.load(StyleSheet);
		var Result=data.transformNode(XSL);
	}else if(navigator.userAgent.toLowerCase().indexOf("webkit")!=-1){
//		alert('Your browser is incompatible with this site.');
		var xsltProcessor = new XSLTProcessor();
		xsltProcessor.importStylesheet(StyleSheet);
		//var d=document.implementation.createDocument("", "", null);
		//var Result=xsltProcessor.transformToFragment(data,d);
		//alert(Result);
		
		xmlDoc = (new DOMParser()).parseFromString(data,'text/xml');
		Result = xsltProcessor.transformToFragment(xmlDoc, document);
		console.log(Result);

	}else if(document.implementation && document.implementation.createDocument){
		// code for Mozilla, Firefox, Opera, the rest of the world.
		var xsltProcessor = new XSLTProcessor();
		var myXMLHTTPRequest = new XMLHttpRequest();
		myXMLHTTPRequest.open('GET', StyleSheet, false);
		myXMLHTTPRequest.send(null);//transform
		var xslStylesheet = myXMLHTTPRequest.responseXML;
		xsltProcessor.importStylesheet(xslStylesheet);
		var Result=xsltProcessor.transformToFragment(data, document);
	}
	return Result;
}

