    /* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

CandF = function() {

    //private
    function downloadException() {
        var msgel = $('download-message');
        msgel.setStyle({color:'#ff0000'});
        msgel.update('Sorry, there was a problem authenticating your download, please try again');
        msgel.appear();
    }


    return {
        downloadDoc: function(id, pwdEl) {

            var passwd = $(pwdEl).value;

//            console.log(passwd);

            new Ajax.Request('/site_includes/xhr_download.php',{
                parameters: {mode:'validatePw',id: id, pw: passwd},
                onSuccess: function(t) {
                    var r = t.responseText, msgel = $('download-message');

                    if(r == 'OK') {
                        msgel.setStyle({color:'#225f17'});
                        msgel.update('Thank You, your download will begin shortly');
                        msgel.appear();
                        setTimeout(function() {
                            location = '/site_includes/xhr_download.php?mode=downloadFile';
                        }, 4000);
                    }
                    else {
                        msgel.setStyle({color:'#990000'});
                        msgel.update('Sorry, the password entered is not correct, please re-enter and try again');
                        msgel.appear();
                    }
//                    console.log(arguments);

                },
                onFailure: downloadException,
                onException: downloadException

            });
        },

        saveVATStatus: function(status) {
            new Ajax.Request('/shop/xhr_checkout.php',{
                parameters: {mode:'saveVATStatus',status:status},
                onSuccess: function(t) {
                    var values = t.responseText.evalJSON();
                    $("myCartVat").update(values.vat);
                    $("myGrandTotal").update(values.total);
                }


            });
        },
//savePersonalDetails: function() {
//
//            //validation
//            var valid = 1;
//            var output = "";
//            var requiredFields = "order_firstname,order_lastname,order_company,order_job_title,order_email,order_phone,order_streetaddress,order_city,order_county,order_postcode,order_country,order_shipname,order_shipstreetaddress,order_shipcity,order_shipcounty,order_shippostcode,order_shipcountry";
//            requiredFields = requiredFields.split(",");
//
//            $$("#details-form input,#details-form select").invoke("removeClassName","invalidField");
//
//            for(var i = 0; i < requiredFields.length; i++) {
//                output = output+requiredFields[i]+":"+$(requiredFields[i]).value+"\n";
//                if($(requiredFields[i]).value == "") {
//                    $(requiredFields[i]).addClassName("invalidField");
//                    valid = 0;
//                }
//            }
//
//            if(valid == 1) {
//                $("panel-x-details").down("h2").update("Your Details");
//                $('details-form').request({
//                   parameters:  {mode:'saveDetails'}
//                });
//                tabs.change('panel-x-delegates', $('tab-x-delegates'));
//            } else {
//                $("panel-x-details").down("h2").update("Your Details - <span style='color:#ff585f'>Please fill in fields marked red</span>");
//            }
//        },

        saveDelegatesToOrder: function(nextpage) {
            //validate
            var valid = 1;

            
            if(nextpage == "payment") {
                var requiredFields = "name|jobtitle|email"; //ask kevin
                $$("#delegates-form input").invoke("removeClassName","invalidField");
				$$(".validationText").invoke("remove");
                $$("#delegates-form input").each(function(e) {
                    if( e.name.match(/.*(title|name|jobtitle|email).*/) ) {
                        if(e.value == "") {
                            e.addClassName("invalidField");
                            valid = 0;
                        }
                    }
					if( e.name.match(/.*(email).*/) ) {
                        if(!e.value.match(/^[^@]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/) && e.value != "") {
                            e.addClassName("invalidField");
							e.insert({'after':'<div class="validationText">Input valid email address</div>'});
                            valid = 0;
                        }
                    }
                });
            }

            if(valid == 1) {
                $("panel-x-delegates").down("h2").update("Delegates");
                $('delegates-form').request({
                   parameters:  {mode:'saveDelegates'}
                });
                tabs.change('panel-x-'+nextpage, $('tab-x-'+nextpage));
            } else {
                $("panel-x-delegates").down("h2").update("Delegates - <span style='color:#ff585f'>Please fill in fields marked red</span>");
            }

        },

        savePaymentMethod: function() {
            $('payment-form').request({
               parameters:  {mode:'saveDetails'}
            });
        },

        getOrderDetails: function(cb) {

            cb = cb || Prototype.emptyFunction;

            new Ajax.Request('/shop/xhr_checkout.php', {
                method: 'post',
                parameters: {mode:'getDetails'},
                onSuccess: function(t) {
                    var r = t.responseJSON;
                    if(r && r.success) {
                        cb(r.details);
                    }
                }
            });
        },

        submitOrder: function() {

            var meth = $RF('radios-payment-method');

            if(!meth) {
                Shop.showMessage({
                    title:'Payment Method',
                    msg: 'Please select a payment method to continue',
                    position:'center', //$('radios-payment-method'),
                    duration:0
                });
//                alert('Please select a payment method');
                return;
            }

            if(meth == "netbanx") {
                this.submitToNetBanx();
            }
            else {
                location='/main/thanks.php';
            }

//            console.log(meth);



        },

        submitToNetBanx: function() {
            
//    <form name="netbanxForm" id="netbanxForm" action="https://www.netbanx.com/cgi-bin/payment/CITY-FINANCIAL" method="POST" />
//        <input type="hidden" name="payment_amount" value="<?php echo $CART->grandTotal() ?>" />
//        <input type="hidden" name="currency_code" value="<?php echo $CART->getCurrency() ?>" />
//        <input type="hidden" name="cardholder_name" value="<?php echo $details['order_firstname']." ".$details['order_lastname'] ?>" />
//        <input type="hidden" name="email" value="<?php echo $details['order_email'] ?>" />
//        <input type="hidden" name="houseno" value="<?php echo $details['order_streetaddress'] ?>" />
//        <input type="hidden" name="postcode" value="<?php echo $details['order_postcode'] ?>" />
//        <input type="hidden" name="orderID" value="<?php echo $CART->getOrderId(); ?>" />
//        <!--<input type="submit" value="Proceed" class="sbmt_btn" />-->
//    </form>

            var frmId = 'netbanxForm';

            if($(frmId)) {
                $(frmId).remove();
            }
            
            var fields = { //- netbanx field name translation to our own
                nbx_payment_amount: 'order_total',
                nbx_currency_code: 'order_currency',
                nbx_cardholder_name: ['order_firstname','order_lastname'],
                nbx_email: 'order_email',
                nbx_houseno: 'order_streetaddress',
                nbx_postcode: 'order_postcode',
                orderID: 'order_id'
            };

            this.getOrderDetails(function(details) {
                
                var frm = new Element('form', {
                    action: 'https://pay.netbanx.com/cityandfinancial',
                    method: 'post',
                    id: frmId
                });

                $H(fields).each(function(item) {
                    var val = '';
                    if(typeof item[1] == 'object') {
                        item[1].each(function(el) {
                            val += details[el] + ' ';
                        });
                        val = val.strip();
                    }
                    else {
                        val = details[item[1]];
                    }

                    //make the payment ammount in the correct format
                    if(item[0] == 'nbx_payment_amount') {
                        val = Math.ceil(val*100);
                    }

                    frm.insert(
                        new Element('input', {type:'hidden', name:item[0], value: val})
                    );

                });

                //This is a new required field which is our reference on netbanxs, it will be merchante name + order id + time
                frm.insert(
                    new Element('input', {type:'hidden', name:'nbx_merchant_reference', value: 'cityandfinancial-'+details['order_id']+"-"+Date()})
                );
                frm.insert(
                    new Element('input', {type:'hidden', name:'nbx_success_url', value: 'http://www.cityandfinancial.com/shop/gateways/netbanx/callback.php'})
                );
                frm.insert(
                    new Element('input', {type:'hidden', name:'nbx_success_show_content', value: '1'})
                );
                frm.insert(
                    new Element('input', {type:'hidden', name:'nbx_failure_url', value: 'http://www.cityandfinancial.com/shop/gateways/netbanx/callback.php'})
                );
                frm.insert(
                    new Element('input', {type:'hidden', name:'nbx_failure_show_content', value: '1'})

                );
                
                frm.insert(
                    new Element('input', {type:'hidden', name:'nbx_success_redirect_url', value: 'http://www.cityandfinancial.com/main/thanks_s.php'})
                );

                frm.insert(
                    new Element('input', {type:'hidden', name:'nbx_failure_redirect_url', value: 'http://www.cityandfinancial.com/main/thanks_d.php'})
                );
                
                frm.insert(
                    new Element('input', {type:'hidden', name:'nbx_redirect_exclude', value: 'nbx_houseno_auth,nbx_success_show_content,nbx_retries_remaining,nbx_postcode_auth,nbx_merchant_reference,nbx_houseno,nbx_netbanx_reference,nbx_email,orderID,nbx_cardholder_name,nbx_currency_code,nbx_failure_show_content,nbx_CVV_auth,nbx_postcode,nbx_payment_type,nbx_success_url,nbx_failure_url,nbx_payment_amount'})
                );



                $(document.body).insert(frm);

                frm.submit();

            });

        }
    }
}();

document.observe('dom:loaded', function() {

    //- removes the 'View Basket' menu item when the carts not on the page
    if(!$('mini-cart') && $('cart-summary')) {
        $('cart-summary').up().next().remove();
        $('cart-summary').up().remove();
    }

});