﻿
if( !tick ) 
{ 
    var tick = function(){};
}

var carReg = "";
var myDirection;
var myBtn;
var address;
var newWin;
function AddClickTaleTag(tag) {
    if (window.ClickTaleTag) {
        ClickTaleTag(tag);
    }
}
function EnableUpdatebutton() {
    $('#UpdateButton').css('display', 'block');
    $('#Loading').css('display', 'none');

}
function DisableUpdatebutton() {
    $('#UpdateButton').css('display', 'none');
    $('#Loading').css('display', 'block');
}

// make a json request to get the map data from the Map action
function GetShowroomDirections() {
    var bloadDirections = GetPostCode(true);
    if (bloadDirections) {
        loadDirections($('#cachedpostcode').val(), address);
    }
    return false;

}


function setUpAddressAndInitialise(mapData) {
    address = mapData.Locations[0].PostCode;
    initialise(mapData);
}

function doLiveChat(vrm) {
    //Has the cachedpostcode got a value - if not show the postcode dialog
    var mydata = '';
    myDirection = null;
    if (vrm != null && vrm != '') {
        carReg = vrm;
    }
    if ($('#cachedpostcode').val() == null || $('#cachedpostcode').val() == '') {
        $('#dialog-form').dialog('open');
    } else {
        var url = window.location.protocol + "//" + window.location.host + '/home/livechat/?postcode=' + $('#cachedpostcode').val();
        newWin = popupLiveChat();
        $.post(url, function(data) {

            $("#dialog-form").dialog('close');
            var cityData = data;
        
             var   chatUrl = 'https://carcraft.whoson.com/chat/chatstart.htm?domain=' + cityData.CarCraftCity.toLowerCase() + '.carcraft.co.uk&x-vrm=' + carReg;
          
            newWin.location = chatUrl;


        });
    }



}
function GetPostCode(isDirections, btn) {
    myBtn = btn;
    $("#searchControl").val($(myBtn).val());

    myDirection = isDirections;


    if ($("#cachedpostcode").val() == null || $("#cachedpostcode").val() == "") {
        $('#dialog-form').dialog('open');
        return false;
    };
    return true;
}

function popupLiveChat() {

    var newWin = window.open('', 'wochat', 'width=484,height=361', 'location=no', true);
    return newWin;
}
function errorHandler(message, url, line) {
    // message == text-based error description
    // url     == url which exhibited the script error
    // line    == the line number being executed when the error occurred

    // handle the error here

    // stop the event from bubbling up to the default window.onerror handler
    // (see the "For More Info" section for an article on event bubbling)
    return true;
}







$(document).ready(function() {

    window.onerror = errorHandler;


    $(".results-right-column .tabs").tabs();
    $(".results-right-column .tabs").show();

    //toggle the componenet with class msg_body
    EnableUpdatebutton();

    $('div.pay-weekly').hide();
    $('div.by-price').hide();

/*start For finance page, hide show copy at the top of the page */
    $(".more").click(function() {
        $(".hide").slideToggle("slow", function() {
            $(".more").toggle(); //hide once show has finished 
        });
    });

    $(".less").click(function() {
        $(".hide").slideToggle("slow", function() {
            $(".more").toggle(); //show once hide has finished
        });
    });
/* end */

    $('#showWeekly').click(function() {
        $('div.pay-monthly').hide();
        $('div.by-price').hide();
        $('div.pay-weekly').show(500);
    });

    $('#showMonthly').click(function() {
        $('div.pay-monthly').show(500);
        $('div.by-price').hide();
        $('div.pay-weekly').hide();
    });

    $('#showPrice').click(function() {
        $('div.pay-monthly').hide();
        $('div.by-price').show(500);
        $('div.pay-weekly').hide();
    });

    $('a[rel*=external]').click(function() {
        window.open(this.href);
        return false;
    });

    // Add styles to buttons
    $("a.button, :button.button, input.button").button();
    $("a.nextButton, :button.nextButton, input.nextButton").button({ icons: { primary: 'ui-icon-circle-arrow-e'} });
    $("a.deleteButton, :button.deleteButton, input.deleteButton").button({ icons: { primary: 'ui-icon-trash'} });
    $("a.editButton, :button.editButton, input.editButton").button({ icons: { primary: 'ui-icon-pencil'} });


    // Add styles to text boxes
    $(":text, select, fieldset, textarea").each(function() {
        $(this).addClass("ui-corner-all ClickTaleSensitive");
    });

    // Add styles to validation summary and it's li children
    $("ul.validation-summary>li").each(function() {
        $(this).prepend("<span class='ui-icon ui-icon-alert ui-icon-left' />");
    });

    // Setup the date picker
    $(".datepicker").datepicker({ changeMonth: true, changeYear: true, showOn: 'button', buttonImage: '/c/i/calendar.png', buttonImageOnly: true, buttonText: "Select Date", yearRange: "1930:2012", dateFormat: "dd/mm/yy" });

    // Flash the validation summary if it's visible or the information flash if not
    if ($(".validation-summary").is(":visible")) {
        // Flash with highlight to attract attention
        $(".validation-summary").effect("highlight", { color: "#FF0000" }, 5000);
    } else {
        // Flash with highlight to attract attention
        $("#informationFlash").effect("highlight", null, 5000);
    }

    //$(".tabs").tabs({ cache:true, ajaxOptions: { async: true} });



    var postcode = $("#locpostcode"),
			allFields = $([]).add(postcode),
			tips = $(".validateTips");

    function updateTips(t) {
        tips
				    .text(t)
				    .addClass('ui-state-highlight');
        setTimeout(function() {
            tips.removeClass('ui-state-highlight', 1500);
        }, 500);
    }

    function checkLength(o, n, min, max) {

        if (o.val().length > max || o.val().length < min) {
            o.addClass('ui-state-error');
            updateTips("Length of " + n + " must be between " + min + " and " + max + ".");
            return false;
        } else {
            return true;
        }

    }

    function checkRegexp(o, regexp, n) {

        if (!(regexp.test(o.val()))) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }

    }

    $("#dialog-form").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
            'OK': function() {
                var bValid = true;
                allFields.removeClass('ui-state-error');
                bValid = bValid && checkLength(postcode, "postcode", 5, 8);
                bValid = bValid && checkRegexp(postcode, /([A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2})/i, "Postcode must be valid : e.g. OL11 3JW");
                if (bValid) {

                    $("#cachedpostcode").val($(postcode).val());
                    $("#cachedpostcode").hide();
                    if (myDirection == null) {
                        var myurl = window.location.protocol + "//" + window.location.host + '/home/livechat?postcode=' + $(postcode).val();
                        var newWin = popupLiveChat();
                        $.post(myurl, function(data) {

                            {

                                $("#dialog-form").dialog('close');
                                var cityData = data;

                                var chatUrl = 'https://carcraft.whoson.com/chat/chatstart.htm?domain=' + cityData.CarCraftCity.toLowerCase() + '.carcraft.co.uk&x-vrm=' + carReg;

                                newWin.location = chatUrl;

                            }
                        });


                    }
                    else {
                        var myurl = window.location.protocol + "//" + window.location.host + '/home/setpostcode?postcode=' + $(postcode).val();
                        var myformdata = $('#searchForm').serialize();
                        $.ajax({
                            type: "POST",
                            url: myurl,
                            data: myformdata,
                            success: function(msg) {

                                if (myDirection == true) {
                                    loadDirections($(postcode).val(), address);
                                    $("#dialog-form").dialog('close');
                                }
                                else {
                                    $("#dialog-form").dialog('close');
                                    __doPostBack = newDoPostBack;
                                    __doPostBack(null);
                                }
                            }
                        });
                    }
                }
            }
        },
        close: function() {
            allFields.val('').removeClass('ui-state-error');
            history.forward();
            return false;

        }
    });

    $('#dialog-form').parent().appendTo($("form:first"));

    function newDoPostBack(eventArgument) {
        var theForm = $('#searchForm');
        if (!theForm.onsubmit || (theForm.onsubmit() != false)) {

            theForm.submit();
        }
    }

    $("#directions-form").dialog({
        autoOpen: false,
        modal: true,
        width: 600,
        buttons: {
            'Print': function() {
                var printWin = window.open("", "Directions");
                printWin.document.open();
                printWin.document.write("<html><body>");
                printWin.document.write("Directions to Carcraft");
                printWin.document.write($("#directions").html());
                printWin.document.write('</body></html>');
                printWin.focus();
                printWin.print();

            },
            'Close': function() {
                $(this).dialog('close');
            }
        }
    });



    $(":text, select, textarea").focus(function() {

        if (this.id == 'locpostcode') return true;

        $(".hint").hide();
        var hint = $(this).next();
        if (hint.hasClass('field-validation-error')) {
            $(hint).next('.hint').show();

        }
        else if (hint.hasClass('ui-datepicker-trigger')) {
            $(hint).next('.hint').show();
        }
        else if (hint.hasClass('hint')) {
            hint.show();
        }


    });



});

function initialise(mapData) {
    $("#mapName").text(mapData.Name);
    var map = new google.maps.Map2($("#map")[0]);
    map.addControl(new google.maps.SmallMapControl());
    map.addControl(new google.maps.MapTypeControl());
    map.setMapType(G_NORMAL_MAP);
    var latlng = new google.maps.LatLng(mapData.LatLng.Latitude, mapData.LatLng.Longitude);
    var zoom = mapData.Zoom;
    map.setCenter(latlng, zoom);
    $.each(mapData.Locations, function(i, location) {
        setupLocationMarker(map, location);
    });
}

function loadDirections(postCode, businessPostCode) {
    try {
        var directions = "from: " + postCode + " to: " + businessPostCode;
        // Initialize the GDirections class, load the directions
        gd = new GDirections(null, null);
        loader = gd.load(directions, { "locale": "en_GB", "getSteps": "true" });
        // event listener
        GEvent.addListener(gd, "load", onLoader);

    } catch (e) {

    }


}

function onLoader() {

    // Grab the distance between point A and point B
    var route = gd.getRoute(0);
    var steps = route.getNumSteps();
    var data = "<ul>";
    for (var s = 0; s < route.getNumSteps(); s++) {
        var step = route.getStep(s);
        data += "<li>";
        data += step.getDescriptionHtml();
        data += "&nbsp;(";
        var mi = Math.round((step.getDistance().meters * 0.000621) * Math.pow(10, 2)) / Math.pow(10, 2);
        data += String(mi);
        data += "&nbsp;miles)";
        data += "</li>";

    }
    data += "<ul>";
    $('#directions').html(data);
    $('#directions-form').dialog('open');
}


function setupLocationMarker(map, location) {
    var latlng = new google.maps.LatLng(location.LatLng.Latitude, location.LatLng.Longitude);
    var marker = new google.maps.Marker(latlng);
    map.addOverlay(marker);

    $("#info").text(location.Name);
    map.openInfoWindow(latlng, $("<p></p>").text(location.Name)[0]);
    google.maps.Event.addListener(marker, "mouseover", function(latlng) {
        $("#info").text(location.Name);

        map.openInfoWindow(latlng, $("<p></p>").text(location.Name)[0]
        );
    });
}


function dateMask(key, textbox) {
    if (key == 8 || key == 46) {
        return true;
    }

    var text = textbox.value;
    if (text.length > 10) {
        return false;
    }

    if ((key == 111) || (key == 191)) {
        if (text.length == 2 || text.length == 5) {
            return true;


        }
        return false;
    }

    if ((key > 47 && key < 58) || (key > 95 && key < 106)) {
        if (key > 95) {
            key = key - (96 - 48);
        }
        if (text.length == 1 || text.length == 4) {
            textbox.value = text + String.fromCharCode(key) + '/';
            return false;

        }
        return true;
    }

    return false;
}




