/** * @author Michal Wrzesniewski */


    DPI:null;

document.observe('dom:loaded', function(){
    if($('DPI_checker')){
        DPI = $('DPI_checker').offsetWidth;
    }
});

document.observe('dom:loaded', function(){
    if($('stationeryStepsWrapper')){
        Stationery.StepsHighlighter.hightlightFirst();
        $('approvalPersonEmail').disabled = true;
        $('so_edit_emailSelect').disabled = true;
        if($('so_quantity')){
        $('so_quantity').disabled = true;
        }
    }
});



var Stationery = {

    selectedContainer: null,
    selectedContainer_center: null,
    selectedContainer_right: null,
    selectedContainer_width: null,
	
    displaySeletedDeliveryAddress: function(address_id){
	
        if($('selectedAddressTextArea')){
            $('selectedAddressTextArea').update='';
            var selectedAddressDetails = $('customDropDownList_'+address_id).innerHTML;
            $('selectedAddressTextArea').innerHTML=selectedAddressDetails;
            $('deliveryAddress_id').value=address_id;
	
        }
    },
	
    

    
    setSelectedContainer:function(container){
        this.selectedContainer = container;
    },

    deselectContainer:function(){
        this.closeEditor();
        this.selectedContainer = null;
    },

    getSelectedContainer:function(){
        return this.selectedContainer;
    },

    openEdtior: function(event){
        this.StepsHighlighter.hightlightCurrent(0);
        event = event || window.event;
        Event.stop(event);

        var container = this.selectedContainer;
        var cont=$(container);
        if (Prototype.Browser.IE) {
            var contText=cont.innerText
        }else{
            contText = cont.textContent;
        }
     
        this.selectedContainer_right = (parseFloat(cont.style.left))* (DPI / 25.4) + cont.getWidth();
        this.selectedContainer_center = (parseFloat(cont.style.left))* (DPI / 25.4) + (cont.getWidth() / 2);
        this.selectedContainer_width = cont.getWidth();

        cont.innerHTML='';

        var editinplaceInput = new Element('INPUT', {
            id: 'editinplaceInput',
            type: 'text',
            value: contText
        });
        cont.appendChild(editinplaceInput);
        var eipi = $('editinplaceInput');
        eipi.style.width = this.selectedContainer_width + 'px';
        eipi.setAttribute('size', cont.length);
        eipi.style.fontFamily = $(cont).style.fontFamily;
        eipi.style.fontStyle = $(cont).style.fontStyle;
        eipi.style.fontWeight = $(cont).style.fontWeight;
        eipi.style.fontSize = $(cont).style.fontSize;
        eipi.style.color = $(cont).style.color;
        eipi.focus();

        document.observe('click', function(){
            this.closeEditor();
        }.bind(this));

        document.observe('keydown', function(event){
            if (event.keyCode == 13) {
                this.closeEditor();
            }
        }.bind(this));

        editinplaceInput.observe('click', function(e) {
            Event.stop(e)
        });

        editinplaceInput.observe('dblclick', function(e) {
            Event.stop(e)
        });

    },
    closeEditor: function(){
        if($('editinplaceInput')){
            var container = this.getSelectedContainer();
            var content = $('editinplaceInput').getValue();
            $('editinplaceInput').parentNode.removeChild($('editinplaceInput'));
            $(container).update(content);
            var eipiWidth = $(container).getWidth();

            this.saveContainerSetting('setContent',content);

            if($(container).style.textAlign == 'center'){
                var newPos1 = parseFloat(this.selectedContainer_center - (eipiWidth /2));
                $(container).style.left = PDFgenarator.convertToMM(newPos1 + 'px') + 'mm';
                this.saveContainerSetting('setHorizontalPosition',PDFgenarator.convertToMM(newPos1 + 'px'))
            }

            if($(container).style.textAlign == 'right'){
                var newPos2 = parseFloat(this.selectedContainer_right - eipiWidth);
                $(container).style.left = PDFgenarator.convertToMM(newPos2 + 'px') + 'mm';
                this.saveContainerSetting('setHorizontalPosition',PDFgenarator.convertToMM(newPos2 + 'px'))
            }
        }
    },
    saveContainerSetting:function(setting, value){
        var url = '../designer/xhr_actions.php';
        var params = 'task='+ setting;
        params += '&value=' + value;
        params += '&container_id=' + this.getSelectedContainer();
        params += '&type=text';
        new Ajax.Request(url, {
            method: 'get',
            parameters: params,
            //onFailure: reportError,
            onComplete: function(t) {
                if(t.responseText != 'Success') {
                    alert('ERROR: ' + t.responseText)
                }
            }.bind(this)
        });

    },
    StepsHighlighter:{
        steps:null,
        hightlightedColour:'#E0E0E0',
        setSteps:function(){
            var stepsArray = $$('#stationeryStepsWrapper .stationerySteps');
            return this.steps = stepsArray;
        },
        resetHighlight:function(){
            if(this.steps == null){
                this.setSteps();
            }
            this.steps.each(function(stepElement){
                $(stepElement.id).setStyle({
                    backgroundColor: 'white'
                });
                $(stepElement.id + '_navi').hide();
            })
        },

        hightlightFirst:function(){
            if(this.steps == null){
                this.setSteps();
            }
            this.resetHighlight();
           
            $(this.steps[0].id).setStyle({
                backgroundColor: this.hightlightedColour
            })
            $(this.steps[0].id + '_navi').show();
        },

        hightlightCurrent:function(currentStep){
            if(this.steps == null){
                this.setSteps();
            }
            this.resetHighlight();
            $(this.steps[currentStep].id).setStyle({
                backgroundColor: this.hightlightedColour
            })
            $(this.steps[currentStep].id+'_navi').show();

            if(this.steps[currentStep].id == 'so_edit_step_2'){
                $('generateSampleFileLink').show();
                $('generateSampleFileLink').style.display='block'
            }else{
                $('generateSampleFileLink').hide();
            }
            if(this.steps[currentStep].id == 'so_edit_step_4'){
                $('so_edit_SendForApproval').show();
                if($('so_edit_OrderNow')){
                $('so_edit_OrderNow').show();
                }
                $('approvalPersonEmail').disabled = false;
                $('so_edit_emailSelect').disabled = false;
            }else{
                if($('so_edit_OrderNow')){
                $('so_edit_OrderNow').hide();
                }
                $('so_edit_SendForApproval').hide();
                $('approvalPersonEmail').disabled = true;
                $('so_edit_emailSelect').disabled = true;
            }
            if(this.steps[currentStep].id == 'so_edit_step_3' || this.steps[currentStep].id == 'so_edit_step_4' ){
                if($('so_quantity')){
                    $('so_quantity').disabled = false;
                }
            }else{
                if($('so_quantity')){
                    $('so_quantity').disabled = true;
                }
            }
            
        }
    },

    OrderNow:{
        generateFile:null,
         generateSampleFile:function(cb_func){
             
            var url = 'so_pdf_generator_sample.php';
            var params = 'file_name='+ $('random_key').getValue() +'_sample.pdf';
            params += '&company_name='+ $('company_name').getValue();
            new Ajax.Request(url, {
                method: 'get',
                parameters: params,
                onComplete: function(t){
                    if(t.responseText == 'Success'){
                        this.generateMainFile();
                        cb_func.bind(this)();

                        this.generateFile = true;

                    }else{
                        this.generateFile = false;
                    }
                    return this.generateFile;
                }.bind(this)
            });
        },
        generateMainFile:function(){
            var url = '../designer/pdf_generator.php';
            var params = 'file_name='+ $('random_key').getValue() +'.pdf';
            params += '&company_name='+ $('company_name').getValue();
			
			var categoryId = $('categoryId').getValue();
            new Ajax.Request(url, {
                method: 'get',
                parameters: params,
                onComplete: function(t){
                    if(t.responseText == 'Success'){
                        
                        this.generateFile = true;
                        var document_id = $('document_id').getValue();
                        if($('so_quantity')){
                            var qty = $('so_quantity').getValue();
                            window.location.href='so_custom_order_checkout.php?file_name='+ $('random_key').getValue()+'&qty='+qty + '&document_id='+document_id+'&categoryId='+categoryId;
                        }else{
                            window.location.href='so_custom_order_checkout.php?file_name='+ $('random_key').getValue()+'&document_id='+document_id;
                        }
                    }else{
                        this.generateFile = false;
                    }
                    return this.generateFile;
                }.bind(this)
            });
        },

        redirectToCheckout:function(){
            this.generateSampleFile(this.generateMainFile)
        }

    },

    OrderConfirmation: {
        sendMail:null,
        generateFile:null,
        
        show: function(){
            var emailInput = $('approvalPersonEmail').getValue();           
            var countItems = $$('#DocumentArea .containerForCustomer').size();
            if (countItems==0){
                $('nameForItem').hide();
            }

            if(/\w+@[a-z0-9A-Z.-]+?\.[a-zA-Z]{2,6}/.test(emailInput)!=true){
                alert('Enter correct email');
                return false;
            }
            if($('so_quantity')){
                if(!$('so_quantity').getValue()){
                    alert('Please go back to step 3 and select quantity');
                    return false;
                }
            }
            var frame = $('finalOrderConf_frame');
            //alert('before lightbox');
            lightbox.show(frame, 550,450);
            //lightbox.show(frame);
            //alert('after lightbox');
            //$('finalOrderConf_Status').hide();
            //$('finalOrderConf_text').show();
            
           // frame.appear({
           //     duration: 0.3
           // });
            
        },
        
        processOrder:function(){

             var countItems = $$('#DocumentArea .containerForCustomer').size();
            if(countItems>0 && $('docName').getValue().length<3){
                alert('Name for item cannot be empty and must contain minimum 3 characters');
                return '';
            }
			
			if($('docDeliverTo').getValue().length<2){
				alert('Please fill \'Deliver To\' field');
                return '';
			}

            if($('deliveryAddress_id') && $('deliveryAddress_id').getValue()== -1){
                  alert('Select delivery address');
                return '';
            }
           
            this.generateSampleFile(this.sendAuthorizationMail);
            
        // $('finalOrderConf_text').hide();
        //$('finalOrderConf_Status').show();


        },
        generateSampleFile:function(cb_func){
            var url = 'so_pdf_generator_sample.php';
            var params = 'file_name='+ $('random_key').getValue() +'_sample.pdf';
            params += '&company_name='+ $('company_name').getValue();
            new Ajax.Request(url, {
                method: 'get',
                parameters: params,
                onComplete: function(t){
                    if(t.responseText == 'Success'){
                        this.generateMainFile();
                        cb_func.bind(this)();
                        
                        this.generateFile = true;
                        
                    }else{
                        this.generateFile = false;
                    }
                    return this.generateFile;
                }.bind(this)
            });
        },
        generateMainFile:function(){
            var url = '../designer/pdf_generator.php';
            var params = 'file_name='+ $('random_key').getValue() +'.pdf';
            params += '&company_name='+ $('company_name').getValue();
            new Ajax.Request(url, {
                method: 'get',
                parameters: params,
                onComplete: function(t){
                    if(t.responseText == 'Success'){
                        this.generateFile = true;
                    }else{
                        this.generateFile = false;
                    }
                    return this.generateFile;
                }.bind(this)
            });
        },
        
        sendAuthorizationMail:function(){
            
            var qty = null;// $('so_quantity').getValue();
            if($('so_quantity')){
                qty = $('so_quantity').getValue();				
            }else{
				qty=0;
			}
			
            var countItems = $$('#DocumentArea .containerForCustomer').size();
            if(countItems==0){
                var blankItem = 0;
            }else{
                blankItem = 1;
            }
            var email = $('approvalPersonEmail').getValue();
            
            var url = 'so_process_order.php';
            var params = 'email=' + email;
            params += '&quantity=' + qty;
            params += '&file_name=' + $('random_key').getValue() +'_sample.pdf';
            params += '&company_name='+ $('company_name').getValue();
            params += '&deliveryAddressId='+ $('deliveryAddress_id').getValue();
            params += '&categoryId='+ $('categoryId').getValue();
			   if($('docName').getValue()!=''){
		   params += '&docName='+ $('docName').getValue();
			   }
			   if($('docReferenceNo').getValue()!=''){
		   params += '&referenceNo='+ $('docReferenceNo').getValue();
			   }
			   if($('docDeliverTo').getValue()!=''){
		   params += '&deliverTo='+ $('docDeliverTo').getValue();
			   }
			   
			   if($('so_specialInstruction').getValue()!=''){
		   params += '&specialInstruction='+ $('so_specialInstruction').getValue();
			   }
			   
			   if($('categoryId').getValue()!=''){
		   params += '&categoryId='+ $('categoryId').getValue();
			   }
			   

			params += '&blankItem=' + blankItem;
            params += '&KT_Insert=' + 1;
           
           new Ajax.Request(url, {
                method: 'get',
                parameters: params,
                onComplete: function(t) {
                    if(t.responseText == 'Success'){
                        this.sendMail = true;
						
                    }else{
                        this.sendMail = false;
                    }
                    this.displayInfo();
                    
                    return this.sendMail;

                }.bind(this)
            
            });
        },
        displayInfo:function(){
            
           var status_text='Thank you.<br /><br /><br />A sample pdf file was sent for futher authorisation. We will inform you about the result as soon as possible.';
            status_text +='<br /><p>If you have any problems please do not hesitate to contact the team on 0845 643 1637 or ';
            status_text +='<a href="mailto:info@taurus-solutions.co.uk">info@taurus-solutions.co.uk</a></p>';
            status_text +='<br /><br /><center><a class="sendStationery" style="width:250px" href="../customers/so_stationery_home.php">Stationery Ordering Home Page</a></center>';

            $('finalOrderConf_text').hide();
            $('finalOrderConf_buttons').hide();
            $('finalOrderConf_Status').update(status_text);
            $('finalOrderConf_Status').show();
            
        }
    },

    updatePrice: function(rateid){
        var rate = $(rateid).getValue();
        var url = 'so_xhr_actions.php';
        var task='getPrice';
        var params = 'task=' + task;
        params += "&rate_id=" + rate;

        new Ajax.Request(url, {
            asynchronous: false,
            method: 'get',
            parameters: params,
            onComplete: function(t) {
                var resp=t.responseText;
                $('rate_response').update('')
                $('rate_response').update('Price: <strong> &pound;'+resp+'</strong>')
            }
        });
    }

}

var PDFgenarator = {
    

    convertToMM:function(value){
    
        var  unit = value.substr(value.length - 2);
 
        if (unit == 'px') {

            var x = parseFloat(value.substr(0, value.length - 2) / DPI * 25.4);

            x = (parseFloat(Math.round(x*Math.pow(10, 2))) / Math.pow(10, 2));

        }
        if (unit == 'mm') {
            x = parseFloat(value.substr(0, value.length - 2));
            x = (parseFloat(Math.round(x*Math.pow(10, 2))) / Math.pow(10, 2));
        }
        return new Number(parseFloat(x)).toFixed(2);
       
    },

    setupHeightForCustomerContainers: function(){
        var containersArray = $$('#DocumentWorkArea > .containerForCustomer');
        containersArray.each(function(el){
            var height = PDFgenarator.convertToMM((el).getHeight() + 'px');
            var task = 'updateContainerHeight'
            var url = '../designer/xhr_actions.php';
            var params = 'task=' + task + "&container_id=" + el.id + "&height=" + height;
            new Ajax.Request(url, {
                method: 'get',
                parameters: params
            });
        })
    },
    setupWidthForCustomerContainers: function(){
        var containersArray = $$('#DocumentWorkArea > .containerForCustomer');
        containersArray.each(function(el){
            var width = PDFgenarator.convertToMM((el).getWidth() + 'px');
            var task = 'updateContainerWidth'
            var url = '../designer/xhr_actions.php';
            var params = 'task=' + task + "&container_id=" + el.id + "&width=" + width;
            new Ajax.Request(url, {
                method: 'get',
                parameters: params
            });
        })
    },


    setupHeightForContainers: function(){
        var containersArray = $$('#DocumentWorkArea > .container');
        containersArray.each(function(el){
            var height = PDFgenarator.convertToMM((el).getHeight() + 'px');
            var task = 'updateContainerHeight'
            var url = '../designer/xhr_actions.php';
            var params = 'task=' + task + "&container_id=" + el.id + "&height=" + height;
            new Ajax.Request(url, {
                method: 'get',
                parameters: params
            });
        })
    },
    setupWidthForContainers: function(){
        var containersArray = $$('#DocumentWorkArea > .container');
        containersArray.each(function(el){
            var width = PDFgenarator.convertToMM((el).getWidth() + 'px');
            var task = 'updateContainerWidth'
            var url = '../designer/xhr_actions.php';
            var params = 'task=' + task + "&container_id=" + el.id + "&width=" + width;
            new Ajax.Request(url, {
                method: 'get',
                parameters: params
            });
        })
    },

    thewindow:null,
    generate: function(){
        if(this.thewindow!=null){
            this.thewindow.close();
            this.thewindow = null;
        }
        this.setupHeightForContainers();
        this.setupHeightForCustomerContainers()
        this.setupWidthForContainers();
        this.setupWidthForCustomerContainers();
        // var url = '../designer/pdf_generator.php';
        var url = 'so_pdf_generator_sample.php';
        this.thewindow = window.open(url,null,
            "height=600,width=800,status=yes,toolbar=no,menubar=no,location=no,resizable=yes");

    /*window.open( url ,'nxwindow'
			   , 'width='+500+',height='+500+',top='+1+',left='+l
				 + ',directories=no,location=no,menubar=no'
				 + ',resizable=yes,scrollbars=no,status=no,toolbar=no');
         */
    }
}






