﻿function hideAll() {
    $('#aMovement, #aCommunity, #av9, #aTips, #aStory, #aAspca').removeClass("active");
    $('#content').height("920px");
    $('#content').css("min-height", "920px");
    $('#pHome div, #pMovement div, #pCommunity object, #pCommunity div, #pAv9 div, #pTips div, #pStory div, #pAspca div').hide();
    $('#pHome, #pMovement, #pCommunity, #pAv9, #pTips, #pStory, #pAspca').animate({ "left": "-925px", width: "0%" }, "slow");
}

function transPage(p, rotator) {    
    hideAll();
    if (p == "pHome") {
        $('#' + p + '').animate({ "left": "0px", width: "905px" }, "slow");
    } else {
        $('#' + p + '').animate({ "left": "0px", width: "925px" }, "slow");
    }
    $('#' + p + ' div').show();
    
    if (rotator == "facts") {
        jQuery('#factsCarousel').jcarousel({
            scroll: 1,
            wrap: 'circular',
            itemVisibleInCallback: { onBeforeAnimation: facts_itemVisibleInCallback },
            itemVisibleOutCallback: { onAfterAnimation: facts_itemVisibleOutCallback }
        });
    }
    if (rotator == "harness" && p == "pAspca") {
        jQuery('#productsCarousel').jcarousel({
            scroll: 1,
            wrap: 'circular',
            itemVisibleInCallback: { onBeforeAnimation: harness_itemVisibleInCallback },
            itemVisibleOutCallback: { onAfterAnimation: harness_itemVisibleOutCallback }
        });
    } else if (rotator == "harness" && p == "pAv9") {
        jQuery('#harnessCarousel').jcarousel({
            scroll: 1,
            wrap: 'circular',
            itemVisibleInCallback: { onBeforeAnimation: harness_itemVisibleInCallback },
            itemVisibleOutCallback: { onAfterAnimation: harness_itemVisibleOutCallback }
        });
    }
}

function formatTitle(title) {
    return 'Paws To Click - ' + (title);
}

function handleChange(event) {
    var index, rel, links = $('a.priLink'), path = event.path;
    if (path.substr(path.length - 1) != '/') {
        path += '/';
    }
    for (var i = 0, l, link; link = links[i]; i++) {
        index = link.rel.indexOf('?');
        rel = (index > -1) ? link.rel.substr(0, index) : link.rel;
        link.className = (rel == path) ? 'selected' : '';
    }
    var parameters = '';
    for (var p in event.parameters) {
        parameters += '&' + p + '=' + event.parameters[p];
    }

    if (event.path == "/CommunityPage/") {
        transPage("pCommunity");
        SWFAddress.setTitle(formatTitle("Our Community"));
        initCommunity();
        return false;
    }
    if (event.path == "/Home/") {
        transPage("pHome");
        SWFAddress.setTitle(formatTitle("Home"));
        return false;
    }
    if (event.path == "/MovementPage/") {
        transPage("pMovement", "facts");
        SWFAddress.setTitle(formatTitle("Our Movement"));
        return false;
    }
    if (event.path == "/StoryPage/") {
        transPage("pStory");
        SWFAddress.setTitle(formatTitle("The Bergan Story"));
        return false;
    }
    if (event.path == "/TipsPage/") {
        transPage("pTips");
        SWFAddress.setTitle(formatTitle("Safe Travel Tips"));
        return false;
    }
    if (event.path == "/V9DTPage/") {
        transPage("pAv9", "harness");
        SWFAddress.setTitle(formatTitle("V9DT Pet Harness"));
        return false;
    }
    if (event.path == "/AspcaPage/") {
        transPage("pAspca", "harness");
        SWFAddress.setTitle(formatTitle("ASPCA"));
        return false;
    }
}

SWFAddress.addEventListener(SWFAddressEvent.CHANGE, handleChange);

var facts_itemList = [
    { url: '/images/facts/fact1.gif', title: 'Every 18 Minutes a car accident occurs due to a loose pet in the vehicle' },
    { url: '/images/facts/fact2.gif', title: '30,000 accidents per year are caused by dogs in the front seats' },
    { url: '/images/facts/fact3.gif', title: '98% of dogs travel unrestrained in moving vehicles' }
];

function facts_itemVisibleInCallback(carousel, item, i, state, evt) {
    var idx = carousel.index(i, facts_itemList.length);
    carousel.add(i, facts_getItemHTML(facts_itemList[idx - 1]));
};

function facts_itemVisibleOutCallback(carousel, item, i, state, evt) {
    carousel.remove(i);
};

function facts_getItemHTML(item) {
    return '<img src="' + item.url + '" alt="' + item.title + '" />';
};

var harness_itemList = [
    { url: '/images/harness/1.gif' },
    { url: '/images/harness/2.gif' },
    { url: '/images/harness/3.gif' },
    { url: '/images/harness/4.gif' },
    { url: '/images/harness/5.gif' },
    { url: '/images/harness/6.gif' },
    { url: '/images/harness/7.gif' },
    { url: '/images/harness/8.gif' },
    { url: '/images/harness/9.gif' },
    { url: '/images/harness/10.gif' }
];

function harness_itemVisibleInCallback(carousel, item, i, state, evt) {
    var idx = carousel.index(i, harness_itemList.length);
    carousel.add(i, harness_getItemHTML(harness_itemList[idx - 1]));
};

function harness_itemVisibleOutCallback(carousel, item, i, state, evt) {
    carousel.remove(i);
};

function harness_getItemHTML(item) {
    return '<img src="' + item.url + '" alt="Harness" />';
};

function checkStatus() {
    $.ajax({
        type: "POST",
        url: "/Services/Bergan.asmx/IsAuthenicated",
        data: "{}",
        contentType: "application/json",
        dataType: "json",
        success: function(res) {
            if (res.d == true) {
                populateMyProfile();
                $("#myProfileDetailsMessage").hide();
                showPopup("#myProfileFormPopup");
            }
            else {
                showPopup("#myProfileSignInPopup");
                $("form#frmSignIn").show();
                $("form#frmForgotPassword").hide();
            }
        },
        error: function(res) {
            alert('error: ' + res.responseText);
        }
    });
}

function initCommunity() {
    var params = { allowScriptAccess: 'always', scale: 'noScale', wmode: 'transparent', allowFullScreen: 'true' };
    var atts = { id: "flashContent", menu: 'false', quality: 'high' };
    var flashvars = {};
    swfobject.embedSWF("/flash/BerganCommunity.swf", "flashContent", "925", "887", "10", "/flash/expressInstall.swf", flashvars, params, atts);
}

$(document).ready(function() {

    $('#pledgeMessage').hide();
    $('#joinCommunityMessage').hide();
    $('.help[title]').qtip({
        position: {
            target: 'mouse',
            adjust: { mouse: true },
            adjust: { x: 10, y: -10 },
            corner: {
                target: 'topLeft',
                tooltip: 'bottomLeft'
            }
        },

        style: {
            width: 200,
            padding: 10,
            background: '#166D9F',
            color: '#FFFFFF',
            textAlign: 'center',
            border: {
                width: 3,
                radius: 5,
                color: '#166D9F'
            },
            name: 'dark' // Inherit the rest of the attributes from the preset dark style
        }
    });

    if ($("#JoinCommunityStatus").val().length > 0) {
        if ($("#JoinCommunityStatus").val() == 'ok') {
            $('#joinCommunityMessage').html('“Thank you! Your have successfully joined our community. Please follow our community links to spread the word to others.”').show();
            $("#PetName").val("");
            $("#FirstName").val("");
            $("#LastName").val("");
            $("#City").val("");
            $("#Zip").val("");
            $("#EmailAddress").val("");
            $("#Password").val("");
            $("#ConfirmPassword").val("");
            $("#Story").val("");
            $("#JoinedBecause").val("");
            $("#uploadify").val("");
            $("#JoinCommunityStatus").val("");
        }
        else {
            $('#joinCommunityMessage').html($("#JoinCommunityStatus").val()).show();
        }
        $('#joinCommunityMessage').show();

        resetPopUp();
        showPopup("#joinCommunityFormPopup");
    }

    if ($("#UpdateCommunityStatus").val().length > 0) {
        if ($("#UpdateCommunityStatus").val() == 'ok') {
            $('#myProfileDetailsMessage').html('Your profile has been successfully updated.').show();
        }
        else {
            $('#myProfileDetailsMessage').html($("#UpdateCommunityStatus").val()).show();
        }

        populateMyProfile();
        $("#myProfileDetails").show();
        $('#myProfileDetailsMessage').show();

        resetPopUp();
        showPopup("#myProfileFormPopup");
    }

    $("fieldset input:first").select();
    $("#Zip").mask("99999");
    $("#DetailsZip").mask("99999");
    $("#zipcode").mask("99999");
    $("#zipCode2").mask("99999");

    $("#zipcode").focus(function() {
        $(this).val('');
    });

    $("#zipcode").blur(function() {
        if ($(this).val().length <= 0)
            $(this).val('Zip Code');
    });

    $("#zipcode2").focus(function() {
        $(this).val('');
    });

    $("#zipcode2").blur(function() {
        if ($(this).val().length <= 0)
            $(this).val('Zip Code');
    });

    $("#detailszip").focus(function() {
        $(this).val('');
    });

    $("#detailszip").blur(function() {
        $(this).val('Zip Code');
    });

    $("a#aJoin, a#aPledge").click(function() {
        showPopup("#pledgePopup");
        return false;
    });

    $("a#aPledge2").click(function() {
        resetPopUp();
        showPopup("#pledgeformPopup");
        return false;
    });

    $("#joinCommunityForm a.help").click(function() {
        return false;
    });

    $("a#aJoinCommunity").click(function() {
        //resetPopUp();
        showPopup("#joinCommunityFormPopup");
        return false;
    });

    $("#aForgotPassword").click(function() {
        $("form#frmSignIn").hide();
        $("form#frmForgotPassword").show();
        return false;
    });

    $("a#aMyProfileSignOut").click(function() {
        $.ajax({
            type: "POST",
            url: "/Services/Bergan.asmx/SignOut",
            data: "{}",
            contentType: "application/json",
            dataType: "json",
            success: function(res) {
                resetPopUp();
            },
            error: function(res) {
                $('#myProfileDetailsMessage').html(res.responseText).show();
                alert('error: ' + res.responseText);
            }
        });
        return false;
    });

    $("a#aForgotPwdSubmit").click(function() {
        if ($("#frmForgotPassword").valid()) {
            var forgotParameters = "{'emailAddress': '" + $('#EmailAddressForgot').val() + "'}";
            $.ajax({
                type: "POST",
                url: "/Services/Bergan.asmx/ForgotPassword",
                data: forgotParameters,
                contentType: "application/json",
                dataType: "json",
                success: function(res) {
                    if (res.d == true) {
                        $('#myProfileLogInMessage').html('Password Reminder has been sent to the email you specified.').show();
                        showPopup("#myProfileSignInPopup");
                    }
                    else {
                        $('#myProfileLogInMessage').html('Sorry, the email address you entered was not found.').show();
                        showPopup("#myProfileSignInPopup");
                    }
                },
                error: function(res) {
                    alert('error: ' + res.responseText);
                }
            })
        }
    });

    $("a#aMyProfile").click(function() {
        checkStatus();
        return false;
    });

    $("a#aSpreadWord").click(function() {
        resetPopUp();
        showPopup("#socialPopup");
        return false;
    });

    $("#aStoreFinder").click(function() {
        pageTracker._trackPageview('/storelocator/zipsearch');
        showPopup("#storeFinderPopup");
        searchLocations($('#zipcode').val());
        return false;
    });

    $("a.closePopup").click(function() {
        resetPopUp();
    });

    $('#aSignInSubmit').click(function() {
        if ($("#frmSignIn").valid()) {
            var joinCommunityParameters = "{'emailAddress': '" + $('#EmailAddressMyProfile').val() + "', 'password': '" + $('#PasswordMyProfile').val() + "'}";
            $.ajax({
                type: "POST",
                url: "/Services/Bergan.asmx/ValidateUser",
                data: joinCommunityParameters,
                contentType: "application/json",
                dataType: "json",
                success: function(res) {
                    if (res.d.length <= 0) {
                        //$("#myProfileLogIn").hide();
                        populateMyProfile();
                        showPopup("#myProfileFormPopup");
                        //$("#myProfileDetails").show();
                    }
                    else {
                        $('#myProfileLogInMessage').html('Sorry, could not find a user with the email address and password entered.').show();
                        showPopup("#myProfileSignInPopup");
                    }
                },
                error: function(res) {
                    $('#myProfileLogInMessage').html('error: ' + res.responseText).show();
                }
            })
        }
    });

    $('#aPledgeSubmit').click(function() {
        if ($("#frmPledge").valid()) {

            // validate if email address has already pledged
            var pledgeParameters = "{'emailAddress': '" + $('#PledgeEmailAddress').val() + "'}";
            $.ajax({
                type: "POST",
                url: "/Services/BerganPledge.asmx/AlreadyPledged",
                data: pledgeParameters,
                contentType: "application/json",
                dataType: "json",
                success: function(res) {
                    if (res.d == true) {
                        $('#pledgeMessage').html('“Thank you! Your pledge has been counted once already. Please follow our community links to spread the word to others.”').show();
                    }
                    else {
                        var pledgeParameters = "{'firstName':'" + $('#PledgeFirstName').val() + "', 'lastName': '" + $('#PledgeLastName').val() + "', 'emailAddress': '" + $('#PledgeEmailAddress').val() + "'}";

                        $.ajax({
                            type: "POST",
                            url: "/Services/BerganPledge.asmx/Pledge",
                            data: pledgeParameters,
                            contentType: "application/json",
                            dataType: "json",
                            success: function(res) {
                                $('#pledgeCountMain').html(res.d).show();
                                $('#pledgeCountIndex').html(res.d).show();
                                $('#pledgeForm').hide();
                                $('#pledgeMessage').html('“Thank you! Your pledge has been counted. Please follow our community links to spread the word to others.”').show();
                            },
                            error: function(res) {
                                $('#pledgeMessage').html('error: ' + res.responseText).show();
                            }
                        });
                    }

                    return res.d;
                },
                error: function(res) {
                    alert('error: ' + res.responseText);
                    return true;
                }
            });
        }
    });

    $("#frmProfile").validate({
        rules: {
            ConfirmPassword: { equalTo: "#Password" }
        }
    });

    var myProfileFileName = '';
    $('#aMyProfileDetailsSubmit').click(function() {

        if ($("#frmMyProfileDetail").valid()) {
            $('#frmMyProfileDetail').submit();
        }
    });

    var fileName = '';
    $('#aCommunitySubmit').click(function() {
        if ($("#frmProfile").valid()) {

            // validate if email address has already joined community
            var joinCommunityParameters = "{'emailAddress': '" + $('#EmailAddress').val() + "'}";
            $.ajax({
                type: "POST",
                url: "/Services/BerganProfile.asmx/AlreadyJoinedCommunity",
                data: joinCommunityParameters,
                contentType: "application/json",
                dataType: "json",
                success: function(res) {
                    if (res.d == true) {
                        $('#joinCommunityMessage').html('“Thank you! You have already joined our community.”').show();
                    }
                    else {
                        $('#frmProfile').submit();
                    }
                },
                error: function(res) {
                    $('#joinCommunityMessage').html('error: ' + res.responseText).show();
                    return true;
                }
            });
        }
    });
});

function showPopup(target) {
    $.blockUI({
        message: $(target),
        css: {
            width: $(target).width(),
            top: ($(window).height() - $(target).height()) / 2.5 + 'px',
            left: ($(window).width() - $(target).width()) / 2 + 'px',
            border: 'none',
            cursor: 'default',
            backgroundColor: ''
        }
    });
}

// reset all displays and hide the popup
function resetPopUp() {
    $.unblockUI();
}

function populateMyProfile() {
    $.ajax({
        type: "POST",
        url: "/Services/BerganProfile.asmx/GetProfileDetails",
        data: "{}",
        contentType: "application/json",
        dataType: "json",
        success: function(res) {
            $('#DetailsId').val(res.d.ID);
            $('#DetailsPetName').val(res.d.PetName);
            $('#DetailsFirstName').val(res.d.FirstName);
            $('#DetailsLastName').val(res.d.LastName);
            $('#DetailsCity').val(res.d.City);
            $('#DetailsStateListID').val(res.d.StateListID);
            $('#DetailsZip').val(res.d.Zip);
            $('#DetailsEmailAddress').val(res.d.EmailAddress);
            $('#DetailsStory').val(res.d.Story);
            $('#DetailsJoinedBecause').val(res.d.JoinedBecause);

            if (res.d.Filename != null) {
                $('#myProfilePicture').attr('href', '/media/profile/' + res.d.Filename);
                $('#myProfilePicture').text('View your profile image');
            } else {
                $('#myProfilePicture').text('No image found');
            }
        },
        error: function(res) {
            $('#myProfileLogInMessage').html('error: ' + res.responseText).show();
        }
    })
}

//Google Maps
var map;
var geocoder;
var pageZip;
var pageProduct;

function load() {
    if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById('map'));

        var mapControl = new GSmallMapControl();
        var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(1, 1));

        map.addControl(mapControl, topLeft);
    }
}

function searchLocations(zipCode) {
    load();

    if (zipCode.length > 1) {
        geocoder.getLatLng(zipCode, function(latlng) {
            if (!latlng) {
                var sidebar = document.getElementById('sidebar');
                sidebar.innerHTML = '<span style="color:#ff0000;"><strong>' + zipCode + ' not found.</strong></span>';
            } else {
                searchLocationsNear(latlng);
            }
        });
    }   
}

function searchLocations2(address) {
    geocoder.getLatLng(address.toString(), function(latlng) {
        if (!latlng) {
            var sidebar = document.getElementById('sidebar');
            sidebar.innerHTML = '<span style="color:#ff0000;"><strong>' + address + ' not found.</strong></span>';
        } else {
            searchLocationsNear(latlng);
        }
    });
}

function searchLocationsNear(center) {
    $('#divError').show();
    $('#snError').html('');
    $("#activityIndicator").show();

    var searchUrl = "/generichandler/getstores.ashx?lt=" + center.lat() + "&ln=" + center.lng();

    GDownloadUrl(searchUrl, function(data) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName('marker');

        //reset map
        map.clearOverlays();
        var sidebar = document.getElementById('sidebar');
        sidebar.innerHTML = '';

        if (markers.length == 0) {
            $("#activityIndicator").hide();
            sidebar.innerHTML = '<span style="color:#ff0000;"><strong>No results found.</strong></span>';
            map.setCenter(new GLatLng(38, -97), 3); //b'ville
            return;
        }

        var bounds = new GLatLngBounds();

        //parse xml, add points		
        for (var i = 0; i < markers.length; i++) {
            //xml data
            var address = markers[i].getAttribute('streetAddress');
            var city = markers[i].getAttribute('city');
            var phone = markers[i].getAttribute('phone');
            var state = markers[i].getAttribute('state');
            var zip = markers[i].getAttribute('zip');
            //additional
            var type = markers[i].getAttribute('type');
            var availableProducts = markers[i].getAttribute('prod');

            //var distance = parseFloat(markers[i].getAttribute	('distance'));
            var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lon')));

            var marker = createMarker(point, type, address, city, state, zip, phone);
            map.addOverlay(marker);

            var sidebarEntry = createSidebarEntry(marker, type, address, city, state, zip, phone, availableProducts);
            sidebar.appendChild(sidebarEntry);
            bounds.extend(point);
        }
        map.setCenter(bounds.getCenter(), 10); //map.getBoundsZoomLevel(bounds)

        $("#activityIndicator").hide();
    });
}

function createSidebarEntry(marker, name, address, city, state, zip, phone, availableProducts) {
    var div = document.createElement('div');

    var html = '<ul><li><h4>' + name + '</h4>' + address + '<br />' + city + ', ' + state + ' ' + zip + '<br />' + phone + '<h4>Products Available:</h4>' + availableProducts.replace(/:/g, "<br />") + '<br /></li></ul>';

    div.innerHTML = html;
    div.style.cursor = 'pointer';

    GEvent.addDomListener(div, 'click', function() {
        GEvent.trigger(marker, 'click');
    });

    return div;
}

function createMarker(point, name, address, city, state, zip, phone) {

    var baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.iconSize = new GSize(14, 22);

    var dogIcon = new GIcon(baseIcon);
    dogIcon.image = "images/gmapdog.gif";

    // Set up our GMarkerOptions object
    markerOptions = { icon: dogIcon };
    var marker = new GMarker(point, markerOptions);

    var html = '<span style="color:#000000;"><b>' + name + '</b><br />' + address + '<br />' + city + ', ' + state + ' ' + zip + '<br />' + phone + '</span>';

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
    });

    return marker;
}