var slider = new Object;
var animateSlider;
var animateSliderSpeed = 5000;
var movementSpeed = 'slow';  

slider = {
    position: 0,
    maxLeft: 0,
    locked: false,
    eMargin: 0,
    eWidth: 0,
    visible: 3,
    commence: function(){
        this.eMargin = parseInt($('.element').css('margin-right').replace('px', ''));
        this.eWidth = $('.element').width(); 
        
        this.left();
        this.right();
        this.countUp(); 
        animateSlider = setTimeout('slider.automate()', animateSliderSpeed);
    },
    countUp: function(){
        this.maxLeft = ($('.element').length-1);
        $('.slider .left').css('background-image', 'url(' + theUrl + 'images/arrow-left-dead.png)');
    },
    left: function(){
        $('.slider .left').click(
            function(){ 
                if(-slider.position != (slider.maxLeft-slider.visible)){
                    $('.slider .right').css('background-image', 'url(' + theUrl + 'images/arrow-right.png)');
                    $('.slider .right').hover(
                        function(){
                            $(this).css('background-image', 'url(' + theUrl + 'images/arrow-right-over.png)');
                        },
                        function(){
                            $(this).css('background-image', 'url(' + theUrl + 'images/arrow-right.png)');
                        }
                    );        
                }  
                if(-slider.position == 1){                                                                           
                    $(this).unbind('mouseenter mouseleave');
                    $(this).css('background-image', 'url(' + theUrl + 'images/arrow-left-dead.png)');
                }    
                if(-slider.position != 0 && !slider.locked){  
                    slider.locked = true;
                    slider.position ++;
                    $('.holder').animate({
                        left: slider.position * (slider.eMargin + slider.eWidth)
                    }, movementSpeed, 
                        function(){
                            slider.locked = false; 
                        }
                    );
                }
            }
        );
    },  
    right: function(){
        $('.slider .right').click(
            function(){ 
                if(slider.position == 1){                 
                    $('.slider .right').css('background-image', 'url(' + theUrl + 'images/arrow-right.png)');
                    $('.slider .right').hover(
                        function(){
                            $(this).css('background-image', 'url(' + theUrl + 'images/arrow-right-over.png)');
                        },
                        function(){
                            $(this).css('background-image', 'url(' + theUrl + 'images/arrow-right.png)');
                        }
                    );                
                }
                if(-slider.position != 1){                
                    $('.slider .left').css('background-image', 'url(' + theUrl + 'images/arrow-left.png)');
                    $('.slider .left').hover(
                        function(){
                            $(this).css('background-image', 'url(' + theUrl + 'images/arrow-left-over.png)');
                        },
                        function(){
                            $(this).css('background-image', 'url(' + theUrl + 'images/arrow-left.png)');
                        }
                    );                                                    
                }
                if(-slider.position == (slider.maxLeft-slider.visible) && !slider.locked){                                                                     
                    $(this).unbind('mouseenter mouseleave');
                    $(this).css('background-image', 'url(' + theUrl + 'images/arrow-right-dead.png)');
                }               
                if(-slider.position != (slider.maxLeft - (slider.visible - 1)) && !slider.locked){
                    slider.locked = true;
                    slider.position --; 
                    $('.holder').animate({
                        left: slider.position * (slider.eMargin + slider.eWidth)
                    }, movementSpeed, 
                        function(){
                            slider.locked = false;                                
                        }
                    );
                }
            }
        );
    },
    automate: function(){  
        if(-slider.position == (slider.maxLeft - (slider.visible - 1))){    
            slider.position = 1;        
            $('.slider .right').trigger('click');    
                    $('.slider .left').unbind('mouseenter mouseleave');
                    $('.slider .left').css('background-image', 'url(' + theUrl + 'images/arrow-left-dead.png)');  
        }else{                        
            $('.slider .right').trigger('click');
        } 
        animateSlider = setTimeout('slider.automate()', animateSliderSpeed);     
    }  
} 


function faq(siteUrl){          
    location = siteUrl + '#' + document.mycombo.faqList.options[document.mycombo.faqList.selectedIndex].value; 
}     

function validateFields(formName){
    var validated = true;
    var includeBookingDateText = true;
    var theString = "The following fields have not been completed: <br />";
    var errorArray = [];
    var searchLength = $('form[name=' + formName + '] input').length-1;
    $('form[name=' + formName + '] input').each(
        function(index){
            if($(this).attr('id') != 'priceField' && $(this).attr('id') != 'theRoute' && $(this).attr('id') != 'carAmount'){  
                $(this).css('color', '#7F92A6');
                if($(this).val() == ""){
                    errorArray.push($(this).attr('alias'));
                    $(this).css('background-color', '#c4504b');
                    $(this).css('color', '#ffffff');  
                    validated = false;
                }else{
                    $(this).css('background-color', '#ffffff');
                    if(typeof(availabilityCheck) === "undefined"){
                        availabilityCheck = true;
                    }
                    
                    if(formName == "enquiryForm"){
                        availabilityCheck = true;
                    }
                    
                    if (validated && index == searchLength && availabilityCheck){
                        var theRoute = "";          
                                         
                        //theRoute += "<table border = '0'>";    
                        theRoute += "<b>Depart from:</b> " + departFrom + "<br />";   
                        theRoute += "<b>Ceremony:</b> " + ceremony + "<br />";
                        theRoute += "<b>Reception:</b> " + reception + "<br />";
                            
                        //theRoute += "</table>";
                        $('#theRoute').val(theRoute); 
                        
                        if(formName == "enquiryForm"){
                            includeBookingDateText = true;
                        } 
                        
                        if(includeBookingDateText){
                            
                            if(formName != "enquiryForm"){
                                if($('#priceError').html() != "" || $('#group').html() == "" ||  $('#zone').html() == "" ||  $('#price').html() == ""){
                                    theString += '<br /> <span style = "color:#C4504B;">You also need to check your price</span>.';
                                    validated = false;
                                    $('#errorLog').html(theString);
                                }else{
                                    document.forms[formName].submit(); 
                                }
                            }else{
                                document.forms[formName].submit(); 
                            }
                        }  
                    }
                } 
            }
        }
    );
    for(a in errorArray){           
        if(errorArray[a] == "Booking Date"){
            includeBookingDateText = false; 
        }
        if(a == errorArray.length - 2){theString += '<span style = "color:#C4504B;">' + errorArray[a] + '</span> and <br />';} 
        else if(a == errorArray.length - 1){
            theString += '<span style = "color:#C4504B;">' + errorArray[a] + '</span>.';
        }else{theString += '<span style = "color:#C4504B;">' + errorArray[a] + '</span>, <br />';}
    }
    
    if(theString != "The following fields have not been completed: <br />"){$('#errorLog').html(theString);}else{
        $('#errorLog').html("");
    }
}
      
function removeField(obj){        
    var countRows = $('.aLocationRow').length;
    if(countRows != 1){
        $(obj).parent().parent().remove();
        
        $('.locationNumber').each(
            function(index){                     
                $(this).html(index + 1);
            }
        );
            
        $('.location').each(
            function(index){                     
                $(this).attr('name', 'location' + (index + 1));
            }
        );        
        
        $('.itinerary').each(
            function(index){                     
                $(this).attr('name', 'itinerary' + (index + 1));
            }
        ); 
    }   
}


//GOOGLE MAPS FUNCTIONS
  
var startLocation; 
var distances = new Array;
var arrayOfVenues = new Array;
var geocoder;
var map;
var latLngObj;
var theDistance;
var counter = 0;
var metreToMile = 0.000621371; 
 
var departFrom; 
var ceremony; 
var reception;

function initialise_google_maps(){     
    geocoder = new google.maps.Geocoder();
    startLocation = new google.maps.LatLng(51.214125,-0.795704);
     
    var myOptions = {
        zoom: 4,
        center: startLocation,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);  
}
    
function findMax( array ){
    return Math.max.apply(Math, array);
};  

function roundNumber(num, dec) {
    var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    return result;
}   

function getLatLng(address, callback){
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            callback(results[0].geometry.location);
        } else {
            $('#priceError').html("Please make sure your venue's<br />post code is correctly entered..."); 
            $('.itinerary').css('background-color', '#c4504b');
            $('.itinerary').css('color', '#ffffff');  
        }
    });
}
 
function calculate_distances(){     
    departFrom = $('input[name="departFrom"]').val(); 
    ceremony = $('input[name="ceremony"]').val(); 
    reception = $('input[name="reception"]').val();
    var bookingDate = $('.datePicker').val();
    
    if(bookingDate){
        arrayOfVenues = [departFrom, ceremony, reception];   
              
        getLatLng(arrayOfVenues[0], function(obj0){
            distances.push(parseFloat(google.maps.geometry.spherical.computeDistanceBetween(startLocation, obj0)) * metreToMile);
            
            getLatLng(arrayOfVenues[1], function(obj1){
                distances.push(parseFloat(google.maps.geometry.spherical.computeDistanceBetween(startLocation, obj1)) * metreToMile);  
                
                getLatLng(arrayOfVenues[2], function(obj2){
                    distances.push(parseFloat(google.maps.geometry.spherical.computeDistanceBetween(startLocation, obj2)) * metreToMile);
                    
                    var longestDistance = findMax(distances);        
                    zoneCheck(longestDistance);
                    distances = [];
                });
            });
        });
    }else{
        $('#priceError').html("You have forgotten to choose a date...");  
        $('.datePicker').css('background-color', '#c4504b');
        $('.datePicker').css('color', '#ffffff');  
    } 
    
    function zoneCheck(distance){ 
        if (distance <= 5){
            zoneResponse(1);    
        }             
        if (distance <= 10 && distance > 5){
            zoneResponse(2);    
        } 
        if (distance <= 15 && distance > 10){
            zoneResponse(3);    
        } 
        if (distance <= 20 && distance > 15){
            zoneResponse(4);    
        } 
        if (distance <= 25 && distance > 20){
            zoneResponse(5);    
        } 
        if (distance > 25){
            zoneResponse(false);    
        }else{
            if($('#priceError').html() == "Unfortunately, we do not cover your area."){$('#priceError').html("")}
        }
    }     
 
    function zoneResponse(response){ 
        if(response){
            checkPrice(response);
        }else{                      
            $('#priceGrid').hide();
            $('#priceField').val(""); 
            $('#priceError').html("Unfortunately, we do not cover your area.");
        }
    }
     
    function checkPrice(zone){
        if(zone){
            var currentDate = $('input[name="bookingDate"]').val();
            currentDate = currentDate.split('/');
            currentYear = currentDate[2];    
            $('#priceGrid').hide(); 
            $('#loading').html('<img src = "' + theUrl + 'images/ajax-loader2.gif" />');
            doAjax(zone);
        }else{ 
            $('#priceGrid').hide();
            $('#priceField').val(""); 
            $('#priceError').html('Please check your locations'); 
        }             
    }
    
    function doAjax(zone){
        $.ajax({
            url: siteUrl + '/pricing/' + currentYear + '?ajax=yes',
            context: document.body,
            async: false,
            success: function(data){   
                $('#priceError, #loading').html('');   
                $('#checkPrice').html(data);   
                var carGroup = $('#carGroup').html();
                var thePrice = $('#' + carGroup + zone).html();          
                $('#group').html(carGroup.toUpperCase());                    
                $('#zone').html(zone); 
                thePrice = thePrice.split('.');   
                $('#price').html('<p>' + thePrice[0] + '<span style = "font-size:20px;">.' + thePrice[1] + '</span></p>');  
                $('#priceField').val(thePrice[0] + '.' + thePrice[1]);
                $('#priceGrid').fadeIn();
                $('#priceError, #loading').html(''); 
            },
            error: function(a,b,c){    
                $('#priceGrid').hide();
                $('#priceField').val(""); 
                if(currentDate == ""){           
                    $('#priceError, #loading').html('You need to enter a booking date');
                }else{                           
                    $('#priceError, #loading').html('Unfortunately you need to book closer to the date'); 
                }            
            }
        });
    }
    
    function exitFunction(){
        halt = true;
        $('#priceGrid').hide();
        $('#priceField').val("");       
        $('#priceError, #loading').html('Please check your locations'); 
    }
        
    function resetCallback(){
        var route = response.routes[0];
        var countMiles = 0;
        var listOfDistances = [];
    } 
}  
  
function loadForm(ele, obj){ 
    $(ele).removeClass('aFormHide');
    $('.aForm').hide();
    $(ele).fadeIn();
    var formPos = $(ele).offset();
    
    window.scroll(0,formPos.top);
    
    if($('#availabilityOutcome').length > 0){   
        $('input[name="bookingDate"]').val("");
        $('#availabilityOutcome').html("");
    }           
}

function fader(){
    setInterval(function(){
            $('.fader').fadeOut('slow', function(){
                $('.fader').fadeIn('slow');
            });
    }, 5000);
}

$(document).ready(
    function(){
        $('.availability').hover(
            function(){
                $(this).css('background-color', '#96243A');
            },
            function(){                                 
                $(this).css('background-color', '#652a36');            
            }
        );                    
        $('.enquiry').hover(
            function(){
                $(this).css('background-color', '#8FB21E');
            },
            function(){                                 
                $(this).css('background-color', '#7b9e0f');            
            }
        );
        
        fader();
                                         
        if($('.niceButton')){
            $('.niceButton').before('<div class = "niceButtonLeft"></div>');
            $('.niceButton').after('<div class = "niceButtonRight"></div>');
            
            //$(this).unbind('mouseenter').unbind('mouseleave')
            
            $('.niceButton').hover(
                function(event){
                    event.preventDefault();
                    $(this).prev().css('background-image', 'url("' + templateUrl + '/images/button-left-booking-o.png")');   
                    $(this).css('background-image', 'url("' + templateUrl + '/images/button-middle-booking-o.jpg")');              
                    $(this).css('color', '#ffffff');     
                    $(this).next().css('background-image', 'url("' + templateUrl + '/images/button-right-booking-o.png")');
                },
                function(event){     
                    event.preventDefault();
                    $(this).prev().css('background-image', 'url("' + templateUrl + '/images/button-left-booking.png")');   
                    $(this).css('background-image', 'url("' + templateUrl + '/images/button-middle-booking.jpg")');        
                    $(this).css('color', '#ffffff');     
                    $(this).next().css('background-image', 'url("' + templateUrl + '/images/button-right-booking.png")');
                }
            );
        }
        
        $('.slider').hover(
            function(){
                clearTimeout(animateSlider);    
            },
            function(){
                animateSlider = setTimeout('slider.automate()', animateSliderSpeed);
            }
        )
        
        if(currentDateDay){
            $('input.datePicker').datepicker({ 
                changeYear: true,
                dateFormat: 'dd/mm/yy',
                minDate: currentDateDay+'/'+currentDateMonth+'/'+currentDateYear
            });
        }
        
        $('input').focus(
            function(){
                $(this).css('background-color', '#ffffff');   
                $(this).css('color', '#7F92A6');
            }
        );  
        
        var imageWidth = 0;
                
        $('.wp-caption').each(
            function(){
                if($('img', this).length > 1){
                    $('img', this).each(
                        function(index){
                            imageWidth += $(this).width();
                            if(index == 0){
                                $(this).css('margin-left', '5px');
                            }else{
                                $(this).css('margin-left', '5px');
                                $(this).css('margin-right', '5px');
                            }
                        }
                    );
                    $(this).width(imageWidth+15);
                    imageWidth = 0;
                }
            }
        );
        
        if($('input[name="bookingDate"]').length > 0){
            if($('input[name="bookingDate"]').val() != ""){  
                checkAvailability($('input[name="bookingDate"]').val(), theTitle);
            }
        }
    }
);
