var devEnv = '';
var usingBadIE = false;
var usingIE = false;
    
if ( document.URL.toString().indexOf('_dev.php',0) > -1 ) {
    devEnv = '/fastprint_dev.php';
}
var dialogs = new Array();

/* Should we be rotating the BOTW? */
var rotateBotw = true;
var countBotw = 1;
var botwLength = 1;
    
function isValidEmail(email) {
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return filter.test(email);
}

/* tests to see if string is in correct UK style postcode: AL1 1AB, BM1 5YZ etc. */
function isValidPostcode(p) {
    var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
    return postcodeRegEx.test(p);
}

/* formats a VALID postcode nicely: AB120XY -> AB1 0XY */
function formatPostcode(p, field) {
    if (isValidPostcode(p)) {
        var postcodeRegEx = /(^[A-Z]{1,2}[0-9]{1,2})([0-9][A-Z]{2}$)/i;
        $(field).val(p.replace(postcodeRegEx,"$1 $2"));
        return true;
    } else {
        return false;
    }
}

if (jQuery.browser.msie && jQuery.browser.version >= 9) {
    jQuery.support.noCloneEvent = true;
}

/** 
 * Cycle through the BOTW's (Books of the week)
 */
function cycleBotw(seconds) {
    var cycleTime = seconds * 1000;
    if (rotateBotw) {
        $('.currentBotw').removeClass('currentBotw');
        $('.botwData').hide();
        $('#bookContentNo' + countBotw).show();
        $('#bookContentNo' + countBotw).addClass('currentBotw');
        
        var elementId = $('.currentBotw').attr('id').substr(13);
        var bookImg = $('#bookImage' + elementId + ' img');
        var bookPos = $(bookImg).position().left + 50;
        $('.bookList .arrow').animate({
            left: bookPos
        });
        
        //       $('.bookList .arrow').css('left', bookPos + 'px');
        countBotw++;
        if (countBotw > botwLength) {
            countBotw = 1;
        }
    }
    
    setTimeout(function(){
        cycleBotw(seconds)
    }, cycleTime);
}

function checkPromoCode(fieldID){    
    var code = $(fieldID).val();
    var promoValues = {};
    promoValues['code'] = code;
    promoValues['total'] = $('#quoteTotal').text();
            
    $.post(devEnv + '/checking-promo-code', {
        'values' : promoValues
    }, function(promoData,status) {
        $('.quoteDetails tr.promo').remove();
        if (promoData['valid'] == true) {
            $('.quoteDetails').append('<tr class="promo"> <td>Promo Code ('+code+') <span class="quantity">Discount: '+promoData['percent']+'%</span> </td> <td class="price"> -&pound;'+parseFloat(promoData['discount']).toFixed(2)+'</td> </tr>');
            if ($('#ebookQuoteForm').length) {
                var curTotal = parseFloat($('#quoteTotal').text()).toFixed(2);
                var newTotal = parseFloat(curTotal -= parseFloat(promoData['discount']).toFixed(2)).toFixed(2);
                $('#quoteTotal').text(newTotal);
            }
        }
    });
}

function quoteUncheck(formID, fieldclass, removeFromRight) {
    if ($('.quoteDetails tr.'+fieldclass).length) {
        $('.quoteDetails tr.'+fieldclass).remove();
    }
    if (rightColumn[fieldclass] && removeFromRight) {
        rightColumn[fieldclass] = null;
    }
    if ($('#'+formID+'_'+fieldclass+'_lab').length) {
        $('#'+formID+'_'+fieldclass+'_lab').removeClass('checked');
        $('#'+formID+'_'+fieldclass+'_lab').parent().find('input').removeAttr('checked');
        $('#'+formID+'_'+fieldclass+'_lab').parent().find('label').removeAttr('checked');
        $('#'+formID+'_'+fieldclass+'_lab').parent().find('input').checked = false;
    }
}

$(document).ready(function() {
    if ($('.body').length) {
        $('.body').addClass('hasJs');
    }
    
    
    if ($('#quoteTotalDiv').length) {
        $('#quoteTotalDiv').removeClass('fixed');
        var lTop = ($('#quoteTotalDiv').offset().top - parseFloat($('#quoteTotalDiv').css('marginTop').replace(/auto/,0)));

        $(window).scroll(function () {
            // what the y position of the scroll is
            var y = $(this).scrollTop();

            usingBadIE// whether that's below the form
            if (y >= lTop) {
                // if so, ad the fixed class
                $('#quoteTotalDiv').addClass('fixed');
            } else {
                // otherwise remove it
                $('#quoteTotalDiv').removeClass('fixed');
            }
        });

    }
    
    if ($.browser.msie) {
        usingIE = true;
        if ($.browser.version < 9) {
            usingBadIE = true;
        }
    }
    
    
    if ($('.quoteBoxed').length) {
        rightColumn['format'] = 'paperback';
        //        rightColumn['basics'] = 'mono';
                
        $('.quoteColumns #quoteForm_promo, .quoteColumns #ebookQuoteForm_promo').live('change', function(){
            checkPromoCode(this);
        });
        
        
        var wordcount = 0;
        $('.quoteColumns .rightColumn table.quoteDetails').show();
        
        if (!$('#ebookQuoteForm').length) {
            $('.quoteBoxed input').live('change', function(){
                var inputLabel = $(this).parent().find('label');
                if (inputLabel.attr('id') == 'quoteForm_bespokecover_lab') {
                    quoteUncheck('quoteForm', 'standardcover', 'standardcover', true);
                }
                if (inputLabel.attr('id') == 'quoteForm_standardcover_lab') {
                    quoteUncheck('quoteForm', 'bespokecover', 'bespokecover', true);
                }
                if (inputLabel.attr('id') == 'quoteForm_paperback_lab') {
                    quoteUncheck('quoteForm', 'quoteForm', 'hardback', true);
                }
                if (inputLabel.attr('id') == 'quoteForm_hardback_lab') {
                    quoteUncheck('quoteForm', 'quoteForm', 'paperback', true);
                }
                if (inputLabel.hasClass('checked')) {
                    inputLabel.removeClass('checked');
                } else {
                    inputLabel.addClass('checked');
                }
            });

            $('#quoteForm_wordcount').live('change', function(){
                var inputClass = '';
                var value = 0;
                var quantity = 0;
                wordcount = parseInt($('#quoteForm_wordcount').val());
                if (rightColumn['proofread'] && rightColumn['proofread'] != null) {
                    inputClass = 'proofread';
                    $('.quoteDetails tr.' + inputClass).remove();
                    value = $(this).parent().find('input').val();
                    if ($(this).val() > 0) {
                        quantity = $(this).val()/1000;
                        var wordcountText = wordcount + ' words';
                        if (quantity < 1) {
                            quantity = 1;
                            wordcountText = 'Minimum charge applies';
                        }
                        $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Proofread <span class="quantity">'+wordcountText+'</span> </td> <td class="price"> &pound;'+(quantity*prices[inputClass]).toFixed(2)+'</td> </tr>');
                    }
                }
                if (rightColumn['layout'] && rightColumn['layout'] != null) {
                    inputClass = 'layout';
                    $('.quoteDetails tr.' + inputClass).remove();
                    value = $(this).parent().find('input').val();
                    if ($(this).val() > 0) {
                        quantity = $(this).val()/1000;
                        if (quantity < 1) {
                            quantity = 1;
                        }
                        var layoutPrice = (quantity*prices[inputClass]);
                        var wordcountText = wordcount + ' words';
                        if (layoutPrice < 25) {
                            layoutPrice = 25;
                            wordcountText = 'Minimum charge applies';
                        }
                        $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Page Layout <span class="quantity">'+wordcountText+'</span> </td> <td class="price"> &pound;'+layoutPrice.toFixed(2)+'</td> </tr>');
                    }
                }
            });
        
            $('#list-id-8 input').click(function(){
                var inputClass = 'paperback';
            
                if (!rightColumn['format'] || rightColumn['format'] == 'hardback') {
                    quoteUncheck('quoteForm', 'hardback', true);
                    $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Publishing Essentials: Paperback </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                }
                rightColumn['format'] = inputClass;
            });
        
            $('#list-id-9 input').click(function(){
                var inputClass = 'hardback';
            
                if (!rightColumn['format'] || rightColumn['format'] == 'paperback') {
                    quoteUncheck('quoteForm', 'paperback', true);
                    $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Publishing Essentials: Hardback </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                }
                rightColumn['format'] = inputClass;
            
            });
        
            //        $('#list-id-10 input').live('click', function(){
            //            var inputClass = 'mono';
            //            
            //            if (!rightColumn['basics'] || rightColumn['basics'] == 'colour') {
            //                $('.quoteDetails tr.colour').remove();
            //                $('#quoteForm_colour').removeAttr('checked');
            //                $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Publishing: Mono </td> <td class="price"> &pound;'+prices[inputClass]+'</td> </tr>');
            //            }
            //            rightColumn['basics'] = inputClass;
            //            
            //        });
            //        
            //        $('#list-id-11 input').live('click', function(){
            //            var inputClass = 'colour';
            //            
            //            if (!rightColumn['basics'] || rightColumn['basics'] == 'mono') {
            //                $('.quoteDetails tr.mono').remove();
            //                $('#quoteForm_mono').removeAttr('checked');
            //                $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Publishing: Colour </td> <td class="price"> &pound;'+prices[inputClass]+'</td> </tr>');
            //            }
            //            rightColumn['basics'] = inputClass;
            //            
            //        });
        
            $('#list-id-10 input').click(function(){
                var inputClass = 'proofread';
                $('.quoteDetails tr.' + inputClass).remove();
                wordcount = parseInt($('#quoteForm_wordcount').val());
            
                if (rightColumn[inputClass] && rightColumn[inputClass] != null) {
                    quoteUncheck('quoteForm', inputClass, true);
                } else {
                    var value = $(this).parent().find('input').val();
                    var quantity = 1;
                    if ($('#quoteForm_wordcount').val() > 0) {
                        quantity = parseInt($('#quoteForm_wordcount').val()/1000);
                    var wordcountText = wordcount + ' words';
                        if (quantity < 1) {
                            quantity = 1;
                            wordcountText = 'Minimum charge applies';
                        }
                
                        $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Proofread <span class="quantity">'+wordcountText+' words</span> </td> <td class="price"> &pound;'+(quantity*prices[inputClass]).toFixed(2)+'</td> </tr>');
                    }
                    rightColumn[inputClass] = true;
                }
            });
        
            $('#list-id-11 input').click(function(){
                var inputClass = 'layout';
                $('.quoteDetails tr.' + inputClass).remove();
                wordcount = parseInt($('#quoteForm_wordcount').val());
            
                if (rightColumn[inputClass] && rightColumn[inputClass] != null) {
                    quoteUncheck('quoteForm', inputClass, true);
                } else {
                    var value = $(this).parent().find('input').val();
                    var quantity = 1;
                    if ($('#quoteForm_wordcount').val() > 0) {
                        quantity = parseInt($('#quoteForm_wordcount').val()/1000);
                        if (quantity < 1) {
                            quantity = 1;
                        }
                        var layoutPrice = (quantity*prices[inputClass]);
                        var wordcountText = wordcount + ' words';
                        if (layoutPrice < 25) {
                            layoutPrice = 25;
                            wordcountText = 'Minimum charge applies';
                        }
                    
                        $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Page Layout <span class="quantity">'+wordcountText+'</span> </td> <td class="price"> &pound;'+layoutPrice.toFixed(2)+'</td> </tr>');
                    }
                
                    rightColumn[inputClass] = true;
                }
            });
        
            $('#list-id-12 input').click(function(){
                var inputClass = 'bespoke';
                $('.quoteDetails tr.standard').remove();
                rightColumn['standard'] = null;
                quoteUncheck('quoteForm', 'standardcover', 'standardcover', true);
            
                if (rightColumn[inputClass] && rightColumn[inputClass] != null) {
                    $('.quoteDetails tr.' + inputClass).remove();
                    rightColumn[inputClass] = null;
                } else {
                    var value = $(this).parent().find('input').val();
                    $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Bespoke Cover Design: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                    rightColumn[inputClass] = true;
                }
            });
        
            $('#list-id-13 input').click(function(){
                var inputClass = 'standard';
                $('.quoteDetails tr.bespoke').remove();
                quoteUncheck('quoteForm', 'bespokecover', 'bespokecover', true);
                rightColumn['bespoke'] = null;
            
                if (rightColumn[inputClass] && rightColumn[inputClass] != null) {
                    $('.quoteDetails tr.' + inputClass).remove();
                    rightColumn[inputClass] = null;
                } else {
                    var value = $(this).parent().find('input').val();
                    $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Standard Cover Design: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                    rightColumn[inputClass] = true;
                }
            });
        
            $('#list-id-14 input').click(function(){
                var inputClass = 'publicity';
            
                if (rightColumn[inputClass] && rightColumn[inputClass] != null) {
                    quoteUncheck('quoteForm', inputClass, true);
                } else {
                    var value = $(this).parent().find('input').val();
                    $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Publicity Pack: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                    rightColumn[inputClass] = true;
                }
            });
        
            $('#list-id-15 input').click(function(){
                var inputClass = 'pressrelease';
            
                if (rightColumn[inputClass] && rightColumn[inputClass] != null) {
                    quoteUncheck('quoteForm', inputClass, true);
                } else {
                    var value = $(this).parent().find('input').val();
                    $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Press Release Pack: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                    rightColumn[inputClass] = true;
                }
            });
        
            $('#list-id-16 input').click(function(){
                var inputClass = 'additionalhardback';
            
                if (rightColumn[inputClass] && rightColumn[inputClass] != null) {
                    quoteUncheck('quoteForm', inputClass, true);
                } else {
                    var value = $(this).parent().find('input').val();
                    $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Additional Hardback Edition: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                    rightColumn[inputClass] = true;
                }
            });
        
            $('#list-id-17 input').click(function(){
                var inputClass = 'additionalebook';
                quoteUncheck('quoteForm', 'additionalebookstandard', false);
                quoteUncheck('quoteForm', 'additionalebookpremium', false);
            
                if (rightColumn[inputClass] && rightColumn[inputClass] == 'additionalebook') {
                    quoteUncheck('quoteForm', inputClass, true);
                } else {
                    var value = $(this).parent().find('input').val();
                    $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Start-up E-Book Conversion: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                    rightColumn[inputClass] = 'additionalebook';
                }
            });
        
            $('#list-id-18 input').click(function(){
                var inputClass = 'additionalebookstandard';
                quoteUncheck('quoteForm', 'additionalebook', false);
                quoteUncheck('quoteForm', 'additionalebookpremium', false);
            
                if (rightColumn['additionalebook'] && rightColumn['additionalebook'] == inputClass) {
                    quoteUncheck('quoteForm', 'additionalebook', true);
                    $('.quoteDetails tr.' + inputClass).remove();
                    rightColumn['additionalebook'] = false;
                } else {
                    var value = $(this).parent().find('input').val();
                    $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Standard E-Book Conversion: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                    rightColumn['additionalebook'] = inputClass;
                }
            });
        
            $('#list-id-19 input').click(function(){
                var inputClass = 'additionalebookpremium';
                quoteUncheck('quoteForm', 'additionalebook', false);
                quoteUncheck('quoteForm', 'additionalebookstandard', false);
            
                if (rightColumn['additionalebook'] && rightColumn['additionalebook'] == inputClass) {
                    quoteUncheck('quoteForm', 'additionalebook', true);
                    $('.quoteDetails tr.' + inputClass).remove();
                    rightColumn['additionalebook'] = false;
                } else {
                    var value = $(this).parent().find('input').val();
                    $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Premium E-Book Conversaion: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                    rightColumn['additionalebook'] = inputClass;
                }
            });
        }
    }
    
    if ($('.quoteBoxed').length && $('#ebookQuoteForm').length) {
        rightColumn['additionalebook'] = 'additionalebook';
        $('#ebookQuoteForm_additionalebook_lab').addClass('checked');
        $('#ebookQuoteForm_additionalebook_lab').parent().find('input').attr('checked', 'checked');
        
        $('#list-id-7 input').click(function(){
            var inputClass = 'additionalebook';
            quoteUncheck('ebookQuoteForm', 'additionalebookstandard', false);
            quoteUncheck('ebookQuoteForm', 'additionalebookpremium', false);
            
            if (!rightColumn[inputClass] || rightColumn[inputClass] != 'additionalebook') {
                var value = $(this).parent().find('input').val();
                $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Start-up E-Book Conversion: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                rightColumn[inputClass] = 'additionalebook';
                $('#quoteTotal').text(prices[inputClass].toFixed(2));
                $('#ebookQuoteForm_'+inputClass+'_lab').addClass('checked');
                checkPromoCode('#ebookQuoteForm_promo');
            }
        });
        
        $('#list-id-8 input').click(function(){
            var inputClass = 'additionalebookstandard';
            quoteUncheck('ebookQuoteForm', 'additionalebook', false);
            quoteUncheck('ebookQuoteForm', 'additionalebookpremium', false);
            
            if (!rightColumn['additionalebook'] || rightColumn['additionalebook'] != inputClass) {
                var value = $(this).parent().find('input').val();
                $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Standard E-Book Conversion: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                rightColumn['additionalebook'] = inputClass;
                $('#quoteTotal').text(prices[inputClass].toFixed(2));
                $('#ebookQuoteForm_'+inputClass+'_lab').addClass('checked');
                checkPromoCode('#ebookQuoteForm_promo');
            }
        });
        
        $('#list-id-9 input').click(function(){
            var inputClass = 'additionalebookpremium';
            quoteUncheck('ebookQuoteForm', 'additionalebook', false);
            quoteUncheck('ebookQuoteForm', 'additionalebookstandard', false);
            
            if (!rightColumn['additionalebook'] || rightColumn['additionalebook'] != inputClass) {
                var value = $(this).parent().find('input').val();
                $('.quoteDetails').append('<tr class="'+inputClass+'"> <td>Premium E-Book Conversaion: </td> <td class="price"> &pound;'+prices[inputClass].toFixed(2)+'</td> </tr>');
                rightColumn['additionalebook'] = inputClass;
                $('#quoteTotal').text(prices[inputClass].toFixed(2));
                $('#ebookQuoteForm_'+inputClass+'_lab').addClass('checked');
                checkPromoCode('#ebookQuoteForm_promo');
            }
        });        
    }
    
    if ($('.tooltip').length && !$('#ebookQuoteForm').length) {
        
        if (!usingBadIE) {
            $('.tooltip').each(function(){
                guiders.createGuider({
                    attachTo: $(this),
                    description: $(this).find('.tooltipDesc').text(),
                    id: $(this).parent().find('input').attr('id'),
                    next: "second",
                    position: 3,
                    overlay: true,
                    title: $(this).find('.tooltipTitle').text()
                });
            });
        
            $('#guider_overlay').live('click', function(){
                guiders.hideAll();
            });
        
            $('.tooltip').live('click', function(){
                guiders.hideAll();
                var id = $(this).parent().find('input').attr('id');
                guiders.show(id);
                $(guiders._guiderById(id)).find('a').click(function(e){ 
                    e.preventDefault(); 
                });
            });

        } else if (usingBadIE) {
            $('.tooltipTitle').remove();
            $('.tooltip').live('click', function(){
                var tip = $(this).children('div').text();
                var trimTo = tip.indexOf('<br />');
                if (trimTo >= 0) {
                    tip = tip.substr(0, trimTo);
                }
                alert(tip);
            });
        }
    }
    botwLength = $('.botwData').length;
    
    $('.arrow, .bookList .bookDescription').show();
    $('#bookContentNo1.botwData').show();
   
    $('.botwImgs li img').hover(function(){
        var bookPos = $(this).position().left + 50;
        $('.bookList .arrow').animate({
            left: bookPos
        });
       
        rotateBotw = false;
       
        var li = $(this).parent().parent();
        var bkClass = $(li).attr('class');
        countBotw = $(li).attr('id').substr(-1, 1);
        
        $('.botwData').hide();
        $('.botwData.' + bkClass).show();
    }, function(){
        rotateBotw = true; 
    });
    
    $('.bookDescription').hover(function(){
        rotateBotw = false;
    }, function(){
        rotateBotw = true; 
    });
    
    if ($('.botwData').length) {
        cycleBotw(10);
    }

    /* homepage rotator */
    if ( $('#fphomerotator').length ) {
        $('#fphomerotator li').show();
        $('#fphomerotator')
        .after('<div id="fphomerotator">')
        .cycle({
            fx:     'scrollLeft',
            speed:  2000,
            timeout: 8000,
            /*easing: 'easeOutElastic',*/
            pager:  '#fphomerotatornav'
        });
    }
    if ( $('#fphomebookrotator').length ) {
        $('#fphomebookrotator')
        .before('<div id="fphomebookrotator">')
        .cycle({
            fx:     'scrollLeft',
            speed:  1000,
            timeout: 8000,
            pager:  '#fphomebookrotatornav'
        });
    }

    $('.nav2').mouseout(function() {
        $(this).addClass("bgOff");
        $(this).removeClass("bgOn");
    });
    $('.nav2').mouseover(function() {
        $(this).addClass("bgOn");
        $(this).removeClass("bgOff");
    });

    if ( $('#consultForm').length ) {
        $('#consultForm').submit(function(e) {
            if ( $('#consult_Part1_title').val() == '' ) {
                e.preventDefault();
                dialogIt('Please enter your title','Missing Details!');
                return false;
            }
            if ( $('#consult_Part1_firstname').val() == '' ) {
                e.preventDefault();
                dialogIt('Please enter your name','Missing Details!');
                return false;
            }
            if ( $('#consult_Part1_surname').val() == '' ) {
                e.preventDefault();
                dialogIt('Please enter your surname','Missing Details!');
                return false;
            }
            if ( $('#consult_Part1_email').val() == '' || !IsValidEmail( $('#consult_Part1_email').val() ) ) {
                e.preventDefault();
                dialogIt('Please enter a valid email address','Missing Details!');
                return false;
            }
            if ( $('#consult_Part2_about').val() == '' ) {
                e.preventDefault();
                dialogIt('Please tell us about your book','Missing Details!');
                return false;
            }
            if ( $('#consult_Part1_phone').val() == '' && $('#consult_Part1_phone').val() != 3 ) {
                e.preventDefault();
                dialogIt('You must enter a pone number for us to contact you','Missing Details!');
                return false;
            }
            $('#contactForm').submit();
        });
    }

    if ( $('#quoteForm').length ) {
        $('#quoteForm').submit(function(e) {
            if ( $('#quoteForm_firstname').val() == '' ) {
                e.preventDefault();
                dialogIt('Please enter your name','Missing Details!');
                return false;
            }
            if ( $('#quoteForm_email').val() == '' || !isValidEmail( $('#quoteForm_email').val() ) ) {
                e.preventDefault();
                dialogIt('Please enter a valid email address','Missing Details!');
                return false;
            }
            if ( $('#quoteForm_wordcount').val() == '' && ($('#quoteForm_proofread_lab').hasClass('checked') || $('#quoteForm_layout_lab').hasClass('checked')) ) {
                e.preventDefault();
                dialogIt('Please enter your books wordcount','Missing Details!');
                return false;
            }
            $('#quoteForm').submit();
        });
    }

    if ( $('#guideForm').length ) {
        $('#guideForm').submit(function(e) {
            if ( $('#guideForm_firstname').val() == '' ) {
                e.preventDefault();
                dialogIt('Please enter your name','Missing Details!');
                return false;
            }
            if ( $('#guideForm_surname').val() == '' ) {
                e.preventDefault();
                dialogIt('Please enter your surname','Missing Details!');
                return false;
            }
            if ( $('#guideForm_email').val() == '' || !IsValidEmail( $('#guideForm_email').val() ) ) {
                e.preventDefault();
                dialogIt('Please enter a valid email address','Missing Details!');
                return false;
            }
            $('#guideForm').submit();
        });
    }

    if ( $('#contactForm').length ) {
        $('#contactForm').submit(function(e) {
            if ( $('#contact_firstname').val() == '' ) {
                e.preventDefault();
                dialogIt('Please enter your name','Missing Details!');
                return false;
            }
            if ( $('#contact_surname').val() == '' ) {
                e.preventDefault();
                dialogIt('Please enter your surname','Missing Details!');
                return false;
            }
            if ( $('#contact_email').val() == '' || !IsValidEmail( $('#contact_email').val() ) ) {
                e.preventDefault();
                dialogIt('Please enter a valid email address','Missing Details!');
                return false;
            }
            $('#contactForm').submit();
        });
    }


    $('#ship1').change(function() {
        $('#ship2').val($('#ship1').val());
    });


    function dialogIt(msg, ttl, closeFunction, beforeCloseFunction) {
        var aDialog = $('<div class="alertDialog"></div>')
        .html('<div class="dialogBox"><h1>'+ttl+'</h1><p>'+msg+'</p></div>').dialog({
            title: ttl,
            modal: true,
            resizable: false,
            minHeight: 50,
            buttons: {
                "OK": function() {
                    aDialog.dialog("close");
                }
            },
            close: function() {
                for ( var x=0; x< dialogs.count; x++ ) {
                    if ( dialogs[x] == aDialog ) {
                        dialogs[x] = null;
                    }
                }
            }
        });

        if ( !(!closeFunction) ) {
            $(aDialog).bind('dialogclose', closeFunction );
        }
        if ( !(!beforeCloseFunction) ) {
            $(aDialog).bind('dialogbeforeclose', beforeCloseFunction );
        }

        dialogs.push(aDialog);
    }

    if (!usingBadIE || 1 +1 == 2) {
        
           
        var values = {};
        var total = parseFloat($('#quoteTotal').text());
        var wordcount = parseInt($('#quoteForm_wordcount').val());
    
        $('#quoteForm input').each(function(index, field){
            if ($(this).attr('checked')) {
                $(this).parent().find('label').addClass('checked');
            }
            var fieldName = $(field).attr('id').replace('quoteForm_', '');
            if (fieldName.indexOf('_') > 0) {
                var fieldNames = fieldName.split('_');
                fieldName = fieldNames[1];
            }
            if (fieldName == 'paperback' || fieldName == 'hardback') {
                if (fieldName == 'paperback' && $(field).attr('checked')) {
                    values['format'] = 'paperback';
                } else if (fieldName == 'hardback' && $(field).attr('checked')) {
                    values['format'] = 'hardback';
                }
                fieldName = 'format';
            } else if (fieldName == 'mono' || fieldName == 'colour') {
                if (fieldName == 'mono' && $(field).attr('checked')) {
                    values['basics'] = 'mono';                
                } else if (fieldName == 'colour' && $(field).attr('checked')) {
                    values['basics'] = 'colour';
                }
                fieldName = 'basics';
            } else if (fieldName == 'bespoke' || fieldName == 'standard') {
                if (fieldName == 'bespoke' && $(field).attr('checked')) {
                    values['bespokecover'] = $(field).val();
                    if (values['standardcover'].length) {
                        values['standardcover'] = null;
                    }
                } else if (fieldName == 'standard' && $(field).attr('checked')) {
                    values['standardcover'] = $(field).val();
                    if (values['bespokecover'].length) {
                        values['bespokecover'] = null;
                    }
                }
                fieldName = 'cover';
            } else if (fieldName == 'promo') {
                values[fieldName] = $(field).val();
            }
        
            if (fieldName != 'title' && fieldName != 'email' && fieldName != 'phone' && fieldName != '_csrf_token' && fieldName != '') {
                if (fieldName == 'wordcount') {
                    values[fieldName] = parseInt($(field).val());
                } else if (fieldName == 'mono' || fieldName == 'colour') {
                    values['basics'] = fieldName;
                } else if (fieldName == 'paperback' || fieldName == 'hardback') {
                    values['format'] = fieldName;
                } else if (fieldName == 'promo') {
                    values[fieldName] = $(field).val();
                } else if (fieldName == 'additionalebook' || fieldName == 'additionalebookstandard' || fieldName == 'additionalebookpremium') {
                    if ($(field).parent().find('label').hasClass('checked')) {
                        values['additionalebook'] = fieldName;
                    } else {
                        values['additionalebook'] = null;
                    }
                } else {
                    if ($(field).attr('checked') && fieldName != 'basics' && fieldName != 'format' && fieldName != 'cover') {
                        values[fieldName] = $(field).val();
                    } else if (!$(field).attr('checked') && fieldName != 'basics' && fieldName != 'format' && fieldName != 'cover') {
                        values[fieldName] = null;
                    }
                }
            }
        });
        
        $('#quoteForm input').live('change', function(){
            var field = this;
            var fieldName = $(this).attr('id').replace('quoteForm_', '');
            if (fieldName.indexOf('_') > 0) {
                var fieldNames = fieldName.split('_');
                fieldName = fieldNames[1];
            }
            var otherField = '';
        
            if (fieldName == 'paperback' || fieldName == 'hardback' || fieldName == 'mono' || fieldName == 'colour') {
                $(this).parent().parent().parent().find('.error_list').remove();
                $(this).parent().parent().parent().find('.checked').removeClass('checked');
                if (fieldName == 'mono' || fieldName == 'colour') {
                    $(this).parent().parent().parent().parent().find('.checked').removeClass('checked');
                }
                $(this).parent().find('label').toggleClass('checked');
            } else if (fieldName == 'bespokecover' || fieldName == 'standardcover') {
                otherField = 'bespokecover';
                if (fieldName == 'bespokecover') {
                    otherField = 'standardcover';
                }
                $(this).parent().parent().parent().find('.error_list').remove();
                if (values[otherField]) {
                    values[otherField] = null;
                }
            }
        
            if (fieldName != 'title' && fieldName != 'firstname' && fieldName != 'surname' && fieldName != 'email' && fieldName != 'phone' && fieldName != '_csrf_token' && fieldName != '') {
                $(this).parent().find('.error_list').remove();
                if (fieldName == 'wordcount') {
                    values[fieldName] = parseInt($(this).val());
                } else if (fieldName == 'mono' || fieldName == 'colour') {
                    values['basics'] = fieldName;
                } else if (fieldName == 'paperback' || fieldName == 'hardback') {
                    values['format'] = fieldName;
                } else if (fieldName == 'promo') {
                    values[fieldName] = $(this).val();
                } else if (fieldName == 'additionalebook' || fieldName == 'additionalebookstandard' || fieldName == 'additionalebookpremium') {
                    if ($(field).parent().find('label').hasClass('checked')) {
                        values['additionalebook'] = fieldName;
                    } else {
                        values['additionalebook'] = null;
                    }
                } else {
                    if ($(this).attr('checked')) {
                        values[fieldName] = $(field).val();
                    } else {
                        values[fieldName] = null;
                    }
                }
                $.post(devEnv + '/calculate-quote', {
                    'values' : values
                }, function(data) {
                    var dataTotal = parseFloat(data['total']);
                    $('#quoteTotal').text(dataTotal.toFixed(2));
                    //                    $('.quoteTotal').removeClass('hidden');
                
                    if ($('#quoteForm_promo').val()) {
                        var promoCode = $('#quoteForm_promo').val();
                        var promoValues = {};
                        promoValues['code'] = promoCode;
                        promoValues['total'] = dataTotal;
            
                        $.post(devEnv + '/checking-promo-code', {
                            'values' : promoValues
                        }, function(promoData,status) {
                            $('.quoteDetails .promo').remove();
                            if (promoData['valid'] == true) {
                                $('.quoteDetails').append('<tr class="promo"> <td>Promo Code ('+promoCode+') <span class="quantity">Discount: '+promoData['percent']+'%</span> </td> <td class="price"> -&pound;'+data['discount'].toFixed(2)+'</td> </tr>');
                            }
                        });
                    }
                });
            }
                
        });
    
        $('#royaltyForm input').each(function(index, field){
            var fieldName = $(field).attr('id').replace('royaltyForm_', '');
            if (fieldName.indexOf('_') > 0) {
                var fieldNames = fieldName.split('_');
                fieldName = fieldNames[1];
            }
            if (fieldName == 'paperback' || fieldName == 'hardback') {
                if ($(field).attr('checked')) {
                    values['format'] = $(field).val();
                }
                fieldName = 'format';
            } else if (fieldName == 'standard' || fieldName == 'demy' || fieldName == 'royal') {
                if ($(field).attr('checked')) {
                    values['layout'] = $(field).val();                
                }
                fieldName = 'layout';
            }
        
            if (fieldName == 'wordcount' || fieldName == 'pages') {
                values[fieldName] = parseInt($(field).val());
            } else if (fieldName == 'rrp') {
                values[fieldName] = parseFloat($(this).val());
            } else {
                if ($(field).attr('checked') && fieldName != 'basics' && fieldName != 'format' && fieldName != 'cover') {
                    values[fieldName] = $(field).val();
                } else if (!$(field).attr('checked') && fieldName != 'layout' && fieldName != 'format') {
                    values[fieldName] = null;
                }
            }
                
        });
    
        $('#royaltyForm input').live('change', function() {
            var fieldName = $(this).attr('id').replace('royaltyForm_', '');
            if (fieldName.indexOf('_') > 0) {
                var fieldNames = fieldName.split('_');
                fieldName = fieldNames[1];
            }
            if (fieldName == 'paperback' || fieldName == 'hardback') {
                fieldName = 'format';
                $(this).parent().parent().parent().find('.error_list').remove();
                $(this).parent().parent().parent().find('.checked').removeClass('checked');
                $(this).parent().find('label').addClass('checked');
            } else if (fieldName == 'standard' || fieldName == 'demy' || fieldName == 'royal') {
                fieldName = 'layout';
                $(this).parent().parent().parent().find('.error_list').remove();
                $(this).parent().parent().parent().find('.checked').removeClass('checked');
                $(this).parent().find('label').addClass('checked');
            }
        
            $(this).parent().find('.error_list').remove();
            if (fieldName == 'wordcount' || fieldName == 'pages') {
                if (fieldName == 'wordcount') {
                    $('#royaltyForm_pages').val('');
                    values['pages'] = 0;
                } else {
                    $('#royaltyForm_wordcount').val('');
                    values['wordcount'] = 0;
                }
                values[fieldName] = parseInt(parseFloat($(this).val()));
            } else if (fieldName == 'rrp') {
                values[fieldName] = parseFloat($(this).val());
            } else {
                if ($(this).attr('checked')) {
                    values[fieldName] = $(this).val();
                } else {
                    values[fieldName] = null;
                }
            }
            $.post(devEnv + '/calculate-royalty', {
                'values' : values
            }, function(data,status) {
                $('#royaltyTotal').text(data['royalty']);
                $('.royaltyTotal').removeClass('hidden');
                if (data['royalty'] < 0) {
                    $('#increaseRRP').removeClass('hidden');
                } else {
                    $('#increaseRRP').addClass('hidden');
                }
            });
        
        });
    }
    
    function updateQuote(field, total, prices) {
        total = parseFloat(total);
        var fieldName = $(field).attr('id').replace('quoteForm_', '');
        if (fieldName.indexOf('_') > 0) {
            var fieldNames = fieldName.split('_');
            fieldName = fieldNames[1];
        }
        
        if (fieldName == 'wordcount') {
            var oldWordcount = wordcount;
            wordcount = parseInt($(field).val());
            
            if ($('#quoteForm_proofread').attr('checked')) {
                total = total - parseFloat(prices['proofread']*(oldWordcount/1000));
                total = total + parseFloat(prices['proofread']*(wordcount/1000));
            }
            if ($('#quoteForm_layout').attr('checked')) {
                total = total - parseFloat(prices['layout']*(oldWordcount/1000));
                total = total + parseFloat(prices['layout']*(wordcount/1000));
            }
            
            if (wordcount == 0) {
                $('#quoteForm_proofread').removeAttr('checked');
                $('#quoteForm_layout').removeAttr('checked');                
            }
            
        } else if (fieldName == 'proofread' || fieldName == 'layout') {
            if (!wordcount) {
                alert('Please tell us how many words are in your book.');
                $(field).removeAttr('checked');
            } else {
                if ($(field).attr('checked')) {
                    total = total + parseFloat(prices[fieldName]*(wordcount/1000));
                    $(field).attr('checked', true);
                } else {
                    total = total - parseFloat(prices[fieldName]*(wordcount/1000));
                    $(field).removeAttr('checked');
                }
            }
        } else {
            if ($(field).attr('checked')) {
                total = total + parseFloat(prices[fieldName]);
                $(field).attr('checked', true);
            } else {
                total = total - parseFloat(prices[fieldName]); 
                $(field).removeAttr('checked');   
            }
        }
        if (total <= 0) {
            total = 0;
        }
        
        return parseFloat(total).toFixed(2);
    }
    
    

});
