﻿var tmpOS = false;

Checkout = {

/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    properties
    
*/





/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    methods
    
*/


    attach: function(edDeskBody)
    {
        if(typeof CheckoutAttachCount == 'undefined')CheckoutAttachCount = 0;
		
		var oParent = document.getElementById('contentLeft');
		var oChild = document.getElementById('edDeskBody');
		if(!oParent || !oChild)
		{
			//If exceeded the number of determined iterations
			if(CheckoutAttachCount > 10)
			{
				throw new Error('Checkout.attach() exceeded its limit of iterations');
			}
			//Try again in 100 miliseconds
			CheckoutAttachCount++;
			setTimeout('Checkout.attach()',100);
			return;
		}
		
		//Clear parent
		oParent.innerHTML = '';
		
		//Recreate edDeskBody
		var div = document.createElement('div');
		div.setAttribute('id','edDeskBody');
		
		//Attach heading
		oParent.appendChild(this.attachHeading());
		
        switch(this.step)
        {
            case 1://initial stage
                //Attach introduction
		        this.attachIntroduction_step1(oParent);
                this.attachStep1(div);
                break;
            case 2://invoice form
                this.attachIntroduction_step2(oParent);
                this.attachStep2(div);
                break;
            case 3://final summary step
                this.attachStep3(div);
                break;
            case 4://submit form
                this.attachStep4(div);
                break;
            default:
        }
        oParent.appendChild(div);
        
       //Update mini cart
       Cart.attachMiniCart(document.getElementById('contentRight'));
    },
    
    attachIntroduction_step1: function(oParent)
    {
        var p = document.createElement('p');
        p.className = 'intro';
         
        //p.appendChild(document.createTextNode('Inspection copies can be made by schools only.'));
        p.innerHTML = 'Read our terms and conditions <a href="libraries/Terms+and+Conditions?open">here</a>.<br><br>Inspection copies can be made by schools only.';
        oParent.appendChild(p);
    },
    
    attachIntroduction_step2: function(oParent)
    {
        var p = document.createElement('p');
        p.className = 'intro';
        p.appendChild(document.createTextNode('Please enter your payment details.'));
        p.appendChild(document.createElement('br'));
        var strong = document.createElement('strong');
        strong.appendChild(document.createTextNode('Your total purchase is $' + Cart.getTotal().toFixed(2)));
        p.appendChild(strong);
        oParent.appendChild(p);
    },
    
    attachHeading: function()
    {
        switch(this.step)
        {
            case 1://initial stage
                var heading = 'Checkout';
                break;
            case 2://invoice form
                var heading = 'School/University invoice details';
                break;
            case 3://final summary step
                var heading = 'Checkout Purchase confirmation';
                break;
            default:
                var heading = '';
        }
        
        var h2 = document.createElement('h2');
        h2.appendChild(document.createTextNode(heading));
        return h2;
    },
    
    attachStep1: function(oParent)
    {
       //Attach summary
       var div = document.createElement('div');
       div.setAttribute('id','cartSummary');
       if(Cart)Cart.attachSummary(div);
       oParent.appendChild(div);
       
       //Attach form
       this.attachStep1Form(oParent);
       
    },
    
    attachStep2: function(oParent)
    {
       //Attach form
       this.attachStep2Form(oParent);
    },
    
    attachStep3: function(oParent)
    {
       //Attach summary
       var div = document.createElement('div');
       div.setAttribute('id','cartSummary');
       if(Cart)Cart.attachSummaryCheckoutStep3(div);
       oParent.appendChild(div);
       
       //Attach delivery details
       this.attachStep3DeliveryDetails(oParent);
       
       //Attach previous button
        var f = document.createElement('fieldset');
        f.className = 'step3Buttons';
        var oInput = DH.createInput('button','previousStep','Previous','25');
        oInput.className = 'button';
        var PreviousStepBtn_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            Checkout.moveBack();
        };
        DH.addEvent(oInput,'click',PreviousStepBtn_onClick);
        f.appendChild(oInput);
        
        //Attach purchase now button
        var oInput = DH.createInput('button','nextStep','Purchase now','26');
        oInput.className = 'button';
        var NextStep_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            Checkout.moveFrom();
        };
        DH.addEvent(oInput,'click',NextStep_onClick);
        f.appendChild(oInput);
        oParent.appendChild(f);  
       
    },
    
    attachStep4: function(oParent)
    {
        
        //create form
        var oForm = this.createForm();  
        
        //Attach website name
        //oForm.appendChild(DH.createHiddenInput('WebSiteName','MEA Secondary'));
        oForm.appendChild(DH.createHiddenInput('WebSiteName','MEA Secondary')); // interim form before secure pay goes live
        
        //Attach eClub
        var oInput = DH.createHiddenInput('eClub','eClub');
        oInput.setAttribute('value','');
        oForm.appendChild(oInput);
        
        //Attach ISBNBundleCode
        var oInput = DH.createHiddenInput('ISBNBundleCode','ISBNBundleCode');
        oInput.setAttribute('value','');
        oForm.appendChild(oInput);
        
        //Attach OrgName
        var oInput = DH.createHiddenInput('OrgName','OrgName');
        oInput.setAttribute('value','');
        oForm.appendChild(oInput);
        
        //Attach DiscountCode
        var oInput = DH.createHiddenInput('DiscountCode','DiscountCode');
        oInput.setAttribute('value','');
        oForm.appendChild(oInput);
        
        //Get step 1 vars
        var oCookie = new CheckoutCookie('checkout_step1');
        var payType = oCookie.getVarValue('PayType');
        
        oCookie.getHiddenInputs_personalDetails(oForm);
        oCookie.getHiddenInputs_information(oForm);
        
        if(payType != '2' && payType != '3')
        {
            //Get step 2 vars
            var oCookie = new CheckoutCookie('checkout_step2');
            oCookie.getHiddenInputs_invoice(oForm);
        }
        
        //Attach items
        Cart.attachCheckoutHiddenInputs(oForm);
        
        //Attach Total
        oForm.appendChild(DH.createHiddenInput('Total',Cart.getTotal().toFixed(2)));
        
        //Attach handling fee
        if(this.isPersonalOrder())
        {
            oForm.appendChild(DH.createHiddenInput('Handling',Cart.handlingFee.toFixed(2)));
        } else {
            var oInput = DH.createHiddenInput('Handling','0');
            
        }
        //Attach freight
        var oInput = DH.createHiddenInput('Freight','0');
        
        oForm.appendChild(DH.createHiddenInput('ST','F'));
        
        //Attach form to parent
        oParent.appendChild(oForm);

        setTimeout('document.getElementById(\'secondary_checkout_form\').submit()',1000);
        
    },
    
    isPersonalOrder: function()
    {
        var oCookie = new CheckoutCookie('checkout_step1'); 
        var payType = oCookie.getVarValue('PayType');
        if(payType && payType == '2')//if payment is credit card
        {
            return true;
        } else {
            return false;
        }
    },
    
    attachStep3DeliveryDetails: function(oParent)
    {
    
      if(this.isPersonalOrder()) {
      var p1 = document.createElement('p');
      var text = "A handling fee of $10.00 applies for private customers.";
      p1.appendChild(document.createTextNode(text));
        oParent.appendChild(p1);
     }
    
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Your delivery details:'));
        h3.style.marginTop = '0';
        oParent.appendChild(h3);
    
        var p = document.createElement('p');
        p.setAttribute('id','deliveryDetails');
        
        var oCookie = new CheckoutCookie('checkout_step1');
        
        //Atach first and last name
        var text = oCookie.getVarValue('Firstname') + ' ' + oCookie.getVarValue('Lastname'); 
        p.appendChild(document.createTextNode(text));
        p.appendChild(document.createElement('br'));
        
        //Attach organisation
        var text = oCookie.getVarValue('Organisation'); 
        p.appendChild(document.createTextNode(text));
        p.appendChild(document.createElement('br'));
        
        //Attach address and city
        var text = oCookie.getVarValue('PostalAddress'); 
        p.appendChild(document.createTextNode(text));
        p.appendChild(document.createElement('br'));
        
        //Attach state and post code
        var text = oCookie.getVarValue('PostalCity') + '   ' + oCookie.getVarValue('PostalState') + '   ' + oCookie.getVarValue('PostalCode'); 
        p.appendChild(document.createTextNode(text));
        p.appendChild(document.createElement('br'));
        
        //Attach to parent
        oParent.appendChild(p);
    },
    
    attachStep1Form: function(oParent)
    {
        var oCookie = new CheckoutCookie('checkout_step1');
        
        var oForm = this.createForm();
        
        // Payment method
        var div = document.createElement('div');        
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Payment method'));
        div.appendChild(h3);

        var f = document.createElement('fieldset');
        f.className = 'payType';
        //f.appendChild(DH.createLabel('Payment','PayType'));
        //var sValue = (oCookie.getVarValue('PayType')) ? oCookie.getVarValue('PayType') : '2';
        //Attach radios
        var ul = document.createElement('ul');
        var names = ['School/University invoice','School/University credit card','Personal credit card'];
        var values = ['4','3','2'];
        
        /*var checkPurchases_onClick = function(oEvent)
        {
        //alert(this.value);
            if(this.value && (this.value == '2' || this.value == '3') && !Cart.hasOnlyItemsInStock()) {
              alert('Items not available cannot be purchased by credit card. Select payment by invoice or else the unavailable item(s) will not be added to your order');
             }
        }*/
            
        for(var i = 0; i < names.length; i++)
        {
            try{
                var checked = "";
                //if(sValue == values[i])checked = "checked='checked'";
                var oInput = document.createElement("<input type='radio' name='PayType' value='" + values[i] + "' " + checked + " tabindex='7' />");
                //DH.addEvent(oInput,'click',checkPurchases_onClick);
            } catch(oError) {
                var oInput = DH.createInput('radio','PayType',values[i],'7');
                //DH.addEvent(oInput,'click',checkPurchases_onClick);                
                //if(sValue == values[i])oInput.checked = true;
            }
            var li = document.createElement('li');
            li.appendChild(oInput);
            li.appendChild(document.createTextNode(names[i]));
            //Attach handling fee message to last item
            if(i == (names.length - 1))
            {
                var p = document.createElement('p');
                p.appendChild(document.createTextNode('(A handling fee of $' + Cart.handlingFee.toFixed(2) + ' applies for private customers.)'));
                li.appendChild(p);
            }
            ul.appendChild(li);
        }
        f.appendChild(ul);
        div.appendChild(f);
		oForm.appendChild(div);
        
        //Personal details
        var div = document.createElement('div');
        div.setAttribute('id','personalDetails');
        
        //Attach heading
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Personal details'));
        div.appendChild(h3);
        
        //Attach First name
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('First name*','Firstname'));
        var sValue = (oCookie.getVarValue('Firstname')) ? oCookie.getVarValue('Firstname') : '';
        var oInput = DH.createInput('text','Firstname',sValue,'1');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach Last name
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Last name*','Lastname'));
        var sValue = (oCookie.getVarValue('Lastname')) ? oCookie.getVarValue('Lastname') : '';
        var oInput = DH.createInput('text','Lastname',sValue,'2');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach Position
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Position*','Position'));
        var sValue = (oCookie.getVarValue('Position')) ? oCookie.getVarValue('Position') : '';
        var oInput = DH.createInput('text','Position',sValue,'3');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach Organisation
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('School name (if applicable)','Organisation'));
        var sValue = (oCookie.getVarValue('Organisation')) ? oCookie.getVarValue('Organisation') : '';
        var oInput = DH.createInput('text','Organisation',sValue,'4');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach ContactType
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Preferred contact','ContactType'));
        var sValue = (oCookie.getVarValue('ContactType')) ? oCookie.getVarValue('ContactType') : 'Email';
        var select = document.createElement('select');
        select.setAttribute('name','ContactType');
        //select.setAttribute('tabindex','5');
        var values = ['Email','Phone','Postal'];
        for(var i = 0; i < values.length; i++)
        {
            var option = document.createElement('option');
            option.appendChild(document.createTextNode(values[i]));
            option.setAttribute('value',values[i]);
            select.appendChild(option);
        }
        switch(oCookie.getVarValue('ContactType'))
        {
            case 'Email': var sValue = 0; break;
            case 'Phone': var sValue = 1; break;
            case 'Postal': var sValue = 2; break;
            default: var sValue = '';
        }
        select.selectedIndex = sValue;
        //select.value = sValue;
        f.appendChild(select);
        div.appendChild(f);
        
        //Attach Comments
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Comments','Comments'));
        var sValue = (oCookie.getVarValue('Comments')) ? oCookie.getVarValue('Comments') : '';
        var oTextArea = document.createElement('textarea');
        oTextArea.setAttribute('name','Comments');
        oTextArea.setAttribute('tabindex','6');
        oTextArea.setAttribute('cols','25');
        oTextArea.appendChild(document.createTextNode(sValue));
        f.appendChild(oTextArea);
        div.appendChild(f);
        
        //Attach PayType
        
        //Attach SalesRepCode
        var f = document.createElement('fieldset');
        //f.appendChild(DH.createLabel('Sales rep code','SalesRepCode'));
        var sValue = (oCookie.getVarValue('SalesRepCode')) ? oCookie.getVarValue('SalesRepCode') : 'website';
        var oInput = DH.createInput('hidden','SalesRepCode',sValue,'8');
        oInput.setAttribute('tabindex','8');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach personal details to form       
        oForm.appendChild(div);
        
		//Information
        var div = document.createElement('div');
        div.setAttribute('id','information');
        
        //Attach heading
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('Information'));
        div.appendChild(h3);

		// attach delivery type
		//alert(oCookie.getVarValue('AddressType'))
		
        var f = document.createElement('fieldset');
        f.className = 'AddressType';
        var ul = document.createElement('ul');   
       try{
        var oInput = document.createElement("<input type='radio' name='AddressType' value='1' />");
        var li = document.createElement('li');
		li.appendChild(oInput);
        li.appendChild(document.createTextNode('Private address'));
        ul.appendChild(li);
        var oInput = document.createElement("<input type='radio' name='AddressType' value='2' />");
        var li = document.createElement('li');
		li.appendChild(oInput);
        li.appendChild(document.createTextNode('School / Institution'));
        ul.appendChild(li);
               
        } catch(oError) {
        var oInput = DH.createInput('radio','AddressType','1','');
        var li = document.createElement('li');
		li.appendChild(oInput);
        li.appendChild(document.createTextNode('Private address'));
        ul.appendChild(li);
        var oInput = DH.createInput('radio','AddressType','2','');
        var li = document.createElement('li');
		li.appendChild(oInput);
        li.appendChild(document.createTextNode('School / Institution'));
        ul.appendChild(li);
        }
        f.appendChild(ul);
        div.appendChild(f);
           
        
        var p = document.createElement('p');
        p.appendChild(document.createTextNode('Note: we do not deliver to post office boxes.'));
        div.appendChild(p);
        
        //Attach postal address
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Street address*','PostalAddress'));
        var sValue = (oCookie.getVarValue('PostalAddress')) ? oCookie.getVarValue('PostalAddress') : '';
        var oInput = DH.createInput('text','PostalAddress',sValue,'9');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach postal city
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Suburb*','PostalCity'));
        var sValue = (oCookie.getVarValue('PostalCity')) ? oCookie.getVarValue('PostalCity') : '';
        var oInput = DH.createInput('text','PostalCity',sValue,'10');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach Postal state
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('State*','PostalState'));
        var select = document.createElement('select');
        select.setAttribute('name','PostalState');
        select.setAttribute('tabindex','11');
        select.appendChild(DH.createOption('Select a state','Select a state'));
        select.appendChild(DH.createOption('ACT','Australian Capital Territory'));
        select.appendChild(DH.createOption('NSW','New South Wales'));
        select.appendChild(DH.createOption('NT','Northern Territory'));
        select.appendChild(DH.createOption('QLD','Queensland'));
        select.appendChild(DH.createOption('SA','South Australia'));
        select.appendChild(DH.createOption('TAS','Tasmania'));
        select.appendChild(DH.createOption('VIC','Victoria'));
        select.appendChild(DH.createOption('WA','Western Australia'));
        switch(oCookie.getVarValue('PostalState'))
        {
            case 'Australian Capital Territory': var sValue = 1; break;
            case 'New South Wales': var sValue = 2; break;
            case 'Northern Territory': var sValue = 3; break;
            case 'Queensland': var sValue = 4; break;
            case 'South Australia': var sValue = 5; break;
            case 'Tasmania': var sValue = 6; break;
            case 'Victoria': var sValue = 7; break;
            case 'Western Australia': var sValue = 8; break;
            default: var sValue = 0;
        }
        select.selectedIndex = sValue;
        f.appendChild(select);
        div.appendChild(f);
        
        //Attach postal code
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Postcode*','PostalCode'));
        var sValue = (oCookie.getVarValue('PostalCode')) ? oCookie.getVarValue('PostalCode') : '';
        var oInput = DH.createInput('text','PostalCode',sValue,'12');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach overseas order
        var f = document.createElement('fieldset');
        f.className = 'overseasOrder';
        f.appendChild(DH.createLabel('Is your order to be delivered outside Australia?','overseasOrder'));
        var sValue = (oCookie.getVarValue('overseasOrder')) ? oCookie.getVarValue('overseasOrder') : '0';
        

        var overseasOrder_onClick = function(oEvent)
        {
            if(this.value && this.value == '1')
            {
                tmpOS = true;
                var isInternational = confirm('If your order is for delivery outside Australia then please ensure you have provided an email address and click OK, your order will be sent to our Sales Department and we will contact you shortly. If you do not wish to proceed with this order then click Cancel.');
                if(!isInternational)
                {
                    var oInputs = document.getElementById('secondary_checkout_form').getElementsByTagName('input');
                    var radioButtons = new Array();
                    for(var i = 0; i < oInputs.length; i++)
                    {
                        if(oInputs[i].type
                           && oInputs[i].type.toLowerCase() == 'radio'
                           && oInputs[i].name
                           && oInputs[i].name == 'overseasOrder')
                        {
                            radioButtons.push(oInputs[i]);
                        }  
                    }
                    if(radioButtons.length == 2)
                    {
                        radioButtons[1].checked = true;
                    }
                }
            }
        };
        
        //Attach radios
        var ul = document.createElement('ul');
        try{
                //attach yes
                var checked = "";
                if(sValue == '1')checked = "checked='checked'";
                tmpOS = false;
                var oInput = document.createElement("<input type='radio' name='overseasOrder' value='1' " + checked + " tabindex='13' />");
                DH.addEvent(oInput,'click',overseasOrder_onClick);
                var li = document.createElement('li');
                li.appendChild(oInput);
                li.appendChild(document.createTextNode('Yes'));
                ul.appendChild(li);
                //attach no
                var checked = "";
                if(sValue == '0')checked = "checked='checked'";
                var oInput = document.createElement("<input type='radio' name='overseasOrder' value='0' " + checked + " tabindex='13' />");
                DH.addEvent(oInput,'click',overseasOrder_onClick);
                var li = document.createElement('li');
                li.appendChild(oInput);
                li.appendChild(document.createTextNode('No'));
                ul.appendChild(li);
                
        } catch(oError) {
            //Attach yes
            var oInput = DH.createInput('radio','overseasOrder','1','13');
            DH.addEvent(oInput,'click',overseasOrder_onClick);
            if(sValue == '1')oInput.checked = true;
            var li = document.createElement('li');
            li.appendChild(oInput);
            li.appendChild(document.createTextNode('Yes'));
            ul.appendChild(li);
            //Attach no
            var oInput = DH.createInput('radio','overseasOrder','0','13');
            DH.addEvent(oInput,'click',overseasOrder_onClick);
            if(sValue == '0')oInput.checked = true;
            var li = document.createElement('li');
            li.appendChild(oInput);
            li.appendChild(document.createTextNode('No'));
            ul.appendChild(li);
        }
        f.appendChild(ul);
        div.appendChild(f);
        
        //Attach phone number
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Phone*','PhoneNumber'));
        var sValue = (oCookie.getVarValue('PhoneNumber')) ? oCookie.getVarValue('PhoneNumber') : '';
        var oInput = DH.createInput('text','PhoneNumber',sValue,'14');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);   
        
        //Attach fax
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Fax','FaxNumber'));
        var sValue = (oCookie.getVarValue('FaxNumber')) ? oCookie.getVarValue('FaxNumber') : '';
        var oInput = DH.createInput('text','FaxNumber',sValue,'15');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f); 
        
        //Attach email address
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Email*','EmailAddress'));
        var sValue = (oCookie.getVarValue('EmailAddress')) ? oCookie.getVarValue('EmailAddress') : '';
        var oInput = DH.createInput('text','EmailAddress',sValue,'16');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f); 
        
        //Attach remember checkbox
        var f = document.createElement('fieldset');
        f.className = 'rememberDetails';
        var sValue = (oCookie.getVarValue('EmailAddress')) ? oCookie.getVarValue('EmailAddress') : '';
        var oInput = DH.createInput('checkbox','Remember','Yes','17');
        var Remember_onClick = function()
        {
            var oCookie = new CheckoutCookie('checkout_step1');
            oCookie.save();
        };
        DH.addEvent(oInput,'click',Remember_onClick);
        if(sValue)
        {
            oInput.checked = true;
        }
        f.appendChild(oInput);
        f.appendChild(DH.createLabel('Remember my details','Remember'));
        div.appendChild(f);
        
        //Attach receive info checkbox
        var f = document.createElement('fieldset');
        f.className = 'receiveInfo';
        var sValue = (oCookie.getVarValue('ReceiveInfo')) ? oCookie.getVarValue('ReceiveInfo') : '';
        var oInput = DH.createInput('checkbox','ReceiveInfo','Yes','18');
        if(sValue)
        {
            oInput.checked = true;
        }
        f.appendChild(oInput);
        f.appendChild(DH.createLabel('Please send me further info on Macmillan products','ReceiveInfo'));
        div.appendChild(f);
        
        //Attach required fields message
        var p = document.createElement('p');
        p.className = 'requiredInfo';
        p.appendChild(document.createTextNode('* = required fields.'));
        div.appendChild(p); 
        
        //Attach buttons
        var f = document.createElement('fieldset');
        f.className = 'buttons';
        var oInput = DH.createInput('button','continueShopping','Continue shopping','19');
        oInput.className = 'continueShopping';
        var ContinueShoppingBtn_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            history.go(-1);
        };
        DH.addEvent(oInput,'click',ContinueShoppingBtn_onClick);
        f.appendChild(oInput);
        var oInput = DH.createInput('button','nextStep','Next step','20');
        oInput.className = 'nextStep';
        var NextStep_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            Checkout.moveFrom();
        };
        DH.addEvent(oInput,'click',NextStep_onClick);
        f.appendChild(oInput);
        div.appendChild(f);   
        
        //Attach information form       
        oForm.appendChild(div);
        
        oParent.appendChild(oForm);    
    },
    
    attachStep2Form: function(oParent)
    {
        var oCookie = new CheckoutCookie('checkout_step2');
        
        var oForm = this.createForm();
        
        //Personal details
        var div = document.createElement('div');
        div.setAttribute('id','invoiceInfo');
        /*
        //Attach heading
        var h3 = document.createElement('h3');
        h3.appendChild(document.createTextNode('School/University invoice details'));
        div.appendChild(h3);
        */
        //Attach First name
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Customer order number*','Inv_Order_Number'));
        var sValue = (oCookie.getVarValue('Inv_Order_Number')) ? oCookie.getVarValue('Inv_Order_Number') : '';
        var oInput = DH.createInput('text','Inv_Order_Number',sValue,'21');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach First name
        var f = document.createElement('fieldset');
        f.appendChild(DH.createLabel('Macmillan Account code (if known)','Inv_Order_Number'));
        var sValue = (oCookie.getVarValue('Inv_Order_AccountCode')) ? oCookie.getVarValue('Inv_Order_AccountCode') : '';
        var oInput = DH.createInput('text','Inv_Order_AccountCode',sValue,'22');
        oInput.className = 'text';
        f.appendChild(oInput);
        div.appendChild(f);
        
        //Attach required fields message
        var p = document.createElement('p');
        p.className = 'requiredInfo';
        p.appendChild(document.createTextNode('* = required fields.'));
        div.appendChild(p);
        
        //Attach p.text
        var p = document.createElement('p');
        p.className = 'text';
        //p.appendChild(document.createTextNode('All Customer Order Numbers will be checked and verified by the Customer Service Department.'));
       // p.appendChild(document.createElement('br'));
       // p.appendChild(document.createTextNode('Proceeding with the Next Step button below will issue a request for an invoice.<br><br><a href="libraries/Terms+and+Conditions">Click here for terms and conditions</a>.'));
        div.appendChild(p);
        p.innerHTML = '<br>Proceeding with the Next Step button below will issue a request for an invoice.<br><br><a href="libraries/Terms+and+Conditions">Click here for terms and conditions</a>.';
        
        //Attach buttons
        var f = document.createElement('fieldset');
        var oInput = DH.createInput('button','previousStep','Previous','23');
        oInput.className = 'button';
        var PreviousStepBtn_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            Checkout.moveBack();
        };
        DH.addEvent(oInput,'click',PreviousStepBtn_onClick);
        f.appendChild(oInput);
        var oInput = DH.createInput('button','nextStep','Next step','24');
        oInput.className = 'button';
        var NextStep_onClick = function(oEvent)
        {
            var target = DH.stopEvent(oEvent);
            Checkout.moveFrom();
        };
        DH.addEvent(oInput,'click',NextStep_onClick);
        f.appendChild(oInput);
        div.appendChild(f);  
         
        //Attach information form       
        oForm.appendChild(div);
        oParent.appendChild(oForm);   
    },
    
    createForm: function()
    {
        var oForm = document.createElement('form');
        oForm.setAttribute('enctype','multipart/form-data');
        oForm.setAttribute('method','post');
        oForm.setAttribute('action','http://macmillan.itechne.com/');
        oForm.setAttribute('id','secondary_checkout_form');
        return oForm;
    },
    
    validate_step1: function()
    {
        //check if there are items in cart
        if(!Cart || !Cart.hasItems())
        {
            alert('Please add items to cart before proceeding.');
            return false;
        }

      
        var vars = new Array();
        var oCookie = new CheckoutCookie('checkout_step1');

    	// check not PO box
    	var regExpPOBox = /(\b)(po|p o|pb|p.o|box|bag|locked|private|locked bag|ms|rmd|private bag)(\b)/;
    	var inputValue = oCookie.getFormTextInputValue('PostalAddress');
    	if (inputValue && regExpPOBox.test(inputValue.toLowerCase())) {
 			alert('Sorry, we do not deliver to post office/private boxes.');
        	return false;
		}

        
        //Validate fields
        var message = oCookie.validate_step1(vars);
        if(vars.length > 0)
        {
            alert(message + vars.join('\n'));
            return false;
        }
        
        //validate cart items against paytype
        var payType = oCookie.getFormRadioInputValue('PayType');
        if (payType==undefined || payType=='undefined') 
        {
            alert('Please select a payment type.');
            return false;
        
        }
        if(payType == '2' && Cart.hasInspectedItems())
        {
            alert('Inspection copies may only be requested by schools.');
            return false;
        }
        if(payType == '3' && Cart.hasInspectedItems())
        {
            alert('Inspect on Approval items cannot be ordered using credit card for payment. Please select payment by invoice or remove these items.');
            return false;
        }

        /*if((payType == '2' || payType == '3') && Cart.hasOnlyItemsOutOfStock())
        {
            alert('Items not available cannot be purchased by credit card. Please select payment by invoice.');
            return false;
        }
        if((payType == '2' || payType == '3') && !Cart.hasOnlyItemsInStock())
        {
            Cart.removeItemsOutOfStock();
        }*/
        
        return true;
    },
    
    validate_step2: function()
    {
        var vars = new Array();
        var oCookie = new CheckoutCookie('checkout_step2');
        //Validate fields
        var message = oCookie.validate_step2(vars);
        if(vars.length > 0)
        {
            alert(message + vars.join('\n'));
            return false;
        }
        
        return true;
    },
    
    moveFrom: function()
    {
        switch(this.step)
        {
            case 1:
                this.moveFrom_step1();
                break;
            case 2:
                this.moveFrom_step2();
                break;
            case 3:
                this.moveFrom_step3();
                break;
            default:
        }
    },
    
    moveBack: function()
    {
        switch(this.step)
        {
            case 3://summary
                this.moveBack_step3();    
                break;
            case 2://invoice
                this.step = 1;
                break;   
            default:
        }
        this.attach();
    },
    
    moveBack_step3: function()
    {
        //Get paytype
        var oCookie = new CheckoutCookie('checkout_step1'); 
        var payType = oCookie.getVarValue('PayType');  
        if(payType == '2' || payType == '3')//credit card
        {
            this.step = 1;
        } else {//invoice
            this.step = 2;
        }
    },
    
    moveFrom_step1: function()
    {
        var step1Valid = this.validate_step1();
        if(step1Valid)
        {
            //Save cookie
            var oCookie = new CheckoutCookie('checkout_step1');
            oCookie.save();
            
            var payType = oCookie.getFormRadioInputValue('PayType');
            if(payType == '2' || payType == '3')//credit card
            {
                this.step = 3;
            } else {
                this.step = 2;
            }
            this.attach();
        } 
    },
    
    moveFrom_step2: function()
    {
        var step2Valid = this.validate_step2();
        if(step2Valid)
        {
            //Save cookie
            var oCookie = new CheckoutCookie('checkout_step2');
            oCookie.save();
            
            this.step = 3;
            
            this.attach();
        } 
    },
    
    moveFrom_step3: function()
    {
        var oCookie = new CheckoutCookie('checkout_step1'); 
        var payType = oCookie.getVarValue('PayType');
        //if(payType == '2' && Cart.hasOnlyItemsInStock())
        if((payType == '2' || payType == '3') && oCookie.getVarValue('overseasOrder')!='1')
        {
            var confirmPurchase = confirm('Please be advised when you confirm your order your credit card will be debited and your order will not be refundable unless we are notified within 14 days that an item is faulty or incorrectly supplied.');
            if(confirmPurchase)
            {
                this.step = 4;
                this.attach();
            }
        }  else {
            this.step = 4;
            this.attach();
        }     
    },
    
    moveTo_step2: function()
    {
    
    },

    init: function()
    {
    
        //Set checkout step
        this.step = 1;
    }

}


/*------------------------------------------------------------------------------------------------------------------------------------------------------------------------

    cookie manager
    
*/

function CheckoutCookie(cookieName)
{
    if(!cookieName || typeof cookieName != 'string' || cookieName.length < 1)
    {
        throw new Error('CheckoutCookieManager constructor expects at least one argument of \'string\' type');
    }
    
    this.name = cookieName;
    this.vars = new Array();
    this.load();
}

CheckoutCookie.prototype.load = function()
{
    var oCookie = DH.getCookie(this.name);
    
    var vars = new Array();
    
    if(oCookie)
    {
        var tempArray = oCookie.split('||');
        for(var i = 0; i < tempArray.length; i++)
        {
            var cookieVar = tempArray[i].split('=');
            if(cookieVar.length != 2)
            {
                throw new Error('CheckoutCookie.load() - cookie is corrupt');
            }
            var item = {name: cookieVar[0],value: decodeURIComponent(cookieVar[1])};
            this.vars.push(item);
            vars.push(item.name + '=' + item.value);
        }
        if(Secondary._LOG_ENABLED)LOG.printULwithH1('CheckoutCookie.load() - cookie loaded',vars);
    }
};

CheckoutCookie.prototype.getVarValue = function(name)
{
    for(var i = 0; i < this.vars.length; i++)
    {
        if(this.vars[i].name == name 
           && typeof this.vars[i].value == 'string' 
           && this.vars[i].value.length > 0)
        {
            return this.vars[i].value;
        }
    }
    return null;
};

CheckoutCookie.prototype.save = function()
{
    var vars = new Array();
    switch(this.name)
    {
        case 'checkout_step1':
            this.get_personalDetails(vars);
            this.get_information(vars);
            break;
        case 'checkout_step2':
            this.get_invoice(vars);
            break;
        default:
    }
    
    if(vars.length > 0)
    {
        var cookieExpires = new Date();
        cookieExpires.setTime(cookieExpires.getTime() + (1 * 60 * 60 * 1000 ));
        DH.setCookie(this.name,vars.join('||'),cookieExpires,'/');
        if(Secondary._LOG_ENABLED)LOG.printULwithH1('CheckoutCookie.save() - cookie saved',vars);
    }
};

CheckoutCookie.prototype.getFormTextInputValue = function(name)
{
    var oForm = document.getElementById('secondary_checkout_form');
    
    if(!oForm) return null;
    
    var oInputs = oForm.getElementsByTagName('input');
    
    if(oInputs.length < 1)return null;
    
    for(var i = 0; i < oInputs.length; i++)
    {
        if(oInputs[i].name 
           && oInputs[i].name == name 
           && typeof oInputs[i].value == 'string' 
           && oInputs[i].value.length > 0)
        {
            return encodeURIComponent(oInputs[i].value.trim());
        }
    }
    return null;
};

CheckoutCookie.prototype.getFormTextAreaValue = function(name)
{
    var oForm = document.getElementById('secondary_checkout_form');
    
    if(!oForm) return null;
    
    var textAreas = oForm.getElementsByTagName('textarea');
    
    if(textAreas.length < 1)return null;
    
    for(var i = 0; i < textAreas.length; i++)
    {
        if(textAreas[i].name 
           && textAreas[i].name == name 
           && textAreas[i].value
           && textAreas[i].value.length > 0)
        {
            return encodeURIComponent(textAreas[i].value.trim());
        }
    }
    return null;
};

CheckoutCookie.prototype.getFormCheckboxInputValue = function(name)
{
    var oForm = document.getElementById('secondary_checkout_form');
    
    if(!oForm) return null;
    
    var oInputs = oForm.getElementsByTagName('input');
    
    if(oInputs.length < 1)return null;
    
    for(var i = 0; i < oInputs.length; i++)
    {
        if(oInputs[i].name 
           && oInputs[i].name == name 
           && oInputs[i].checked
           && typeof oInputs[i].value == 'string' 
           && oInputs[i].value.length > 0)
        {
            return encodeURIComponent(oInputs[i].value.trim());
        }
    }
    return null;
};

CheckoutCookie.prototype.getFormSelectValue = function(name)
{
    var oForm = document.getElementById('secondary_checkout_form');
    
    if(!oForm) return null;
    
    var selects = oForm.getElementsByTagName('select');
    for(var i = 0; i < selects.length; i++)
    {
        if(selects[i].name && selects[i].name == name)
        {
            var select = selects[i];
        }
    }
    
    //If no select found
    if(!select)return null;
    
    var options = select.getElementsByTagName('option');
    //If no option tags found
    if(options.length < 1)return null;
    return options[select.selectedIndex].value;
};

CheckoutCookie.prototype.getFormRadioInputValue = function(name)
{
    var oForm = document.getElementById('secondary_checkout_form');
    
    if(!oForm) return null;
    
    var inputs = oForm.getElementsByTagName('input');
    var radios = new Array();
    for(var i = 0; i < inputs.length; i++)
    {
        if(inputs[i].type && inputs[i].type.toLowerCase() == 'radio'
           && inputs[i].name && inputs[i].name == name)
        {
            radios.push(inputs[i]);
        }
    }
    
    //If no select found
    if(radios.length < 1)return null;
    
    for(var i = 0; i < radios.length; i++)
    {
        if(radios[i].checked)return radios[i].value;
    }
    
    return null;
};

CheckoutCookie.prototype.get_personalDetails = function(vars)
{

    //Get firstname
    var inputValue = this.getFormTextInputValue('Firstname');
    if(inputValue)vars.push('Firstname=' + inputValue);
    
    //Get lastname
    var inputValue = this.getFormTextInputValue('Lastname');
    if(inputValue)vars.push('Lastname=' + inputValue);
    
    //Get position
    var inputValue = this.getFormTextInputValue('Position');
    if(inputValue)vars.push('Position=' + inputValue);
    
    //Get Organisation
    if (this.getFormRadioInputValue('AddressType') == '1') {  // private address
      var inputValue = "";
    }
    else {
      var inputValue = this.getFormTextInputValue('Organisation');
      if(inputValue)vars.push('Organisation=' + inputValue);
	} 
  
   
    //Get ContactType
    var inputValue = this.getFormSelectValue('ContactType');
    if(inputValue)vars.push('ContactType=' + inputValue);
    
    //Get comments
    var inputValue = this.getFormTextAreaValue('Comments');
    if(inputValue)vars.push('Comments=' + inputValue);
    
    //Get PayType
    var inputValue = this.getFormRadioInputValue('PayType');
    if(inputValue)vars.push('PayType=' + inputValue);
    
    //Get SalesRepCode
    var inputValue = this.getFormTextInputValue('SalesRepCode');
    if(inputValue)vars.push('SalesRepCode=' + inputValue);
};

CheckoutCookie.prototype.getHiddenInputs_personalDetails = function(oForm)
{
    //Get firstname
    oForm.appendChild(DH.createHiddenInput('FirstName',this.getVarValue('Firstname')));
    
    //Get lastname
    oForm.appendChild(DH.createHiddenInput('LastName',this.getVarValue('Lastname')));
    
    //Get position
    oForm.appendChild(DH.createHiddenInput('Position',this.getVarValue('Position')));
    
    //Get Organisation
    /*** bug?
    var inputValue = (this.getVarValue('Organisation').toLowerCase().indexOf('school') == -1)
                      ? ('School ' + this.getVarValue('Organisation')) : this.getVarValue('Organisation') ;
    oForm.appendChild(DH.createHiddenInput('SchoolName',inputValue));
    */
     oForm.appendChild(DH.createHiddenInput('SchoolName',this.getVarValue('Organisation')));    
        
    //Get ContactType
    switch(this.getVarValue('ContactType'))
    {
        case 'Email': var sValue = '1'; break;
        case 'Phone': var sValue = '2'; break;
        case 'Postal': var sValue = '3'; break;
        default: var sValue = '';
    }
    oForm.appendChild(DH.createHiddenInput('PreferredContactType',sValue));
    
    //Attach comments
    if(this.getVarValue('Comments'))
    {
        var textArea = document.createElement('textarea');
        textArea.style.display = 'none';
        textArea.setAttribute('name','Comments');
        textArea.appendChild(document.createTextNode(this.getVarValue('Comments')));
        oForm.appendChild(textArea);
    }
        
    //Get PayType
    oForm.appendChild(DH.createHiddenInput('PaymentType',this.getVarValue('PayType')));
    
    //Get SalesRepCode
    oForm.appendChild(DH.createHiddenInput('SalesRepCode',this.getVarValue('SalesRepCode')));
};

CheckoutCookie.prototype.getHiddenInputs_information = function(oForm)
{
    //Get PostalAddress
    oForm.appendChild(DH.createHiddenInput('PostalAddress',this.getVarValue('PostalAddress')));
    
    //Get PostalCity
    oForm.appendChild(DH.createHiddenInput('PostalCity',this.getVarValue('PostalCity')));
    
    //Get PostalState
    var isOverseasOrder = (this.getVarValue('overseasOrder') == '1') ? true : null;
    if(isOverseasOrder)
    {
        oForm.appendChild(DH.createHiddenInput('PostalState','International'));
    } else {
        oForm.appendChild(DH.createHiddenInput('PostalState',this.getVarValue('PostalState')));
    }
    
    //Get PostalCode
    oForm.appendChild(DH.createHiddenInput('PostalCode',this.getVarValue('PostalCode')));
    
    //Get PhoneNumber
    oForm.appendChild(DH.createHiddenInput('PhoneNumber',this.getVarValue('PhoneNumber')));
    
    //Get FaxNumber
    oForm.appendChild(DH.createHiddenInput('FaxNumber',this.getVarValue('FaxNumber')));
    
    //Get EmailAddress
    oForm.appendChild(DH.createHiddenInput('EmailAddress',this.getVarValue('EmailAddress')));
    
    //Get ReceiveInfo
    var moreInfo = (this.getVarValue('ReceiveInfo') == 'Yes') ? 'True' : 'False';
    oForm.appendChild(DH.createHiddenInput('FurtherInfo',moreInfo));
};

CheckoutCookie.prototype.getHiddenInputs_invoice = function(oForm)
{
    //Get customer order number
    oForm.appendChild(DH.createHiddenInput('Inv_Order_Number',this.getVarValue('Inv_Order_Number')));
    
    //macmillan account code
    oForm.appendChild(DH.createHiddenInput('Inv_Order_AccountCode',this.getVarValue('Inv_Order_AccountCode')));
};

CheckoutCookie.prototype.get_information = function(vars)
{
    //Get PostalAddress
    var inputValue = this.getFormTextInputValue('PostalAddress');
    if(inputValue)vars.push('PostalAddress=' + inputValue);
    
    //Get PostalCity
    var inputValue = this.getFormTextInputValue('PostalCity');
    if(inputValue)vars.push('PostalCity=' + inputValue);
    
    //Get PostalState
    var inputValue = this.getFormSelectValue('PostalState');
    if(inputValue)vars.push('PostalState=' + inputValue);
    
    //Get PostalCode
    var inputValue = this.getFormTextInputValue('PostalCode');
    if(inputValue)vars.push('PostalCode=' + inputValue);
    
    //Get overseasOrder
    var inputValue = this.getFormRadioInputValue('overseasOrder');
    if(inputValue)vars.push('overseasOrder=' + inputValue);
    
    //Get PhoneNumber
    var inputValue = this.getFormTextInputValue('PhoneNumber');
    if(inputValue)vars.push('PhoneNumber=' + inputValue);
    
    //Get FaxNumber
    var inputValue = this.getFormTextInputValue('FaxNumber');
    if(inputValue)vars.push('FaxNumber=' + inputValue);
    
    //Get EmailAddress
    var inputValue = this.getFormTextInputValue('EmailAddress');
    if(inputValue)vars.push('EmailAddress=' + inputValue);
    
    //Get Remember
    var inputValue = this.getFormCheckboxInputValue('Remember');
    if(inputValue)vars.push('Remember=' + inputValue);
    
    //Get ReceiveInfo
    var inputValue = this.getFormCheckboxInputValue('ReceiveInfo');
    if(inputValue)vars.push('ReceiveInfo=' + inputValue);
};

CheckoutCookie.prototype.get_invoice = function(vars)
{
    //Get customer order number
    var inputValue = this.getFormTextInputValue('Inv_Order_Number');
    if(inputValue)vars.push('Inv_Order_Number=' + inputValue);
    
    //macmillan account code
    var inputValue = this.getFormTextInputValue('Inv_Order_AccountCode');
    if(inputValue)vars.push('Inv_Order_AccountCode=' + inputValue);
};

CheckoutCookie.prototype.validate_step1 = function(vars)
{
    //Get firstname
    var inputValue = this.getFormTextInputValue('Firstname');
    if(!inputValue)vars.push('-Firstname');
    
    //Get lastname
    var inputValue = this.getFormTextInputValue('Lastname');
    if(!inputValue)vars.push('-Lastname');
    
    //Get position
    var inputValue = this.getFormTextInputValue('Position');
    if(!inputValue)vars.push('-Position');
    
    // Address Type
    var inputValue = this.getFormRadioInputValue('AddressType');
    if(!inputValue)vars.push('-Address type (private or school/institution)');  
    
    //Get PostalAddress
    var inputValue = this.getFormTextInputValue('PostalAddress');
    if(!inputValue)vars.push('-PostalAddress');
    
    //Get PostalCity
    var inputValue = this.getFormTextInputValue('PostalCity');
    if(!inputValue)vars.push('-Suburb');
    
    //Get PostalState
    if (!tmpOS) {
    var inputValue = this.getFormSelectValue('PostalState');
    if(!inputValue || inputValue == 'Select a state')vars.push('-State');
    }
    
    //Get PostalCode
    var inputValue = this.getFormTextInputValue('PostalCode');
    if(!inputValue)vars.push('-Postcode (numbers only)');
    
    //Get PhoneNumber
    var inputValue = this.getFormTextInputValue('PhoneNumber');
    if(!inputValue)vars.push('-Phone (numbers only)');
    
    //Get FaxNumber
    var inputValue = this.getFormTextInputValue('FaxNumber');
    //if(!inputValue)vars.push('-Fax (numbers only)');
    
    //Get EmailAddress
    var inputValue = this.getFormTextInputValue('EmailAddress');
    if(!inputValue)vars.push('-Email');
    
    if(vars.length > 0)return 'You must fill out the following field(s):\n\n';
    
    //second step of validation
    var reNumbersOnly = /^[0-9]+$/;
    var reEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    
    //Get PostalCode
    var isoverseasOrder = this.getFormRadioInputValue('overseasOrder');
    var inputValue = this.getFormTextInputValue('PostalCode');
    var reNumbersOnly = /^[0-9]+$/;
    if (!inputValue || !reNumbersOnly.test(inputValue) || (isoverseasOrder == "0" && inputValue.length > 4)) vars.push('-Postcode (numbers only)');
    
    //Get PhoneNumber
    var inputValue = this.getFormTextInputValue('PhoneNumber');
    if(!inputValue || !reNumbersOnly.test(inputValue))vars.push('-Phone (numbers only)');
    
    //Get FaxNumber
    var inputValue = this.getFormTextInputValue('FaxNumber');
    //if(!inputValue || !reNumbersOnly.test(inputValue))vars.push('-Fax (numbers only)');
    
    //Get EmailAddress
    var inputValue = this.getFormTextInputValue('EmailAddress');
    var reEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    if(!inputValue || !reEmail.test(decodeURIComponent(inputValue)))vars.push('-Email');
    
    if(vars.length > 0)return 'Please verify the following field(s):\n\n';
    
    return true;    
};

CheckoutCookie.prototype.validate_step2 = function(vars)
{
    //Get firstname
    var inputValue = this.getFormTextInputValue('Inv_Order_Number');
    if(!inputValue)vars.push('-Customer order number');
   
    if(vars.length > 0)return 'You must fill out the following field(s):\n\n';
    
    return true;    
};



