﻿//************************************************************************************* 
// File     :   scuba_functions
// Requires :   jquery.js (version 1.2.6+), braingnat.js (version 0.1.2+)
// Author   :   Kyle Weems (ksw)
// Origin   :   mindfly.com
// Created  :   January 23, 2009
// Modified :   October 26, 2009
// Purpose  :   Holds the functions for site-specific needs.
//*************************************************************************************

// Variable for later use with google maps.
var map = null;

// Runs when page is loaded.
$(document).ready(function() {
    BrainGnat.setContentHeight();
    bindDealerGo();
    dealerContactInfoShutter();
    confirmDealerAcctType();
    clickAnchorAsButtonOnPressingEnter();
});

// bindDealerGo() - Binds the Dealer Locator's search button
function bindDealerGo() {
    $('a.cmdGo').bind('click', function() {
        loadDealers($('#txtZip').attr('value'), $('#sbMiles').attr('value'));
        return false;
    });
    $('#txtZip').bind('keydown', function(event) {
        if (event.which == 13) {
            return false;
        }
    });
    $('#txtZip').bind('keypressed', function(event) {
        if (event.which == 13) {
            return false;
        }
    });
    $('#txtZip').bind('keyup', function(event) {
        if (event.which == 13) {
            loadDealers($('#txtZip').attr('value'), $('#sbMiles').attr('value'));
        }
        return false;
    });
} // end of function


// loadMap() - Loads a google map on the Dealer Locator page
function loadMap() {
    if ($('#mapCanvas').length > 0) {
        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById("mapCanvas"));
            geocoder = new GClientGeocoder();
            map.addControl(new GLargeMapControl());
        }
    }
} // end of function


// loadDealers() - Does an AJAX.NET asynchronous call to retrieve a JSON formatted list of dealers, and then processes them at processDealers().
function loadDealers(zip, radius) {
    $('#content').css('height', 'auto');
    $('#loadResults').css('display', 'block');
    $('.dealerResults').css('display', 'none');
    var root_id = $('.dealerRoot').attr('value');
    $.get('/js/MCNT.JSON2.ashx', { 'root_id': root_id, 'zip': zip, 'radius': radius }, processDealers);
} // end of function


// processDealers() - Opens the map in the dealer locator and adds a point for every dealer located.
function processDealers(data) {
    $('.dealerResults').css('display', 'block');
    $('#loadResults').css('display', 'none');
    loadMap();
    var zoom = Math.round(11 - ($('#sbMiles').attr('value') / 50));
    if (zoom < 6) { zoom = 6; }
    var json = eval('(' + data + ')');
    for (i = (json.dealer.length - 1); i > -1; i--) {
        var latlng = new GLatLng(json.dealer[i].latitude, json.dealer[i].longitude);
        var dealername = json.dealer[i].dealername;
        if (json.dealer[i].url != "") {
            var url = json.dealer[i].url;
            if (url.substr(0, 7) != "http://") {
                url = "http://" + url;
            }
            dealername = "<a href='" + url + "' target='_blank'>" + dealername + "</a>";
        }
        var address = json.dealer[i].address + "<br />" + json.dealer[i].city + ", " + json.dealer[i].state + " " + json.dealer[i].zip + "<br />" + json.dealer[i].phone;
        showAddress(dealername, latlng, address, zoom);
    }
} // end of function



// errorFunc() - Dummy error handling function
function errorFunc(data) {
    alert('There was an error fetching the dealer list:');
}


// showAddress() - Loads a marker (and creates info window) for a point at latlng.
function showAddress(locationName, latlng, address, zoom) {
    if (GBrowserIsCompatible()) {
        map.setCenter(latlng, zoom);
        var marker = new GMarker(latlng);
        map.addOverlay(marker);
        marker.bindInfoWindowHtml(locationName + "<br />" + address);
    }
} // end of function


function dealerContactInfoShutter() {
    $('.repInfo button').bind('click', function() {
        $(this).siblings('ul').toggleClass('show');
        if ($(this).siblings('ul').hasClass('show')) {
            $(this).html('Click to Close List');
        } else {
            $(this).html('Click for Rep List');
        }
        return false;
    });
    $('.repInfo h3').bind('click', function() {
        $(this).siblings('ul').toggleClass('show');
        if ($(this).siblings('ul').hasClass('show')) {
            $(this).siblings('button').html('Click to Close List');
        } else {
            $(this).siblings('button').html('Click for Rep List');
        }
    });
}

// confirmDealerAcctType() - On Dealer Login page, checks if account number entered matches this website, if not it redirects the user.
function confirmDealerAcctType() {
    $('input[id$="txtLoginAccount"]').bind('keyup', function() {
        var login = $('input[id$="txtLoginAccount"]').attr('value');
        if (login.length > 5) {
            $.get('/DealerAccountLoginHandler.axd?account=' + login, function(data) {
                json = eval('(' + data + ')');
                if (typeof (json.dealerlogin[0]) != 'undefined') {
                    if (json.dealerlogin[0].validAccount == "True") {
                        if (json.dealerlogin[0].correctSite == "False") {
                            $('input[id$="txtLoginAccount"]').unbind('keyup');
                            alert("The account number you have entered goes to a different McNett site. We will redirect you to the proper URL.");
                            window.location = json.dealerlogin[0].correctUrl;
                        }
                    }
                }
            });
        }
    });

    $('input[id$="txtCreateAccount"]').bind('keyup', function() {
        var login = $('input[id$="txtCreateAccount"]').attr('value');
        if (login.length > 5) {
            $.get('/DealerAccountLoginHandler.axd?account=' + login, function(data) {
                json = eval('(' + data + ')');
                if (typeof (json.dealerlogin[0]) != 'undefined') {
                    if (json.dealerlogin[0].validAccount == "True") {
                        if (json.dealerlogin[0].correctSite == "False") {
                            $('input[id$="txtCreateAccount"]').unbind('keyup');
                            alert("The account number you have entered goes to a different McNett site. We will redirect you to the proper URL.");
                            window.location = json.dealerlogin[0].correctUrl;
                        } else {
                            if (isNaN(json.dealerlogin[0].postalCode)) {
                                $('label[id$="txt_zip"] .fieldLabel').html('Country Name');
                            } else {
                                $('label[id$="txt_zip"] .fieldLabel').html('Store Zip Code');
                            }
                        }
                    }
                }
            });
        }
    });
}

function clickAnchorAsButtonOnPressingEnter() {
    $('.dealerLogin input').keyup(function(e) {
        if (e.keyCode == 13) {
            var command = $('.dealerLogin .button').attr('href');
            var bits = command.split("javascript:");
            command = bits[1];
            eval(command);
        }
    });
    $('.dealerNeedAcct input').keyup(function(e) {
        if (e.keyCode == 13) {
            var command = $('.dealerNeedAcct .button').attr('href');
            var bits = command.split("javascript:");
            command = bits[1];
            eval(command);
        }
    });
    $('.createUser input').keyup(function(e) {
        if (e.keyCode == 13) {
            var command = $('.createUser .button').attr('href');
            var bits = command.split("javascript:");
            command = bits[1];
            eval(command);
        }
    });
}