﻿//mootools fix
		 Request.HTML.implement({
  
         processHTML: function(text){
             var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
             text = (match) ? match[1] : text;            
             var container = new Element('div');          
             return $try(function(){
                 var root = '<root>' + text + '</root>', doc;
                 if (Browser.Engine.trident){
                     doc = new ActiveXObject('Microsoft.XMLDOM');
                     doc.async = false;
                     doc.loadXML(root);
                 } else {
                     doc = new DOMParser().parseFromString(root, 'text/html');
                 }
                root = doc.getElementsByTagName('root')[0];
                 for (var i = 0, k = root.childNodes.length; i < k; i++){
                    var child = Element.clone(root.childNodes[i], true, true);
                     if (child) container.grab(child);
                 }
                 return container;
             }) || container.set('html', text);
        }
    
     });
     // Array Remove - By John Resig (MIT Licensed)
    Array.prototype.remove = function(from, to) {
      var rest = this.slice((to || from) + 1 || this.length);
      this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
    };		
		window.addEvent('domready',function() { 
			//starting over with objects
			//need "order state" object
			function orderState(){
			    //defaults
			    //currency/edu settings
			    this.usd=true;
			    this.naOnly=true;
			    this.educational=false;
			    //what else to store?
			    this.productstring='';
			    //methods...submit?
			    //itemlist is child of this
			    this.catalog=new itemList(); 
			    this.selected=new Array();
			    this.forms=new Array();
			    this.productStringInputs=new Array();
			    this.currencyPickers=new Array();
			    this.submitButtons=new Array();
			    this.submitForms=new Array();
			    this.totalLabels=new Array();
			    this.totalNumbers=new Array();
			    this.shippingPickers=new Array();
			    this.selectedShipping='';
			    this.subTotal=0;
			    this.productsSubtotal=0;
			    this.trainingSubtotal=0;
			    this.courseDiscount=false;
			    
			};
						
			orderState.prototype.getCountry=function(){
			    //figure out CAN/US/OTHER from usd/naonly?
			    var country='CAN';
			    if (this.usd==true){
			        if(this.naOnly==true){
			            country='US';
			        }else{
			            country='OTHER';    
			        };
			    };		    
			    return country;
			};
			
			function salesForm(parent,target,mode,pagesection,orderObj){
			    //base of product/services form
			    this.top=parent;
			    this.linktarget=target;
			    this.style=mode;
			    this.pagesection=pagesection;
			    this.currentOpenItem=null;
			    this.orderStateObj=orderObj;
			};
			
			
			salesForm.prototype.scrollToItem=function(item){
			    //scrolls to form? or item in form?
			    //add dummy element, remove
			    var tmpel=new Element('a',{'href':'#tmp'});
			    // window.location.hash=?
			
			};

			salesForm.prototype.loadItemPage=function(linkelement,scrollTo){
			    var linktarget=this.linktarget;
			    var url=linkelement.retrieve('targetlink');
			    this.currentOpenItem=linkelement.retrieve('itemObject');
			    var formObj=this;
			    //jump to section optional
			    if(scrollTo==true && linkelement.hasClass('local')==false){
			         window.location.hash=this.pagesection;
			    };
			    //loading icon
			    loadingIcon(linktarget);
			    var req=new Request.HTML({evalResponse:true, async:true, evalScripts:false, method:'get',url:url,
            	    onSuccess: function(html){
                        	$(linktarget).set('html','');
                			$(linktarget).adopt(html);
                	        //convert any intlinks in the page
                	        formObj.orderStateObj.ConvertPageProductLinks();
                	        //add 'buy now'/add to cart button? what's wrong here?
            		        formObj.addToCartBox();

            	        	},
                     onFailure: function(){
                        	//error message
                    		$(linktarget).set('html','request failed...');
                    		}   				
                     });
                     //do request
            		req.send();	
                    setEducationalInfo(linkelement); 
            		//set style of any activeintlink elements back to intlink
	    	        var intlinks=$$('.activeintlink');
		    		for (var x=0, n=intlinks.length; x<n; x++){
			    	    var item=intlinks[x];
        		    	item.removeClass('activeintlink');
		        	    item.addClass('intlink');
				        };
					 //set style to activeintlink
    				 //set all 'intlinks' with same href to activeintlink
    	    		setActiveIntLinks(url);             			

			};
			
						
			//TODO: enhance this
			salesForm.prototype.addToCartBox=function(){
			    //might ultimately be more complex, show summary etc
			    var item=this.currentOpenItem;    //so now we know everything about it
			    if(item==null){
			        return;
			    };
			    //doens't work through non-form links!
			    //don't show anything if not actual product
                if(item.linkOnly==true || item.type=='course'){
                    return;
                };
			    var button=new Element('div', {'class' : 'span-4 append-3 last '});
			    var submit=new Element('input',{'type':'submit','name':'Submit','value':'Add to cart','class':'submitbutton'});
			    //var link=new Element('a');
			    //link.set('text','Add to cart');
			    //link.set('href','#add');
			    submit.store('itemObj',item);
			    submit.store('formObj',this);
			    submit.addEvent('click',function(){
			        var order=this.retrieve('formObj').orderStateObj;
			        order.addOne(this.retrieve('itemObj'));
			        //update apearance..?
			        //scroll to entry on form
			        //this.retrieve('formobj').scrollToItem(this.retrieve('itemobj'));
			    });
			    
			    button.adopt(submit);
			    this.linktarget.adopt(button);
			
			};
			
			orderState.prototype.ConvertPageProductLinks=function(){
			    //converts prodlinks on page to int links w/scrolling to section...?
			    //prodlinks are called prodlink with class name of target order form top
			    for(var i=0, l=this.forms.length; i<l ; i++){
			        var formid=this.forms[i].top.get('id');
			        var links=$$('.prodlink.' + formid);
			        if(links.length>0){
    			        //do stuff common here
	    		        var formObj=this.forms[i];

    			        for(var li=0, ll=links.length; li<ll ;li++){
                            //do something...?
                                    
	    		                //much the same as for product links, but with extra scroll to pagesection anchor
		    	                var item=links[li];
			                    var target=item.getProperty('href');
			                    item.store('targetlink',target);
			                    item.store('formobject',formObj);
                                //href should? match
                                var itemObj=this.urlItemMatch(target);
                                item.store('itemObject',itemObj);
			                    item.removeClass('prodlink');
			                    item.addClass('intlink');
                                item.addEvent('click',function(){
                                    //scroll to formObj anchor
                                    //set target to loading icon
                                    var targetForm=this.retrieve('formobject');
                                    targetForm.loadItemPage(this,true);     
                                    return false;
                                });                 
    			            };
    			        };
			        
			    };
			};
						
            salesForm.prototype.convertProductLinks=function(){
                //turn prodlinks into internal links...I guess
                var links=$(this.top).getElements('a.prodlink');
                var formObj=this;
                for (var i=0, l=links.length; i<l; i++){
                    //do whatever here
                    //need to save link to actual item element
                    //could do all of this on drawing form?
                    var item=links[i];
                    var target=item.getProperty('href');
                    item.store('targetlink',target);
                    item.store('formobject',formObj);
                    //item.setProperty ('href','#'+this.pagesection +'?/'+target.substring(0,target.length-4));	//turn href into anchor -'.htm'
                    item.removeClass('prodlink');
                    item.addClass('intlink');
                    item.addEvent('click',function(){
                        //set target to loading icon
                        formObj.loadItemPage(this,false);                             
                        return false;
                    });
                };
            };
            			
			orderState.prototype.loadDefaultPages=function(){
			    //load first item in each form
			    for(var i=0, l=this.forms.length; i<l ; i++){
			        var links=$(this.forms[i].top).getElements('a.intlink');
			        if(links.length>0){
			            //load first
			           links[0].fireEvent('click');
			        };
			    };
			};

			
			orderState.prototype.redrawForms=function(){
			    //redraws forms after a change in country/currency/edu			    
			    //need to destroy currency pickers
			    //something silly about this...
                    this.currencyPickers=null;
                    this.currencyPickers=new Array();
			    for (var f=0, fl=this.forms.length; f< fl; f++){
			        var curForm=this.forms[f];
			        //get info from form about top,linktarget,style
			        var top=curForm.top;
			        var target=curForm.linktarget;
			        var style=curForm.style;
			        var pagesection=curForm.pagesection
			        top.set('html',''); //woa that's gonna kill the currency picker, everything!			        
			        this.forms[f]=new salesForm(top,target,style,pagesection,this);

			        //populate
			        var prodtype
			        if(style=='courses'){
			            prodtype='course';
			        }else{
			            //whoops how to handle 'basic' and 'download'?
			            //match?
			            prodtype='basic download';
			        };
			        this.addCurrencyPicker(style,top);
			        this.addCatalogHeaders(style,top);
			    
  			        for (var i=0, l=this.catalog.products.length; i< l; i++){
  			            var currentItem=this.catalog.products[i];
  			                //if (currentItem.type==prodtype){
  			                if (prodtype.indexOf(currentItem.type)>= 0){
                            currentItem.addToForm(this.forms[f],this.usd,this);
                        };
			        };
			        this.forms[f].convertProductLinks();    
			    };
			    //refresh the order
			    this.MigrateOrderToUpdatedForms();
			    this.refreshShippingOptions();	
			    this.refreshOrder();	    
			};
			
			
			orderState.prototype.addShippingForm=function(targetForm){
			    //add shipping options form based on country
			    var shipContainer=new Element('div', {'class' : 'span-11 last shipcontainer'});   //doesn't that vary?
			    shipContainer.set('text','default shipping form here');
				shipContainer.inject(targetForm,'after');
                this.shippingPickers.push(shipContainer);
			    //now just call refresh 
			    this.refreshShippingOptions();
			};
			
			orderState.prototype.refreshShippingOptions=function(){
			    //pick out only relevant shipping options
			    //get currently picked shipping, if match found use it, otherwise use default of first one
			    var currShip=this.selectedShipping;
			    var shippingMatch=false;

			    var currentOptions=new Array();
			    var testCountry=this.getCountry();
			    for(var i=0, l=this.catalog.shipping.length; i<l; i++){
			        if(this.catalog.shipping[i].country==testCountry){
			            currentOptions.push(this.catalog.shipping[i]);
			            if(this.catalog.shipping[i].id==currShip){
			                shippingMatch=true;			            
			            };
			        };
			    };
			    var optionsType;
			    //if 0 length, nothing, if 1, fixed, >1 radio button
			    if(currentOptions.length==0){
			        optionsEl=new Element('div',{'class':'span-8 prepend-2 shipoptions'});
			        optionsEl.set('text','ERROR: no shipping options applicable');	
    			    for(var p=0,pl=this.shippingPickers.length; p<pl; p++){
    			        var picker=this.shippingPickers[p];
    			        //empty out
    			        picker.empty();
    			          			        
    			    };
    			    //quit?
    			    return;			        
			    };
			    for(var p=0,pl=this.shippingPickers.length; p<pl; p++){
			        var picker=this.shippingPickers[p];
			        //empty out
			        
			        
			        
			        picker.set('html','');
			        var optionsEl=this.generateShippingPickForm(currentOptions,p);
			        picker.adopt(optionsEl);

			        
			    };
			    //if no match found use default
			    if(shippingMatch!=true){
			        currShip=currentOptions[0].id;
			    };
			    this.PickShipping(currShip);
			};
			
			orderState.prototype.PickShipping=function(shipID){
			    //set current picked shipping
			    //select/deseelect in all shippingPickers
                //set 'c' property in orderstate			    
                this.selectedShipping=shipID;
                this.refreshOrder();
                
			};
			
			orderState.prototype.generateShippingPickForm=function(options,pickerindex){
			    //create option group 
			    var parent=new Element('div', {'class' : 'span-11 last'});
			    if(options.length==1){
			        //simpler, one un-unpickable choice...is or ain't it part of the form?
			        //hmm, how to pick? do something in orderupdate? add prop to shipping?
			        var iteminput=new Element('input',{'type':'hidden','value':'1','name':options[0].id});
			        parent.adopt(iteminput);
			        var description=new Element('div',{'class':'partlabel span-8 prepend-1'});
			        description.set('text',options[0].desc);
			        parent.adopt(description);
			        if(options[0].price > 0){
			            var price=new Element('div',{'class':'price span-1 last'});
			            price.set('text',options[0].price);
			            parent.adopt(price);
			        };
			    }else{
			        //make each an option...custom js handles pick/unpicking?
			        for(var i=0,l=options.length;i<l;i++){
    			        //would have to pick if it's the picked one
    			        var rowcontainer=new Element('div', {'class' : 'span-11 last'});
    			        //problem...name needs to be unique to that picker
    			        var inputHolder=new Element('div',{'class':'partnumber span-1'});
    					var iteminput=new Element('input',{'type':'radio','value':options[i].id,'name':'p'+pickerindex});
    					inputHolder.adopt(iteminput);
    					//attach event
    					var orderObj=this;
    					iteminput.addEvent('click',function(){
    					    orderObj.PickShipping(this.get('value'));
    					});			        
			            var description=new Element('div',{'class':'partlabel span-8'});
			            description.set('text',options[i].desc);
			            var price=new Element('div',{'class':'price span-2 last'});
					    price.set('text',options[i].price); //"price" will be in approp currency?
			            rowcontainer.adopt(inputHolder);
			            rowcontainer.adopt(description);
			            rowcontainer.adopt(price);
			            parent.adopt(rowcontainer);
			        };
			    };
			    return parent;
			};



            orderState.prototype.enableShippingOptions=function(enable){
                //set enable/disable on shipping pickers
                var setting=true;
                if(enable==true){setting=false};
                for(var i=0,l=this.shippingPickers.length; i<l ; i++){
                
                    var parent=this.shippingPickers[i];
                    var inputs=parent.getElements('input');
                    for(var ii=0,ll=inputs.length;ii<ll;ii++){
                        inputs[ii].set('disabled',setting);
                    };
                };
            
            };
			
			orderState.prototype.updateShippingPickers=function(){
			    //select/deselect shipping options...
			    for(var i=0, l=this.shippingPickers.length; i<l;i++){
			        //for each shipping picker set
			        //look for 'option' elements
			        //compare name to selectedShipping, pick/unpick
			        var parent=this.shippingPickers[i];
			        var options=parent.getElements('input[type=radio]');
			        for(var ii=0,ll=options.length;ii<ll;ii++){
			            if(options[ii].get('value')==this.selectedShipping){
			                //select
			                options[ii].set('checked',true);
			            }else{
			               options[ii].set('checked',false);

			            };
			        };
			    };
			};

			
			orderState.prototype.addSalesForm=function(top,target,mode,targetpagesection){
			    //make, add to form array
			    //might want to have mini-form for one product? I.e. more trad. product listings
			    top.set('html','');
			    var newform= new salesForm(top,target,mode,targetpagesection,this); 
			    this.forms.push(newform);
			    
			    var prodtype
			    if(mode=='courses'){
			        prodtype='course';
			    }else{
			        prodtype='basic download';
			    };
			    
			    this.addCurrencyPicker(mode,top);
			    this.addCatalogHeaders(mode,top);
			    
			    //woahwoahwoah this needs to be more complex for
  			    for (var i=0, l=this.catalog.products.length; i< l; i++){
  			        var currentItem=this.catalog.products[i];
  			        if (prodtype.indexOf(currentItem.type)> -1){
                        currentItem.addToForm(newform,this.usd,this);
                    };
			    };
			    this.addSubtotalsAndSubmit(mode,top);

			    if(prodtype!='course'){
			        this.addShippingForm(top);
			    };
                //
                newform.convertProductLinks();
            };
			
			
			orderState.prototype.addSubtotalsAndSubmit=function(productTypes,targetForm){
			    //would be nice to not put this stuff 'in' the form, so that it doesn't have to be recreated
			    //place "after" the targetform
			    //need to be props of orderstate because order forms get replaced
			    var submitContainer=new Element('div',{'class':'span-6'});
			    submitContainer.inject(targetForm,'after');
                //something silly here...all these params should be props of orderState, or calculated when product string refreshed?
                var merchantNumber='1739';
                if(this.usd==true){merchantNumber='8036'};
               	var theform=new Element('form',{'method':'post','action':'https://secure.internetsecure.com/process.cgi'});
				submitContainer.adopt(theform);
				var merch=new Element('input',{'type':'hidden','name':'MerchantNumber','value':merchantNumber});
				theform.adopt(merch);
				var lang=new Element('input',{'type':'hidden','name':'language','value':'english'});
				theform.adopt(lang);
				var returnurl=new Element('input',{'type':'hidden','name':'ReturnURL','value':'http://www.hydraulicdesign.net/thank-you.htm'});
				theform.adopt(returnurl); 
				//product string here
				//hmm, do we really want to update this stuff on-the-fly? yeah, less scripting?
				var products=new Element('input',{'type':'hidden','name':'Products','value':this.productstring,'class':'productstring'});
				theform.adopt(products);  
				//want to save the submit buttons
				var submit=new Element('input',{'type':'submit','name':'Submit','value':'Securely Process Order','class':'submitbutton'});
				theform.adopt(submit);
                this.submitButtons.push(submit);                
                //now add a total label
				var totlabel=new Element('div',{'class':'span-3 totallabel'});
				totlabel.inject(submitContainer,'after');
				totlabel.set('text','Subtotal');
				//now add div for actual total
				//TODO:separate 'trianing' & 'products' subtotals
				var totholder=new Element('div',{'class':'span-1 last subtotal'});
				totholder.set('text','0');
				totholder.inject(totlabel,'after');
                //store these elements with orderstate
			    this.productStringInputs.push(products);
			    this.submitForms.push(submitContainer);
			    this.totalLabels.push(totlabel);
			    this.totalNumbers.push(totholder);
			    //disable submit buttons for now
			    this.setSubmit(false);
			    this.setSubtotalLabels();
			};

		    orderState.prototype.setSubtotalLabels=function(){
		        //find totalLabel property of all forms
		        for( var i=0, n=this.totalLabels.length ; i<n; i++){
		            var totalLabel=this.totalLabels[i];
		            //want to make smarter for 'products/services'
		                var labelText='US Dollar Total';
                        if(this.usd==false){
                            labelText='Canadian Dollar Total';
                        };		            
		                totalLabel.set('text',labelText);
		        };
		    };
            orderState.prototype.setSubmit=function(enable){
					//sets submit buttons
					var button=this.submitButtons;
					for( var i=0, n=button.length ; i<n; i++){				 			    
					if(enable){
						$(button[i]).setProperty('disabled',false);
						$(button[i]).setProperty('value','Process Order Securely');
					}else{
						$(button[i]).setProperty('disabled',true);
						$(button[i]).setProperty('value','Process Order Securely');
					};
					};
			
				};

			orderState.prototype.addCatalogHeaders=function(productTypes,targetForm){
			    
			    if(productTypes=='courses'){
			        //courses header
			        var headernstudents=new Element('div',{'class':'span-3 prepend-1 orderheader'});
			        headernstudents.set('text','Enter Number of Students');
			        targetForm.adopt(headernstudents);
    				var priceheader=new Element('div',{'class':'span-1 prepend-5 orderheader last headercurrency'});
    				var pht='$US';
    				if(this.usd==false)pht='$CDN';
    				priceheader.set('text',pht);
                    targetForm.adopt(priceheader);			        
			        
			    }else{
			        //products header
				    var headerq=new Element('div',{'class':'span-2 append-5 orderheader'});
				    headerq.set('text','Enter Quantity');
    				var stockstatusheader=new Element('div',{'class':'span-2 orderheader'});
    				stockstatusheader.set('text','Usually Ships In');
    				var priceheader=new Element('div',{'class':'span-2 last orderheader'});
    				var pht='$US';
    				if(this.usd==false)pht='$CDN';
    				priceheader.set('text',pht);
				    targetForm.adopt(headerq);
				    targetForm.adopt(stockstatusheader);
				    targetForm.adopt(priceheader);
				    targetForm.adopt(priceheader);
			    };
			};


			
            orderState.prototype.addCurrencyPicker=function(productTypes,targetForm){
                //make the element based on the product types
                //store currencySelect array
                //which come down to whether country or just currency
               var parent=new Element('div',{'class':'span-9 last formselect'});
               targetForm.adopt(parent);
               var pickerObj=new currencySelect(parent,pickType); 
                var pickType='country';
                var label=new Element('div',{'class' : 'small formselnote span-3 '});
                label.set('text','Please select from where you are ordering');
                if(productTypes=='courses'){
                    //then only currency
                    pickType='currency';
                    label.set('text','Please select your currency');    
               };
               parent.adopt(label);
   			    //add options
                var optionsWrapper=new Element('div',{'class':'span-5 last formselect'}); //wrapper  
                parent.adopt(optionsWrapper);	
			    
                //how to handle showing/hiding based on selections?
                //how to generically handle events? and stuff?
                //object would have...the element,                
                if(pickType=='currency'){
                    //add 'canadian' and 'us'
                    //might want edu disc. too, butt...

                    var uslink=new currencyOption(optionsWrapper,this,'US Dollars','USD','ALL','ALL');

                    pickerObj.options.push(uslink); 
                   var canlink=new currencyOption(optionsWrapper,this,'Canadian Dollars','CDN','ALL','ALL');     

                    pickerObj.options.push(canlink); //add to array of options in picker ob

                }
                else{
                    //pickType=='country'
                    pickerObj.options[0]=new currencyOption(optionsWrapper,this,'Canada','CDN','CAN',false);
                    pickerObj.options[1]=new currencyOption(optionsWrapper,this,'Canada Educational','CDN','CAN',true);
                    pickerObj.options[2]=new currencyOption(optionsWrapper,this,'US','USD','US',false);
                    pickerObj.options[3]=new currencyOption(optionsWrapper,this,'US Educational','USD','US',true);
                    pickerObj.options[4]=new currencyOption(optionsWrapper,this,'All Other countries','USD','OTHER',false);
              
                };
                
 
                this.currencyPickers.push(pickerObj);
            };
			
			function currencySelect(parent,type){
			    //picker for currency
			    //depends on country restriction params of objects in form
			    //what to store?
			    this.top=parent;
			    this.type=type;
			    this.options=Array();
			};
			
            function currencyOption(parentEl,objOrderState,text,currency,country,edu){
                //the option parameters set what clicking sets...

                this.el=new Element('span');
                parentEl.adopt(this.el);
                this.el.set('text',text);
                this.text=text;
                this.currency=currency;
                this.country=country;
                this.edu=edu;
                this.parentOrder=objOrderState;
                this.setLink();

            };

            currencyOption.prototype.setLink=function(){
                //sets to link or not based on current cnd/edu/etc settings
                //bit of discrepancy between country/currency settings right now from parentOrder to this
                //a lot of what they call "business logic" in here
                var testUSD=false;
                var testEdu=false;
                var testNaOnly=true;
                if (this.currency=='USD'){testUSD=true;};
                if (this.edu==true){testEdu=true};
                if (this.country=='OTHER'||this.country=='ALL'){testNaOnly=false};
                //this works for product links
                if (this.parentOrder.usd==testUSD && this.parentOrder.educational==testEdu && testNaOnly==this.parentOrder.naOnly){
                    this.linkOff();
                //now for curr only?
                }else if(this.country=='ALL' && this.parentOrder.usd==testUSD ){
                    this.linkOff();
                }else{
                    this.linkOn();
                };           
            };
            
            currencyOption.prototype.linkOn=function(){

                var newEl=new Element('a');
                newEl.replaces(this.el);
                this.el=newEl;
                this.el.set('text',this.text);
                //use first three letters of text?
                this.el.set('href','#' + this.text.substr(0,2));
                //set events
                var thisLink=this;
                this.el.addEvent('click',function(){
                    //determine how to set usd/naOnly/educational based on this curr/country/edu
                    //not everything necessarily changes
                    var currentOrder=thisLink.parentOrder;
                    if(thisLink.currency=='USD'){
                        currentOrder.usd=true
                    }else{
                        currentOrder.usd=false;
                        };
                    if(thisLink.country=='OTHER'){
                        currentOrder.naOnly=false;
                    }else if(thisLink.country=='CAN' || thisLink.country=='US'){
                        currentOrder.naOnly=true;
                    };
                    if(thisLink.edu==true){
                        currentOrder.educational=true;
                    }else if (thisLink.edu==false){
                        currentOrder.educational=false;
                    }; 
                    if(thisLink.country=='ALL' && thisLink.currency=='CDN' && currentOrder.naOnly==false){
                        currentOrder.naOnly=true;
                    };  
                    //now regen all forms as necessary
                    currentOrder.redrawForms();                     
                    return false;
                });
                
            };
            currencyOption.prototype.linkOff=function(){
                var newEl=new Element('span');
                newEl.replaces(this.el);
                this.el=newEl;
                this.el.set('text',this.text);
               
            
            };
            
            
            
            function orderItemFromCatalog(copyfrom){
                

                        //set basics
                        this.id=copyfrom.id;
                        //just copy text of link
                        var tmp=new Element('div');
                        tmp.set('html',copyfrom.titlelink);
                        this.desc=tmp.get('text');
                        tmp.destroy();
                        this.cad=copyfrom.cad;
                        this.usd=copyfrom.usd ;             
                        this.type=copyfrom.type;
                        this.taxflags=copyfrom.taxflags;
                        //set possible optional    
                
            };

			function item(){
			    //product or service
			    //'picked' status
			    //partnumber 
			    //description
			    //maybe date?
			    //entered quantity
			    //has a price, tax parameters, products it excludes (download, etc.)
			    //might have discounts based on other selected products
			    //element(s) for inputting it
			    //we don't really need to 'know' any of this stuff often, but this is how to organize how to add it
			    //would like to not have to 'code' the layout, use a 'prototype'
			    //diff item types would just be variants on this, not have to use 'inheritance'
			    //type of item property? prolly, would be clever if never needed
			    this.type=null; //could be basic, course,ship,download
			};
			
			orderState.prototype.refreshOrder=function(){
			    //update product string, totals, submit buttons
			    //update exclusions? hmm no, more part of the input?
			    //update shipping(possibly the same thing?)
			    this.updateMerchId();
			    this.updateShippingPickers();
                this.regenProductString();
                this.displayTotals();
                //enable-disable buttons
                if(this.subTotal > 0){
                    this.setSubmit(true);
                }else{
                    this.setSubmit(false);
                };
                this.setSubtotalLabels();	
			
			
			};
			
			orderState.prototype.updateMerchId=function(){
			    //find the "merchantnumber" elements
			    var merchIDs=$$('input[name=MerchantNumber]');
			    var merchantNumber='1739';
                if(this.usd==true){merchantNumber='8036'};
			     //var productEntries=$(document.body).getElements('input[name='+ this.selected[i].id +']');
                for(var i=0, l=merchIDs.length; i<l; i++){
                    merchIDs[i].setProperty('value',merchantNumber);
			    }
			};
			
			orderState.prototype.displayTotals=function(){
			    //for each in totalNumbers, set it's text
			    //add for discount .courseDiscount
			    for(var i=0, l=this.totalNumbers.length; i<l; i++){
			        if(this.courseDiscount==false){
			        //will make more complex somehow...
			        this.totalNumbers[i].set('text',this.subTotal);
			        }
			        else{
			        
			        this.totalNumbers[i].set('text',this.subTotal + ' with bonus');
			        };
			    };
			};
			
			orderState.prototype.applyCourseDiscount=function(item){
			    //look through selected, add up products/download total
			    //returns discount amount?
			    var prodTotal=0;
			    var qdiscount=100;
			    if(this.usd==false){qdistcount=120};
  			    for (var i=0, l=this.selected.length; i< l; i++){
                    var item=this.selected[i];
                    if(item.type!='course'){
                        prodTotal=prodTotal + item.usd * item.quantity;
                    }
			    };
			    if(prodTotal>=395){ 
			        return qdiscount;
			    }
			    else{
			        return 0;
			    };
			};
			
			
			orderState.prototype.regenProductString=function(){
			    //for now, puts in 'productstring' div
			    //should also update tmps, tots?
			    //put here so that we don't have to go through this more than once?
                var productstring='Price::Qty::Code::Description::Flags'; 
                var subtotal=0;
                var anythingToShip=false;
                var productsTotal=0;
                var firstCourseFound=false;
                var discount=0;
                this.courseDiscount=false;
  			    for (var i=0, l=this.selected.length; i< l; i++){
  			        discount=0;
                    var item=this.selected[i];
                    if(item.type=='basic'){
                        anythingToShip=true;
                    }
                    else if (item.type=='course' && firstCourseFound==false){
                        //test for discount quantity
                        discount=this.applyCourseDiscount(item);
                        firstCourseFound=true;
                    };
                    var price=item.usd;
                    if(this.usd==false){price=item.cad};
                    var desc=item.desc;
                    //how to tweak for discount with quantity? only want to apply once...
                    if(discount > 0 ){
                        this.courseDiscount=true;
                        var itemtotal=item.quantity * price;
                        desc=desc + ' with discount';
                        if(item.quantity==1){
                            price=price-discount;
                        }else{
                            //apply equiv discount based on quantity?
                            price=price-(discount/item.quantity);
                        };
                        //same as below...but shouldn't be?
                        productstring=productstring+'|'+price+'::'+item.quantity+'::'+item.id+'::'+desc+'::'+item.taxflags;
                        subtotal=subtotal+(item.quantity * price);  
                    }                    
                    else{
                        productstring=productstring+'|'+price+'::'+item.quantity+'::'+item.id+'::'+desc+'::'+item.taxflags;
                        subtotal=subtotal+(item.quantity * price);  
                    }
			    };
			    //add shipping
			    //but only if any products selected!
			    if(this.selectedShipping!='' && anythingToShip==true){
			        //enable shipping options
			        this.enableShippingOptions(true);
			        //find shipping object
                    for(var i=0, l=this.catalog.shipping.length; i<l; i++){
                        var currShip=this.catalog.shipping[i];
                        if(currShip.id==this.selectedShipping){
                            //add it...but only if any products selected?
                            //price is cad or usd..better not screw up!
                             productstring=productstring+'|'+currShip.price+'::1::'+currShip.id+'::'+currShip.desc+'::';
                             subtotal=subtotal+currShip.price;

                        };
                    };			        
			    }else if(anythingToShip==false){
			        //dim the shipping options
			        this.enableShippingOptions(false);
			    };
			    
			    
			    this.subTotal=subtotal;                          
              	//set product string in forms
              	
                for (var i=0,l=this.productStringInputs.length; i<l; i++){
                    this.productStringInputs[i].set('value',productstring);
                }; 	
			};


            orderState.prototype.MigrateOrderToUpdatedForms=function(){
                //sorta similar to 'update' but no new entry
                //need to make sure selected products are still in visible forms
                
  			        for (var i=0, l=this.selected.length; i< l; i++){
  			            //what the...all getting set to the same value?
  			            var productEntries=$(document.body).getElements('input[name='+ this.selected[i].id +']');
  			            if (productEntries.length==0){
  			                //remove from selected...something about this wrong
  			                this.selected.remove(i);
  			                //i=i-1; //why don't I need to adjust i?
  			            }else{
  			                //set values..something wron ghere
  			                for (var ii=0, ll=productEntries.length; ii< ll; ii++){
                                productEntries[ii].setProperty('value',this.selected[i].quantity);
			                };  
  			            };
  			        };              
            };


			orderState.prototype.addOne=function(changeditem){
			    //updates order based on incrementing one item
			    //how to do quickly? find it's quanitity element, increment, fire OrderInput?
			    //nah, don't have to check, totally diff sequence
			    var alreadyPicked=false;
			    var quantity=1;
			    for (var i=0, l=this.selected.length; i< l; i++){
			            if(this.selected[i].id==changeditem.id){
			                alreadyPicked=true;
			                quantity=parseFloat(this.selected[i].quantity)+1;
			                this.selected[i].quantity=quantity;			                			                
			                break;
			            };
			    };
			    if(alreadyPicked==false){
			        //new entry
			            var newitem=new orderItemFromCatalog(changeditem);
			            newitem.quantity=quantity;
			            //update course setting as needed
			            if (changeditem.type=='course'){
			                  //if it's a course, orgig labal+date=new label			                    
			                  //find selected option
			                  var parent=quantityelement.getParent();//gets the div
			                  var parent=parent.getParent();    //gets container
			                  var datepicker=parent.getElement('select'); //WHAT THE?
                                //get picked from select element...?
                              var pickeddate=datepicker.options[datepicker.selectedIndex].text;
			                  newitem.desc=newitem.desc+' '+pickeddate;   
			             };

			            this.testProductExclusions(newitem);
			            //add to the array
			            this.selected.push(newitem);			    
			    };
			    //update all common elements
			    var allInputs=$(document.body).getElements('input[name='+ changeditem.id +']');
  			    for (var i=0, l=allInputs.length; i< l; i++){
                     allInputs[i].setProperty('value',quantity);
			    };
		    			    
			    this.refreshOrder();			    
			};					

            //should be made more generic?
			orderState.prototype.orderInput=function(changeditem,quantityelement){
                //updates order based on change to entry of item...
                //make fancier to handle 'add to cart' button?
                //see if added or removed
                //first case--removed
                var quantity=quantityelement.getProperty('value');
                //need to update all common elements with that value
                var allInputs=$(document.body).getElements('input[name='+ changeditem.id +']');
                //changing this won't fire keyup event
                if(allInputs.length>1){
  			        for (var i=0, l=allInputs.length; i< l; i++){
                        allInputs[i].setProperty('value',quantity);
			        };
			    };
                if(quantity==''){
                    //removed or bad input
                    //see if in selected array
  			        for (var i=0, l=this.selected.length; i< l; i++){
			            if(this.selected[i].id==changeditem.id){
			                //remove from selected array
			                this.selected.remove(i);
			                break;
			            };
			        };
                }
                else{
                    //see if it's in array, if so update something somehow
                    var found=false;
  			        for (var i=0, l=this.selected.length; i< l; i++){
			            if(this.selected[i].id==changeditem.id){
			                //update the quantity
			                this.selected[i].quantity=quantity;
			                if (this.selected[i].type=='course'){
			                    //if it's a course, orgig label+date=new label			                    
			                    //find selected option
    			                  var parent=quantityelement.getParent();//gets the div
    			                  var parent=parent.getParent();    //gets container
    			                  var datepicker=parent.getElement('select');
                                    //get picked from select element...
                                    //get label dir from el
                                  var pickeddate=datepicker.options[datepicker.selectedIndex].text;
    			                  this.selected[i].desc=parent.getElement('a').get('text')+' '+pickeddate;   
			                    
			                };
			                found=true;
			                break;
			            };
			        };
			        if(found==false){
			            //new entry
			            var newitem=new orderItemFromCatalog(changeditem);
			            newitem.quantity=quantity;
			            //update course setting as needed
			            if (changeditem.type=='course'){
			                  //if it's a course, orgig labal+date=new label			                    
			                  //find selected option
			                  var parent=quantityelement.getParent();//gets the div
			                  var parent=parent.getParent();    //gets container
			                  var datepicker=parent.getElement('select'); //WHAT THE?
                                //get picked from select element...?
                                //TODO: handle only 1 date, no 'datepicker'
                              var pickeddate=datepicker.options[datepicker.selectedIndex].text;
			                  newitem.desc=newitem.desc+' '+pickeddate;   
			             };

			            this.testProductExclusions(newitem);
			            //add to the array
			            this.selected.push(newitem);
			        };
                
                };	    
                //update product string and other stuff
                this.refreshOrder();
                //put summary in a div somewhere for testing
              
			};

			orderState.prototype.testProductExclusions=function(addedItem){
			    //compare added item to catalog.exclusions array 
			    var testID=addedItem.id;
  
			    for (var i=0, l=this.catalog.exclusives.length; i<l; i++){
			        var currExcl=this.catalog.exclusives[i];
			        for(var ii=0, ll=currExcl.length; ii<ll; ii++){
			            if(testID==currExcl[ii]){
			                //make copy of exclusions array minus testID
			                var toRemove=currExcl.slice();
			                toRemove.remove(ii);
			                //remove from selected array the other matching items
			                for(var iii=0, lll=this.selected.length; iii<lll; iii++){
			                    var found=false;
			                    for(var e=0, el=toRemove.length; e<el; e++){
			                        if(this.selected[iii].id==toRemove[e]){
			                            found=true;
			                            break;
			                        };
			                    };
			                    if(found==true){
			                        //how to 'reset?
			                        //will need to use function to handle deselecting items or shipping toggles
                                    var allInputs=$(document.body).getElements('input[name='+ this.selected[iii].id +']');
                                    //changing this won't fire keyup event
                                    //if(allInputs.length>1){
                      			        for (var j=0, k=allInputs.length; j< k; j++){
                                            allInputs[j].setProperty('value','');
                    			        };
                    			    //};
			                        this.selected.remove(iii);
                                    lll=this.selected.length;
			                    };
			                };
			                return;
			            };   
			        };
			    };
			};
			
			
			
			orderState.prototype.urlItemMatch=function(strTest){
			    var allLinks=$$('a');
			    for(var i=0, l=allLinks.length; i<l ; i++){
			        //go through each link, look for element with matching URL and itemObject
			        var link=allLinks[i];
			        var linkstr=link.getProperty('href');
			        if(linkstr!=null){
			            if(linkstr.contains(strTest)==true){
			                var itemObj=link.retrieve('itemObject');
			                if(itemObj!=null){
			                    return itemObj;
			                };
			            };
			        };
			    };
			    return null;
			};
			
			item.prototype.addToForm=function(targetform,usd,targetorder){
			    //needs to only do this if of appropriate edu/country
			    //compare naOnly to
                        //objitem.naonly=naOnly;
                        //objitem.edu=educational;
                        //objitem.kit=kits;  	
                //don't show educational outside edu
                if((targetorder.educational==false && this.eduOnly==true) || (targetorder.educational==true && this.comOnly==true)){
                    return;                
                };
                //how to only show int when outside
                if(targetorder.naOnly==false && this.naonly==true){
                    return;
                };
 		        //these objects should keep track of how many copies of themselves there are			   
			    var container=new Element('div',{'class' : 'span-11 last'});
			    //might have more than one, can't store part numbe in id, store in name
			    var quantity=new Element('input',{'type':'text','value':'','size':'2','maxlength':'2','name':this.id});
			    //make container div for it
			    var quantitybox=new Element('div',{'class':'partnumber span-1'});
                //make label with link..size would be diff for product vs class
                var partlabel=new Element('div',{'class':'datepick span-6'});
                partlabel.set('html',this.titlelink);
				//look for a and set class to prodlink?
				var productlinks=partlabel.getChildren('a');
				//more than one or only one? if more than one there could be a problem! or just a gap...
				for(var links=0, numlinks=productlinks.length; links<numlinks ; links++){	
				    //turn into prodlink or intlink?		
					productlinks[links].setProperty('class','prodlink');
					productlinks[links].store('itemObject',this);
											
				};
                var price=new Element('div',{'class':'price span-1 last'});
                if(usd==true){
                    price.set('text',this.usd);
                }else{
                    price.set('text',this.cad);
                };
                
			    //add input events
			    var inputItem=this;
			    quantity.addEvent('keyup',function(){
			        //verify entry
			        var userinput=this.getProperty('value');
			        var test=userinput.toInt();
			        //if invalid, set to nothing
					if(isNaN(test) || test < 1){this.setProperty('value','');};
    			    //somehow update the currentorder...brute force whole thing? yes 'cause of exclusions
    			    //want to change 'top' object from the product list to the order
			        targetorder.orderInput(inputItem,this);
			    });

                if(this.linkOnly==true){
			        //hide quantity box
			        quantity.addClass('hidden');
                };


                if(this.linkOnly==true){
                         partlabel.setProperty('class','partlabel span-8 linkonly');
                };

                if(this.type=='basic' || this.type=='download'){
                    container.adopt(quantitybox);
                    quantitybox.adopt(quantity);
                    container.adopt(partlabel);
                    //add stock status
                    var status=new Element('div',{'class':'stockstatus span-2'});
                    status.set('text',this.stockstatus);
                    container.adopt(status);
                    container.adopt(price);
                }else if (this.type=='course'){
                    container.adopt(partlabel);
                    container.adopt(quantitybox);
                    quantitybox.setProperty('class','span-2 prepend-1 partnumber')
                    price.setProperty('class','span-2 last price');
                    quantitybox.adopt(quantity);
                    //change partlabel class
                    partlabel.setProperty('class','partlabel span-8 prepend-3 last');
                    
                    if(this.linkOnly==true){
                        partlabel.setProperty('class','partlabel span-8 prepend-1 linkonly');
                    };

                    //add class selection
                    var classdates=new Element('div',{'class':'span-6'});
                    //if more than one class date, build combobox
                    //TODO:make combobox invisible if only 1 startdate
                        var combo=new Element('select',{'name':this.id+'pick','class':'datepick'});
                        //select first option...
                        var firstoption=new Element('option',{'selected':'selected'});
                        firstoption.set('text',this.startdates[0]);
                        combo.adopt(firstoption);
                        if(this.startdates.length>1){
                            for(var i=1,l=this.startdates.length; i<l ;i++){
                                var option=new Element('option');
                                option.set('text',this.startdates[i]);
                                combo.adopt(option);
                            };
                        }else{
                            //make invisible, set text
                            classdates.set('text',this.startdates[0]);
                            combo.setStyle('display','none');
                        };
                        classdates.adopt(combo);
                        combo.addEvent('change',function(){
                        //would have to find 'parent,' get to label? oh hell just add as property? 
                        var parent=this.getParent();
                        parent=parent.getParent();
                        var inputel=parent.getElement('input[type=text]');
                        targetorder.orderInput(inputItem,inputel);
                        });	    

                                        
                    container.adopt(classdates);
 
                   container.adopt(price);
               
                
                };
                
                targetform.top.adopt(container);
			    //add similar to option
			    
			};
						
			function itemList(){
			   //collection of products
			   //array of items
			   this.products=new Array();
			   this.exclusives=addBasicExclusions();
			   //built from external files
			   //it 'knows' how to read data from the files, since could change
			   //this.shipping=new Array(); //array of shipping options, they are just 'items, but might as well be separate
                //make shipping own array, but try to treat the same..?
                this.shipping=new Array();
			    var xpresscad=new item(); 
			    xpresscad.type='shipping';
			    xpresscad.desc='Free ExpressPost Shipping';
			    xpresscad.country='CAN';			    
			    xpresscad.id='SHIPXP';
                xpresscad.price=0;
                this.shipping.push(xpresscad);
                var basicUS=new item();
                basicUS.type='shipping';
                basicUS.desc='Free Regular Airmail(1-2 weeks typical, not recommended for high-value orders)';
                basicUS.id='SHIPUSB';
                basicUS.country='US';
                basicUS.price=0;
                this.shipping.push(basicUS);
                var xpressUSA=new item();
                xpressUSA.type='shipping';
                xpressUSA.desc='ExpressPost USA Shipping(3-5 days)';
                xpressUSA.id='SHIPXPUS';
                xpressUSA.country='US';
                xpressUSA.price=20;
                this.shipping.push(xpressUSA);
                var fedex=new item();
                fedex.type='shipping';
                fedex.desc='FedEx via Canada Post Priority Courier(1-2 days)';
                fedex.id='SHIPFEDX';
                fedex.country='US';
                fedex.price=40;
                this.shipping.push(fedex);
                var intAir=new item();
                intAir.type='shipping';
                intAir.desc='International Airmail Shipping';
                intAir.id='SHIPINT';
                intAir.country='OTHER';
                intAir.price=15;
                this.shipping.push(intAir);
			}

            function addBasicExclusions(){
                var arrExclude=new Array();
                //fvs
                arrExclude[0]=new Array('FVS','FVSDLD','FVSSPDLD');
                //us shipping
                //any way of using this? not really needed
                //arrExclude[1]=new Array('SHIPUSB','SHIPXPUS','SHIPFEDX');
                return arrExclude;
            };

			itemList.prototype.confirmUniqueItem=function(id){
			    //see if product exists in products array
			    for (var i=0, l=this.products.length; i< l; i++){
			        if (id==this.products[i].id){
			            //should retern ref to object!  
			            return this.products[i];
			        };
			    };
                return true;			    
			};
						
			itemList.prototype.addFromFile=function(file){
			    //builds list of items from a file
			    //loads file into dummy element? doesn't keep around
			    var data=new Element('div',{'id':'importresult'});
			    var req=new Request.HTML({evalResponse:true, async:false, evalScripts:false, method:'get',url:file,
			    onSuccess: function(html){
					data.set('html','');
					data.adopt(html);
			    },
    			onFailure: function(){
   			        return false;
		    	}
			
			    });
    			//do request
	    		req.send();
                //get data, loop through
			    var rows=data.getElements('tr');
			    var naOnly=false;
			    var educational=false;
			    var kits=false;
			    var indexID=0;
			    var indexName=1;
			    var indexCDN=-1;
			    var indexUSD=-1;
			    var indexDate=-1;
			    var indexStatus=-1;
			    var eduOnly=false;
			    var comOnly=false;
				for (var i=0, l=rows.length; i < l; i++){
					var row=rows[i];
					var rowclass=row.getProperty('class');
					if(rowclass=='end'){break;};//quit if hit the end
					var data=row.getChildren();
					if(rowclass=='tabletitle'){
					    //use titles to figure out where data is...
					    //id is always at 0,Name 1
					    //if trainingform, data[2] will contain class start date
					    //what about special discounts???
					    //enable objects to set self edu discount if asked?
					    var testmode=data[2].get('text');
					    if(testmode.search(/class/i)!=-1){
					        indexDate=2;
					        indexCDN=3;
					        indexUSD=4;    
					    }
					    else {
					        //default
					        indexStatus=2;
					        indexCDN=3;
					        indexUSD=4;
					    };
					    continue;
					};
					//proper working of these is dependent upon the order of price list
					if(rowclass=='naonly'){
					    naOnly=true;
					    comOnly=true;
					    continue;
					    };
					if(rowclass=='commontoedu'){
                        comOnly=false;				    
					};
					if(rowclass=='edu'){
						naOnly=true;
					    educational=true;
					    eduOnly=true
					    continue;
					    };
					if(rowclass=='kits'){
					    kits=true;
					    naOnly=true;
					    educational=true;
					    eduOnly=true;
					    continue;
					};
					
					//now read row data, load into array of product objects
					//but only for courses
					var addNew=true;
					if(indexDate!=-1 && rowclass!='infolink'){
					    //problem:'info' links not unique! need to make unique?
					    addNew=this.confirmUniqueItem(data[indexID].get('text'));	
					    //returns the obj to add date to
					};
					
					if(addNew==true){
                       var objitem=new item();
                        //set basics..okay these need to be
                        objitem.id=data[indexID].get('text');
                        objitem.titlelink=data[indexName].get('html');
                        objitem.cad=data[indexCDN].get('text');
                        objitem.usd=data[indexUSD].get('text'); 
                        objitem.naonly=naOnly;
                        objitem.comOnly=comOnly;
                        objitem.edu=educational;
                        objitem.eduOnly=eduOnly;
                        objitem.kit=kits;
                        objitem.linkOnly=false;
                        if(rowclass=='infolink'){
                            objitem.linkOnly=true;
                            objitem.naonly=false;
                            objitem.comOnly=false;
                        
                        };                  
                        //set possible optional     
                        if(indexDate!=-1){
                            //why not just make a damn array since it's not simple to test for them
                            objitem.startdates=new Array();
                            objitem.startdates[0]=data[indexDate].get('text');
                            //add function addClassDate
                            objitem.addClassDate=addClass;
                            objitem.type='course';
                            //FOR TESTING ONLY add {TEST}
                            objitem.taxflags='{GST}{HST}'
                        };
               		    if(indexStatus!=-1){
               		        objitem.stockstatus=data[indexStatus].get('text');
               		        
               		        objitem.type='basic';
               		        //if id ends with "DLD," downloaded product
               		        if(objitem.id.endsWith('DLD')==true){
               		            objitem.type='download';
               		        };
               		        objitem.taxflags='{PST}{GST}{HST}';
           	    	    };
           		        //add to array
           		        this.products.push(objitem);           		    }
           		    else{
           		        //add start date to last obj
           		        addNew.addClassDate(objitem.startdate=data[indexDate].get('text'));
                     };
			    };
		    
			    
                //remove data...well it's never added to doc anyway?
                //return success
                return true;			    
			};
			
			String.prototype.endsWith=function(str){
			    var lastIndex=this.lastIndexOf(str);
			    return (lastIndex != -1) && (lastIndex + str.length == this.length);
			};
			
			function addClass(datetext){
			    //turns this.startdate into array if necessary, pushes datetext
			    //if not an array, is a string...uhoh
			    if (this.startdates.constructor.toString().indexOf("Array") == -1){
			        //is not an array,make one
			        var olddate=this.startdate;
			        this.startdates=new Array();
			        this.startdates[0]=olddate;    
			    };
			    this.startdates.push(datetext);
			};
						
			/////////////////////////////////////////////////////////////////////////
			//////////////////////////////////////////////////////////////////////
			//END starting over

			function setEducationalInfo(srcEl){
				//toggles 'edusmallprint' element visibility based on whether product (uh oh what about non-products?) is educational
				//looks to see if the product id--if there is one--contains "EDU" or "KIT"
				var searchel=srcEl.getParent();
				//okay, problem ehre...but what's going on?			
				if(searchel!=null){
				searchel=searchel.getParent();
				//ok, instead just use the element we want
				var partel=searchel.getElement('input');
				var testreg=new RegExp('ED|KIT');
				if ((partel != null)&&(partel.get('name').test(testreg)==true)){
					//default: turn off
					$('edusmallprint').setStyle('display','block');	
				}else{
					//default: turn off
					$('edusmallprint').setStyle('display','none');	
				};
				};			
			};
		
			function loadingIcon(target){
				//injects loading icon into the target div...centered paragraph?
				//clear out target
				$(target).set('html','');
				var loadp=new Element('p');
				loadp.setProperty('class','loadgif');
				var loading=new Element('img',{'src':'images/ajax-loader.gif'});
				loadp.adopt(loading);
				$(target).adopt(loadp);
			};
			function setMouseOverIntLinks(url){
				//set all 'intlinks' with matching url to activeintlink
				var intlinks=$$('.intlink');
				for (var x=0, n=intlinks.length; x<n; x++){
					var thislink=intlinks[x];
					if (thislink.retrieve('targetlink')==url){
						thislink.addClass('intlinkhover');
						//set style of parent bar
					var firstParent=thislink.getParent();
					var itemParent=firstParent.getParent();
					itemParent.addClass('intlinkhoverbar');
					};			
				};

			};
			function removeMouseOverIntLinks(url){
				//remove all intlinkhovers
				var intlinks=$$('.intlinkhover');
				for (var x=0, n=intlinks.length; x<n; x++){
					var thislink=intlinks[x];
						thislink.removeClass('intlinkhover');
					var firstParent=thislink.getParent();
					var itemParent=firstParent.getParent();
					itemParent.removeClass('intlinkhoverbar');

		
				};

			};
		
			function setActiveIntLinks(url){
				//set all 'intlinks' with matching url to activeintlink
				var intlinks=$$('.intlink');
				for (var x=0, n=intlinks.length; x<n; x++){
					var thislink=intlinks[x];
					if (thislink.retrieve('targetlink')==url){
						thislink.addClass('activeintlink');
						thislink.removeClass('intlink');
					};			
				};
			};		
			//actually doing stuff
			//should be in separate file?
			var theorder=new orderState();
			theorder.catalog.addFromFile('masterorderform.htm');
			theorder.catalog.addFromFile('mastertrainingform.htm');

			//now add make a form with allproducts and display it somewhere
			//theorder.addSalesForm($('extraformtest'),$('productentry'),'all','main');
			theorder.addSalesForm($('trainingorder'),$('trainingentry'),'courses','training');
			theorder.addSalesForm($('orderform'),$('productentry'),'products','store');
			
			theorder.loadDefaultPages();
			theorder.ConvertPageProductLinks();

		});