/// <reference path="jquery-vsdoc.js" />

$(document).ready(function () {

    $('.product-nav li').hover(function () { $(this).addClass('hover') }, function () {
        $(this).removeClass('hover')
    });

    $('.home #derma-bodywash').hover(function () {
        $("#derma-bodywash-desc").css({ left: "505px" })
    }, function () {
        $("#derma-bodywash-desc").css({ left: "-9999px" })
    });

    $('.home #derma-bodymoisturiser').hover(function () {
        $("#derma-bodymoisturiser-desc").css({ left: "445px" })
    }, function () {
        $("#derma-bodymoisturiser-desc").css({ left: "-9999px" })
    });

    $('input, select, textarea').focus(function () {
        $(this).addClass('focus');
    }).blur(function () {
        $(this).removeClass('focus');
    });

    $('input[type="text"]').each(function () {
        $(this).val($(this).attr('title'))
    });

    $('input[type="text"]').click(function () {
        if ($(this).val() == $(this).attr('title'))
            $(this).val('');
    }).blur(function () {
        if ($(this).val() == "")
            $(this).val($(this).attr('title'));
    });

    $('ul, ol').each(function () {
        $('li:first', this).addClass('first-child');
        $('li:last', this).addClass('last-child');
    });


    if ($('.product-nav').length != 0) {
        var page = window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1);
        switch (page) {
            case "GentleSkinCleanser.aspx":
                $('.product-nav li:eq(0)').addClass('hover');
                break;
            case "OilySkinCleanser.aspx":
                $('.product-nav li:eq(1)').addClass('hover');
                break;
            case "GentleCleansingBar.aspx":
                $('.product-nav li:eq(2)').addClass('hover');
                break;
            case "DailyAdvanceUltraHydratingLotion.aspx":
                $('.product-nav li:eq(3)').addClass('hover');
                break;
            case "MoisturisingLotion.aspx":
                $('.product-nav li:eq(4)').addClass('hover');
                break;
            case "MoisturisingCream.aspx":
                $('.product-nav li:eq(5)').addClass('hover');
                break;
            case "IntensiveMoisturisingLotion.aspx":
                $('.product-nav li:eq(6)').addClass('hover');
                break;
        }

    }


    /************************** functinos for the where to buy map ****************************************/
    var map = null;
    var marker = null;
    var markerLocation = null;
    var MarkerStores = [];
    var MARKER_BOUNDS_LIMIT = 10;
    var mapInfoWindow = null;
    var panorama = null;
    var REQUEST_URL = 'GetLocations.aspx'



    function initializeMap() {
        mapInfoWindow = new google.maps.InfoWindow();
        var myOptions = {
            zoom: 3,
            center: new google.maps.LatLng(-25.165173, 133.242187),
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("where-to-buy-Map"),
        myOptions);
    }


    function showIsWorking(show) {
        if (show) $('#where-to-buy-Map').fadeIn();
        else setTimeout(function () { $('#where-to-buy-Map').fadeOut(); }, 1000);
    }

    function plotLocation(address) {
        showIsWorking(true);
        var geocoder = new google.maps.Geocoder();
        if (geocoder) {
            geocoder.geocode({ 'address': address + ', Australia' }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    removeCenterLocation();
                    var size = results.length;
                    if (size > 1) {
                        showAddressSuggest(results);
                    }
                    var markerOptions = {
                        position: results[0].geometry.location,
                        map: map
                    };
                    markerLocation = new google.maps.Marker(markerOptions);
                    setCenter();
                    plotStores();
                    removeCenterLocation();
                } else {
                    alert("Unable to locate your address, please try another location.");
                    showTextResults(false);
                    showIsWorking(false);
                    reset();
                }
            });
        }
    }


    function showAddressSuggest(addressList) {
        var copy = "<li class='no-liststyle'>Do you mean</li>";
        for (var i = 0; i < addressList.length; i++) {
            copy += "<li><a href='" + addressList[i].geometry.location + "'>" + addressList[i].formatted_address + "</a></li>";
        }
        $('#listSuggest').append(copy);
    }


    $("#listSuggest li a").live("click", (function (e) {
        e.preventDefault();
        $("#txtAddress").val($(this).text());
        plotLocation($(this).text());
    })
    );


    function setCenter() {
        map.setZoom(16);
        map.setCenter(markerLocation.getPosition());
    };


    function plotStores() {
        var lat = markerLocation.getPosition().lat();
        var lng = markerLocation.getPosition().lng();
        $.ajax({
            url: REQUEST_URL + '?long=' + lng + '&lati=' + lat,
            success: function (data, textStatus, XMLHttpRequest) {
                var json = $.parseJSON(data);
                if (json == null || json.length == 0) {
                    alert("No store found near that address, try searching for another location.");
                } else {
                    removeStores();
                    mapBounds = new google.maps.LatLngBounds();
                    mapBounds.extend(markerLocation.getPosition());
                    for (var j in json) createStoreMarker(json[j], j);
                    map.fitBounds(mapBounds);
                    var listItems = '';
                    for (var i = 0; i < 6 && i < json.length; i++) listItems += createTextResult(json[i]);
                    $('#vet-finder-results ul').empty().append(listItems);
                    showTextResults(true);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                map.setZoom(15);
                map.panTo(markerUser.getPosition());
                alert("An error has occurred, please try again later.");
            },
            complete: function (XMLHttpRequest, textStatus) {
                showIsWorking(true);
            }
        });
    }


    function createStoreMarker(store, index) {
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(store.Latitude, store.Longitude),
            map: map
        });

        google.maps.event.addListener(marker, 'click', function () {
            var content = '';
            var contentStreet2 = '';
            if (store.AddressLine2 != '') contentStreet2 = store.AddressLine2 + '<br />';
            var contentWebsiteUrl = '';
            if (store.Website != '') contentWebsiteUrl = '<a href="' + store.Website + '" target="_blank">View website</a><br />';



            var contentImage = '';

            if (store.BannerGroup && store.BannerGroup != '') {
                var imageName = store.BannerGroup.replace(/ /gi, "_");

                var exist = FileExists('/Common/Images/stores/' + imageName + '.jpg');
                if (exist == true) {
                    contentImage = '<div class="photo-frame-small photo-frame-small-right"><img src="/Common/Images/stores/' + imageName + '.jpg"  alt="" /></div>';
                }
            }



            content = '<h4>' + store.PharmacyName + '</h4>' + contentImage + '';

            content += '<p>' + store.AddressLine1 + '<br />' + contentStreet2 + ' ' + store.Suburb + ' ' + store.Postcode;

            if (store.Phone != '') {
                content += '<br />' + store.Phone;
            }

            content += '<br />' + contentWebsiteUrl + '</p>';


            //content += '<p class="info-links"><a href="#" class="showStreetView">Street view</a>';


            content = '<div style="height:130px;width:300px" class="info-window">' + content + '</div>';



            var infoWindowOptions = {

                position: marker.getPosition(),

                content: content

            };




            mapInfoWindow.setOptions(infoWindowOptions);

            mapInfoWindow.open(map, marker);


        });


        if (index < MARKER_BOUNDS_LIMIT) mapBounds.extend(marker.position);

        MarkerStores.push(marker);

    }


    function FileExists(strURL) {
        oHttp = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
        oHttp.open("HEAD", strURL, false);
        oHttp.send();
        return (oHttp.status == 404) ? false : true;
    }

    $(".showStreetView").live("click", (function (e) {
        e.preventDefault();
        //var berkeley = new google.maps.LatLng(37.869085, -122.254775);

        //var sv = new google.maps.StreetViewService();
        //panorama = new google.maps.StreetViewPanorama(document.getElementById("#where-to-buy-Map"));
        //sv.getPanoramaByLocation(berkeley, 50, processSVData);

    })
    );



    function processSVData(data, status) {
        if (status == google.maps.StreetViewStatus.OK) {
            var marker = new google.maps.Marker({
                position: data.location.latLng,
                map: map
                //title: data.location.description
            });

            panorama.setPano(data.location.pano);
            panorama.setPov({
                heading: 270,
                pitch: 0,
                zoom: 1
            });
            panorama.setVisible(true);

            google.maps.event.addListener(marker, 'click', function () {

                var markerPanoID = data.location.pano;
                // Set the Pano to use the passed panoID
                panorama.setPano(markerPanoID);
                panorama.setPov({
                    heading: 270,
                    pitch: 0,
                    zoom: 1
                });
                panorama.setVisible(true);
            });
        } else {
            alert("Street View data not found for this location.");
        }
    }



    function removeStores() {
        if (MarkerStores.length) {
            for (var v in MarkerStores) {
                google.maps.event.clearInstanceListeners(MarkerStores[v]);
                MarkerStores[v].setMap(null);
            }
        }
        MarkerStores = [];
        mapInfoWindow.close();
    }


    function removeCenterLocation() {
        if (markerLocation) {
            google.maps.event.clearInstanceListeners(markerLocation);
            markerLocation.setMap(null);
        }
    }



    $('#btnAddressSearch').click(function (e) {
        $("#listSuggest li").remove();
        e.preventDefault();
        var address = $('#txtAddress').val();
        if (address.length == 0) alert('Please enter an address.');
        else plotLocation(address);
    });

    if ($('#where-to-buy-Map').length != 0) {
        $('#sub-navigation').remove();
        initializeMap();
    };


    /********************************************* skin care flash ********************************/

    if ($('#flash-906x590').length != 0) {
        swfobject.embedSWF("/Common/Flash/SkincareGuide.swf", "flash-906x590", "906", "590", "9.0.0", "", "", { bgcolor: "#000000", wmode: "transparent" });

    }



});
