$(document).ready(function() {
    fixContentHeight();
    SideNavTreeView();
    HomesCarousel();
    //initializePropImgs();
    InitNeighborhoodModal();
    //initializeHomeSlides();
    InitContactForm();
});

function initializeHomeSlides() {
    $('.joe_featured-pagers').css('visibility', 'visible');
    $('.joe_featured-pagers .joe_featured-pager:first').addClass('active');
    $('.joe_featured-slides .joe_featured-slide:first').addClass('active');
    $('.joe_featured-slides .joe_featured-slide').show();
    setInterval("slideSwitch()", 7000);
}

function slideSwitch() {
    var $active = $('.joe_featured-slides .joe_featured-slide.active');
    var $activePager = $('.joe_featured-pagers .joe_featured-pager.active');
    if ($active.length == 0) $active = $('.joe_featured-slides joe_featured-slide:last');
    if ($activePager.length == 0) $activePager = $('.joe_featured-pagers .joe_featured-pager:last');

    var $next = $active.next().length ? $active.next()
			        : $('.joe_featured-slides .joe_featured-slide:first');

    var $nextPager = $activePager.next().length ? $activePager.next()
			        : $('.joe_featured-pagers .joe_featured-pager:first');

    $active.addClass('last-active');
    $activePager.addClass('last-active');

    $next.css({ opacity: 0.0 })
			        .addClass('active')
			        .animate({ opacity: 1.0 }, 300, function() {
			            $active.removeClass('active last-active');
			            $nextPager.addClass('active');
			            $activePager.removeClass('active last-active');
			        });
}
function fixContentHeight() {
    if ($('.main-content_body').height() < $('.sidebar-lft').height()) {
        //calculate offset based on padding and header of content area
        var contentOffset = parseFloat($('.main-content_body').css('padding-top').replace("px", "")) + $('.main-content_header').height();
        //calcuate required height based on left sidebar height and offset
        var contentHeight = $('.sidebar-lft').height() - contentOffset;
        //set the new min-height of the content body
        $('.main-content_body').css('min-height', contentHeight);
    }
}

function initializePropImgs() {
    var navImages = $('.img-viewer_nav-imgs img');
    var mainImages = $('.img-viewer_imgs .img-holder');
    $(mainImages).css({ opacity: 0.0 }).show();
    slides = new Array();
    for (i = 0; i < navImages.length; i++) {
        var tempSlide = {
            nav: navImages[i],
            img: mainImages[i],
            current: false,
            showSlide: function() {
                //$(this.img).fadeTo('slow', '100', function(){
                //		$(this).css('z-index', '5000');
                //	});
                $(this.img).animate({ opacity: 1 }, 1000, function() {
                    $(this).css('z-index', '5000');
                });
                $(this.nav).addClass('selected');
                this.current = true;
            },
            hideSlide: function() {
                //$(this.img).fadeTo('slow', '0', function(){
                //	$(this).css('z-index', '0');
                //});
                $(this.img).animate({ opacity: 0 }, 1000, function() {
                    $(this).css('z-index', '0');
                });
                $(this.nav).removeClass('selected');
                this.current = false;
            }
        };
        $(tempSlide.img).animate({ opacity: 0 }, 1);
        slides.push(tempSlide);
    }
    if (slides != null && slides.length > 0) {
        slides[0].showSlide();
    }
    for (j = 0; j < slides.length; j++) {
        $(slides[j].nav).bind('click',
			{
			    currentSlide: slides[j]
			},
				function(e) {
				    var currentSlide = e.data.currentSlide;
				    var prevSlide = "";
				    $.each(slides, function() {
				        if (this.current == true) {
				            prevSlide = this;
				        }
				    });
				    switchImg(prevSlide, currentSlide);
				}
		);
    }
    $('.img-viewer_up').hover(function() {
        var limit = $('.img-viewer_nav-slider').height();
        var pos = $('.img-viewer_nav-slider').position();
        $('.img-viewer_nav-slider').animate({ top: 0 }, 1000);
    }, function() {
        $('.img-viewer_nav-slider').stop();
    });
    $('.img-viewer_down').hover(function() {
        var imgsHeight = $('.img-viewer_nav-slider').height();
        var limitHeight = $('.img-viewer_nav-imgs').height();
        var offset = limitHeight - imgsHeight;
        if (offset < 0) {
            var pos = $('.img-viewer_nav-slider').position();
            $('.img-viewer_nav-slider').animate({ top: offset }, 1000);
        }
    }, function() {
        $('.img-viewer_nav-slider').stop();
    });
}

function switchImg(prevImage, nextImage) {
    if (nextImage != prevImage) {
        nextImage.showSlide();
        prevImage.hideSlide();
    }
}

function SubmitLead(formName) {
    ClearLeadValidation();
    //make ajax call to submit lead from form <formName>
    var fn = $("#firstname").val();
    var ln = $("#lastname").val();
    var em = $("#email").val();
    var ph = $("#phone").val();
    var cy = $("#country option:selected").val();
    var st = $("#state option:selected").val();
    var zp = $("#zip").val();
    var cm = $("#comments").val();
    var el = $("#email_list:checked").val() !== undefined;

    if (ValidateLead(fn, ln, em, cy, st, zp)) {

        //alert(cy + '\n' + st + '\n' + el);
        document.body.style.cursor = 'wait';

        $.ajax({
            type: "POST",
            dataType: 'json',
            url: "/Lead/SubmitContact",
            data: { FirstName: fn, LastName: ln, Email: em, Phone: ph, Country: cy, State: st, Zip: zp, Comments: cm, Subscribe: el },
            cache: false,
            success: SubmitLeadSuccessCallback,
            error: SubmitLeadErrorCallback
        });
    }
}

function ClearLeadValidation() {
    $("#firstname").removeClass("fieldrequired");
    $("#lastname").removeClass("fieldrequired");
    $("#email").removeClass("fieldrequired");
    $("#country").removeClass("fieldrequired");
    $("#state").removeClass("fieldrequired");
    $("#zip").removeClass("fieldrequired");
}

function ValidateLead(fn, ln, em, cy, st, zp) {
    var reasons = new Array();
    if (fn == null || fn == undefined || fn.length <= 0) {
        reasons.push("First Name is required.");
        $("#firstname").addClass("fieldrequired");
    }
    if (ln == null || ln == undefined || ln.length <= 0) {
        reasons.push("Last Name is required.");
        $("#lastname").addClass("fieldrequired");
    }
    if (em == null || em == undefined || em.length <= 0) {
        reasons.push("Email is required.");
        $("#email").addClass("fieldrequired");
    }
    if (cy == null || cy == undefined || cy.length <= 0) {
        reasons.push("Country is required.");
        $("#country").addClass("fieldrequired");
    }
    if (cy == "United States") {
        if (st == null || st == undefined || st.length <= 0) {
            reasons.push("State is required.");
            $("#state").addClass("fieldrequired");
        }
        if (zp == null || zp == undefined || zp.length <= 0) {
            reasons.push("Zip/Postal Code is required.");
            $("#zip").addClass("fieldrequired");
        }
    }
    //return true if no invalid reasons; false if at least one reason
    if (reasons.length > 0) {
        RenderLeadReasons("Please correct the following fields:", reasons);
        return false;
    }
    else {
        return true;
    }
}

function RenderLeadReasons(msg, reasons) {
    var msg = "<p>" + msg + "</p><ul>";
    $(reasons).each(function(r) {
        msg += "<li>" + reasons[r] + "</li>";
    });
    msg += "</ul>";

    ShowLeadNotification(msg);
}

function SubmitLeadSuccessCallback(result) {
    document.body.style.cursor = 'default';
    if (result.isValid) {
        ShowLeadNotification("Success!");

        GetConversionText();


    }
    else {
        if (result.reasons != null) {
            RenderLeadReasons(result.Error, result.reasons);
        }
        else {
            ShowLeadNotification(result.Error);
        }
    }
}

function SubmitLeadErrorCallback(xhr, error, exception) {
    ShowLeadNotification("Internal Server Error on lead submission.");
    document.body.style.cursor = 'default';
}

function ShowLeadNotification(msg) {
    $("#LeadErrorNotification").html(msg);
    $("#LeadErrorNotification").slideDown('slow', function() { var cnTmr = setTimeout('HideLeadNotification();', 5000); });
}

function HideLeadNotification() {
    $("#LeadErrorNotification").slideUp('slow');
}
function ShowNotification(msg) {
    $("#ErrorNotification").html(msg);
    $("#ErrorNotification").slideDown('slow', function() { var cnTmr = setTimeout('HideNotification();', 5000); });
}

function HideNotification() {
    $("#ErrorNotification").slideUp('slow');
}

/*      Google and Yahoo Converstion text  */

function GetConversionText() {

    GetYahooLeadConversionText();
    GetGoogleLeadConversionText();
}

function geturlpath() {
    var url = window.location.href;
    var path = url.split("/").pop();
    if (path == "ContactUs" || path == " ") {
        alert(path);

    }
}

function GetYahooLeadConversionText() {
    // Yahoo Inc Code for request information conversion page
    window.ysm_customData = new Object();
    window.ysm_customData.conversion = "transId=,currency=,amount=";
    var ysm_accountid = document.getElementById("hdnYahooConversionAccountID").value;
    var script = document.createElement('SCRIPT');
    script.src = '//srv3.wa.marketingsolutions.yahoo.com/script/ScriptServlet?aid=' + ysm_accountid + '';
    script.type = 'text/javascript';
    var div = document.getElementById('divYahooConversionText');
    div.appendChild(script);

}
function GetGoogleLeadConversionText() {
    document.getElementById('divGoogleConversionText').innerHTML = '';

    var google_conversion_id = document.getElementById("hdnGoogleConversionID").value;
    var google_conversion_language = document.getElementById("hdnGoogleConversionLanguage").value;
    var google_conversion_format = document.getElementById("hdnGoogleConversionFormat").value;
    var google_conversion_color = document.getElementById("hdnGoogleConversionColor").value;
    var google_conversion_label = document.getElementById("hdnGoogleConversionLabel").value;

    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://www.googleadservices.com/pagead/conversion.js';

    var noscript = "";
    noscript += "<noscript>\r\n";
    noscript += "<img height=\"1\" width=\"1\" border=\"0\" src=\"http://www.googleadservices.com/pagead/conversion/1034534148/?label=XQWtCJiHjwEQhPqm7QM&amp;guid=ON&amp;script=0\"/>\r\n";
    noscript += "</noscript>\r\n";

    var div = document.getElementById('divGoogleConversionText');
    div.appendChild(script);
    $('#divGoogleConversionText').append(noscript);

}



function SideNavTreeView() {
    $(".sidebar-nav").treeview({
        persist: "location",
        collapsed: true,
        unique: true
    });
}

function HomesCarousel() {
    $('.listings_top').jcarousel({
        itemLoadCallback: UpdateVisibleRange,
        scroll: 4,
        animation: "slow"
    });

    $('.listings_bottom').jcarousel({
        itemLoadCallback: UpdateHomesiteWaterfrontRange,
        scroll: 4,
        animation: "slow"
    });
}
function UpdateVisibleRange(carousel, state) {
    $("#listings_visible_range span").html(carousel.first + " - " + carousel.last);
}

function UpdateHomesiteWaterfrontRange(carousel, state) {
    $("#waterfront_listings_range span").html(carousel.first + " - " + carousel.last);
}

function InitNeighborhoodModal() {
    $("#ModalWindow").jqm({ modal: true });
}

function OpenNeighborhoodModal() {
    $("#ModalWindow").jqmShow();
}

function OpenMapModal(address, latitude, longitude) {
    $("#MapModalWindow").jqmShow();
    initializeMap();    
    //If latitude and Longitude are provided 
    if (latitude != null && latitude != '') {
        mapLatLong(address, latitude, longitude)
    }
    else {
        mapAddress(address)
    }

}

/* GOOGLE API for Maps*/
var geocoder;
var directionDisplay;
var directionsService;
var map;
var gRedIcon;
var gSmallShadow;
var infoWindow;


function initializeMap() {
    geocoder = new google.maps.Geocoder(); //Initializing GeoCoder
    directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer(); //Initializing Directions Renderer

    var myLatlng = new google.maps.LatLng(0, 0);
    //var myLatlng = codeAddress();
    var myOptions = {
        zoom: 8,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("mapControl"), myOptions);
    directionsDisplay.setMap(map);

    gRedIcon = new google.maps.MarkerImage(
                  "http://labs.google.com/ridefinder/images/mm_20_red.png",
                  new google.maps.Size(12, 20),
                  new google.maps.Point(0, 0),
                  new google.maps.Point(6, 20));
    gSmallShadow = new google.maps.MarkerImage(
                  "http://labs.google.com/ridefinder/images/mm_20_shadow.png",
                  new google.maps.Size(22, 20),
                  new google.maps.Point(0, 0),
                  new google.maps.Point(6, 20));


}


function codeAddress() {
    var address = $("#CommunityAddress").html().trim().replace("<br>", " ");
    mapAddress(address);
}
function mapAddress(address) {
    if (address != null) {
        $("#toAddress").val(address);

        geocoder.geocode({ 'address': address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    animation: google.maps.Animation.DROP,
                    position: results[0].geometry.location,
                    map: map
                });
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
    }
}

function mapLatLong(address, latitude, longitude) {
    if (address != null) {
        $("#toAddress").val(address);
        $("#hidlatitude").val(latitude);
        $("#hidlongitude").val(longitude);
        map.setCenter(new google.maps.LatLng(latitude, longitude));
        var marker = new google.maps.Marker({
            animation: google.maps.Animation.DROP,
            position: new google.maps.LatLng(latitude, longitude),            
            map: map
        });
        infoWindow = new google.maps.InfoWindow;
    }
}

function calcRoute() {
    initializeMap();
    var errMsg = "Google can't find the address: Please enter valid address";
    var start = document.getElementById("fromAddress").value;
    var latitude = document.getElementById("hidlatitude").value;
    var longitude = document.getElementById("hidlongitude").value;
    var end = '';
    if (latitude != null && latitude != "") {
        end = new google.maps.LatLng(latitude, longitude);
    }
    else {
        end = document.getElementById("toAddress").value;
    }
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
        else {
            alert(errMsg);
        }
    });
}


/**  Email To Friend     **/

function EmailToFriend() {
    var RegExEmail = /^(([a-z0-9]+\.)|([a-z0-9]+([_\-]{0,1}[a-z0-9])+\.))*([a-z0-9]+[_\-a-z0-9]*[a-z0-9]+)\@(([a-z0-9]+\.)|([a-z0-9]+([_\-]{0,1}[a-z0-9])+\.))*([a-z0-9]+[_\-a-z0-9]*[a-z0-9]+)\.[a-z]{2,4}$/i;
    var friendEmail = $("#txtFriendEmail").val();
    var referrerName = $("#txtName").val();
    var validationSummary;
    var isValid = true;

    if (referrerName == "") {
        alert("Please enter your name");
        isValid = false;
        $("#EmailFieldValidator").show();
    }
    else {
        $("#EmailFieldValidator").hide();
    }
    if (isValid == true) {
        if (friendEmail == "") {
            alert("Please enter your friend's email address");
            isValid = false;
            $("#RegularExpressionValidator5").show();
        }
        else {
            $("#RegularExpressionValidator5").hide();
        }

        if (!friendEmail == "") {
            if (!RegExEmail.test(friendEmail)) {
                alert("Please enter valid email address in the format: yourname@yourdomain.com");
                isValid = false;
            }
        }
    }

    if (isValid == true) {
        $.ajax({
            url: "/Account/SendEmailToFriend",
            type: "POST",
            cache: false,
            data: { FriendEmail: friendEmail, ReferrerName: referrerName },
            success: function(result) {
                $("#divFields").hide();
                $("#divMessages").show();
            }
        });
    }

    return false;
}

function InitContactForm() {
    var countryObj = $("#country");
    if (countryObj.length > 0) {
        //var country = $("#country").val();
        $("#country").change(CountrySelected);
    }
}

function CountrySelected(eventObject) {
    var selectedCountry;
    if (eventObject != null && eventObject.currentTarget != null) {
        var id = "#" + eventObject.currentTarget.id + " option:selected";
        selectedCountry = $(id).val();
    }
    else {
        selectedCountry = $("select#country option:selected").val();
    }
    if (selectedCountry != null && selectedCountry.length > 0) {
        if (selectedCountry == "United States"
            || selectedCountry == "Canada") {
            //LoadStates(selectedCountry);
        }
        else {
            //HideStates();
        }
    }
}

function LoadStates(country) {

    $.ajax({
        url: "/Lead/GetStates",
        type: "POST",
        cache: false,
        data: { Country: country },
        success: function(result) {
            if (result.isValid) {
                var options = '<option value="">--- Please choose ---</option>';
                for (var i = 0; i < result.States.length; i++) {
                    var state = result.States[i];
                    options += '<option value="' + state.Value + '">' + state.Text + "</option>";
                }
                $("#state").show();
                $("select#state").html(options);
            }
            else {
                ShowLeadNotification(result.Error);
            }
        },
        error: function() { ShowLeadNotification("Oops! This server may be misconfigured. We cannot find the list of States for this country."); }
    });

}

function HideStates() {
    $("#state").hide();
}

//On image error
function ImgError(source) {
    source.src = "/images/Residential_sm.jpg";
    source.onerror = "";
    return true;
}
