/* Begin Finance Calc Payment */
var d = 0;
var f = 523;
var r = 0.159;

function CalcPayment(p, m) {
    var n = p * (1 - d) + f;
    if (n < 0) { return 0; }
    else
    { return ((n * (r / 12)) / (1 - Math.pow(1 + r / 12, -m))) * 12 / 52; }
}

function RecalcFinAmt(amount, termId, resultId, onroadcosts) {

    var finTermSelect = document.getElementById(termId);

    if (finTermSelect != null) {

        $.ajax({
            cache: false,
            type: 'POST',
            contentType: "application/json",
            beforeSend: function () { },
            complete: function () { },
            url: '../../vehicleservice.asmx/CalculateFinance',
            data: "{'inputAmount':'" + amount + "','inputTerm':'" + finTermSelect.value + "','inputOnRoadCosts':'" + onroadcosts + "'}",
            success: function (data) {

                var financeLabel = $('[id$=' + resultId + ']');
                financeLabel.empty();

                if (data.d[0] != "") {
                    var amount = JSON.parse(data.d[0]);
                    financeLabel.append(amount);
                }
            },
            dataType: "json",
            error: function (msg) {
                //alert(msg.statusText);
            }
        });
    }
}

function RecalcFinAmtDisplay(amount, termId, resultId, onroadcosts) {
    RecalcFinAmtDisplay(amount, termId, '', resultId, onroadcosts);
}

function RecalcFinAmtDisplay(amount, termId, frequency, resultId, onroadcosts) {
    
    var finTermSelect = document.getElementById(termId);

    if (finTermSelect != null) {

        $.ajax({
            cache: false,
            type: 'POST',
            contentType: "application/json",
            beforeSend: function () { },
            complete: function () { },
            url: '../../vehicleservice.asmx/CalculateFinanceDisplay',
            data: "{'inputAmount':'" + amount + "','inputTerm':'" + finTermSelect.value + "','inputFrequency':'" + frequency + "','inputOnRoadCosts':'" + onroadcosts + "'}",
            success: function (data) {

                var financeLabel = $('[id$=' + resultId + ']');
                financeLabel.empty();

                if (data.d[0] != "") {
                    var amount = JSON.parse(data.d[0]);
                    financeLabel.append(amount);
                }
            },
            dataType: "json",
            error: function (msg) {
                
                alert(msg.statusText);
            }
        });
    }
}
/* End Finance Calc Payment */

/* Begin Document Ready*/
var screenSize;


var Motorcentral = function () {
    var screenSize;
}

// Create the motorcentral object
var mc = new Motorcentral();



$(document).ready(function () {
    
    // Get the screen size
    mc.screenSize = getResponsiveScreenDisplay();
    
    screenSize = getResponsiveScreenDisplay();

    // Select all the abide validation submit buttons
    var btns = $('[data-mcsubmit]').each(function (e) {
        
        // Loop the submission buttons
        //$("[id$=btnSend]").on("click", function (e) {
        $(this).on("click", function (e) {
            // Stop the default event bubbling
            e.stopPropagation();
            e.preventDefault();

            // Run the abide validation
            //Foundation.libs.abide.validate($('#frmDefault').find('input, select, textarea'), { type: '' })

            // Check if the button has a specific panel id to validate supplied
            var validationPanelId = $(this).data('mcsubmit');

            // No panel id found
            if (validationPanelId == "") {
                // Search the entire page for controls to validate
                validationPanelId = "frmDefault"
            }
            
            // Validate all required fields for the given id
            Foundation.libs.abide.validate($('#' + validationPanelId).find('input, select, textarea'), { type: '' })

            // Setup the event trigger
            $.event.trigger({
                type: "mcAbideValidationSubmit",
                targetButton: e.target
            });

            return false;
        });

    });
});
/* End Document Ready*/

$(window).smartresize(function () {
    
    var tempScreenSize = getResponsiveScreenDisplay();
    mc.screenSize = tempScreenSize;
    $.event.trigger({
        type: "screenResized",
        screenSize: mc.screenSize
    });
    //if (mc.screenSize != tempScreenSize) {
    //    mc.screenSize = tempScreenSize;

    //    $.event.trigger({
    //        type: "screenResized",
    //        screenSize: mc.screenSize
    //    });
    //}
});


/* Begin MC Abide Validation Handler*/

// Setup the mc abide validation handler
$(document).on("mcAbideValidationSubmit", validationSubmitHandler);

function validationSubmitHandler(e) {
    // Check if the abide validation is valid
    var invalidControls = $(this).find('[data-invalid]:enabled');
    var isValid = invalidControls.length == 0;
    if (isValid) {
        var btn = $(e.targetButton);

        // Disable the button on click
        btn.attr('disabled', 'disabled');
        // Do the original button's function
        

        window.location = e.targetButton.href;

    } else {

        // Only scroll to nearest validation error if not a popup form
        if ($(e.targetButton).closest('[data-reveal]').length == 0) {
            $('body').scrollTo('#' + invalidControls.first().attr('id'), 200, { offset: -70 });
        } 
    }
}
/* End MC Abide Validation Handler*/

var google_map_keys = [];
var google_map_maps = [];

/* Begin Google Map initiator
//https://developers.google.com/maps/documentation/javascript/styling#stylers
<![CDATA[ */
function setMapAddress(address, controlId, pinImageUrl, color, scrollWheel, disableDefaultUi, pinTitle, zoomLevel, isDraggable) {
    var geocoder = new google.maps.Geocoder();

    var mapColor = null;
    if (color == "Black") {
        mapColor = [
       {
           featureType: "all",
           stylers: [
               { saturation: -100 },
               { lightness: -40 },
               { hue: '#000000' }
           ]
       }];
    }


    geocoder.geocode({ address: address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latlng = results[0].geometry.location;
            var options = {
                zoom: zoomLevel,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                styles: mapColor,
                scrollwheel: scrollWheel,
                disableDefaultUI: disableDefaultUi,
                draggable: isDraggable

            };

            var mymap = new google.maps.Map(document.getElementById(controlId), options);

            //Store this map in js variable if not already stored (this is required for map refresh on contact page)
            if (google_map_keys.indexOf(controlId) < 0) {
                google_map_keys.push(controlId);
                google_map_maps.push(mymap);
            }

            var marker = new google.maps.Marker({
                map: mymap,
                position: results[0].geometry.location,
                icon: pinImageUrl,
                title: pinTitle
            });

        }
    });
}
/* ]]>
End Google Map initiator */

/**
Get url query string parameter
**/
function getParameterByName(name) {
    return getParameterFromUrl(name, window.location.search);
}

function getParameterFromUrl(name, url) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

/* Begin foundation block-grid-x center */
//var Main;

//Main = (function () {
//    function Main() {
//        this.pickHangers();
//    }

//    Main.prototype.pickHangers = function () {
//        return $('ul[class*=small-block-grid-').each((function (_this) {
//            return function (i, el) {

//                var $liLastRow, $lis, $ul, length, multiplier, re, remainder, rowCount, str, width;
//                $ul = $(el);
//                $lis = $ul.find('li');
//                str = $ul.attr('class');
//                re = /\w+\-block\-grid\-(\d+)\b/i;
//                rowCount = str.match(re)[1];
//                length = $lis.length;
//                remainder = length % rowCount;
//                if (remainder > 0) {
//                    $liLastRow = $($lis.slice(-remainder));
//                    multiplier = rowCount - remainder;
//                    width = _this.getWidthPercentage($lis, multiplier);
//                    return $liLastRow.first().css({
//                        "margin-left": "" + width + "%"
//                    });
//                }
//            };
//        })(this));
//    };

//    Main.prototype.getWidthPercentage = function ($el, n) {
//        var parentWidth, percent, width;
//        width = $el.outerWidth() * n;
//        parentWidth = $el.parent().outerWidth();
//        return percent = 100 * (width / parentWidth) / 2;
//    };

//    return Main;

//})();

//$(function () {
//    var main;
//    return main = new Main();
//});

/* End foundation block-grid-x center */


function getResponsiveScreenDisplay() {

    // Available responses are determined via the foundation-helper.css
    // These are: sm/md/lg/xl/xxl
    return window.getComputedStyle($('#responsiveTell')[0], ':after').getPropertyValue('content').replace(/"/g, '');
}

/* Show common popup - foundation reveal */
function ShowCommonPopup(title, message) {
    $(function () {
        var popup = $('#dlg-common');
        popup.find('.common-modal-title').empty().append(title);
        popup.find('.common-modal-content').empty().append(message);
        popup.foundation('reveal', 'open');

    });
};

/*Add toggledisabled to jquery object*/
(function ($) {
    $.fn.toggleDisabled = function () {
        return this.each(function () {
            this.disabled = !this.disabled;
            
        });
    };
})(jQuery);

(function ($) {
    $.fn.mcEnable = function () {
        return this.each(function () {
            this.disabled = false;            
        });
    };
})(jQuery);
(function ($) {
    $.fn.mcDisable = function () {
        return this.each(function () {
            this.disabled = true;            
        });
    };
})(jQuery);

/* Resets all the controls within a given container id */
function ResetControls(elementID) {

    var container = $('[id$=' + elementID + ']').children();
    container.find('input,textarea').each(function () {
        $(this).val('');
    });
    container.find('select').each(function () {
        $(this)[0].selectedIndex = 0;
    });    
    return false;
}


/* Code for slide down navigation and search for medium */

var scr_EnableToggleNav = false;
var scr_OldSize;
var scr_LgWidth = 1009;
var NavClass = 'nav.navigation > ul';
function InitToggleNav() {
    scr_EnableToggleNav = true;
    scr_OldSize = $(window).width();
    if (scr_EnableToggleNav) {
        if (scr_OldSize > scr_LgWidth) {
            $(NavClass).show();
        }
        else {
            $(NavClass).hide();
        }
    }
}


function toggleNav() {
    if (scr_EnableToggleNav) {
        var CurrentSize = $(window).width();
        if (CurrentSize >= scr_LgWidth) {
            $(NavClass).show();
            return;
        }
        var nav = $(NavClass);
        if (nav.hasClass('nav-show')) {
            nav.slideUp();
            nav.removeClass('nav-show');
        }
        else {
            nav.slideDown();
            nav.addClass('nav-show');
            var search = $('.master.main-search');
            if (search.hasClass('search-show')) {
                search.slideUp();
                search.removeClass('search-show');
            }
        }
    }
}

function toggleSearch() {
    var search = $('.master.main-search');
    if (search.hasClass('search-show')) {
        search.slideUp();
        search.removeClass('search-show');
    }
    else {
        search.slideDown();
        search.addClass('search-show');
        var nav = $(NavClass);
        if (nav.hasClass('nav-show')) {
            nav.slideUp();
            nav.removeClass('nav-show');
        }
    }
}

$(window).resize(function () {
    var CurrentSize = $(window).width();
    if (scr_EnableToggleNav) {
        if (CurrentSize >= scr_LgWidth && scr_OldSize < scr_LgWidth) {
            $('nav.navigation > ul').show();
        }

        if (CurrentSize < scr_LgWidth && scr_OldSize >= scr_LgWidth) {
            $('nav.navigation > ul').hide();
            $('nav.navigation > ul').removeClass('nav-show');
        }
    }
    scr_OldSize = CurrentSize;
})


/* end toggle nav and search code*/
