var genericErrorMsg = "Oops! Please wait just one moment while we get our act together. If any horses are readily available, you are free to hold them…"
                        + "If you were in the middle of a search, you can try refreshing the web browser or you can navigate back to the homepage and start again.";

var ie = (typeof window.ActiveXObject != 'undefined');
$(document).ready(function() {

    /* show carousel */
    $("#home-carousel").fadeIn('300');
    /* general */
    $(".btn-active").hover(function() {
        $(this).css("background-position", "0 -33px");
    }, function() {
        $(this).css("background-position", "0 0");
    });
    $(".btn-active").mousedown(function() {
        $(this).css("background-position", "0 -66px");
    }).mouseup(function() {
        $(this).css("background-position", "0 0");
    });
    /* binh: handling this with ajax saveAd()
    $(".save").click(function() {
    var whichLink = $(this);
    $(whichLink).removeClass("save")
    $(whichLink).addClass("saving");
    window.setTimeout(function() {
    $(whichLink).removeClass("saving");
    $(whichLink).text("Saved");
    $(whichLink).addClass("saved");
    }, 3000);
    return true;
    });
    */
    $("#send-form-cancel").click(tb_remove);
    $("a.flag").toggle(function() {
        $(this).parents(".flag-wrapper").addClass("flag-open");
        return false;
    }, function() {
        $(this).parents(".flag-wrapper").removeClass("flag-open");
        return false;
    });
    $("a.flagno").toggle(function() {
        $(".flag-wrapper").each(function() {
            $(this).removeClass("flag-open");
        });
        $(this).parents(".flag-wrapper").addClass("flag-open");
        return false;
    }, function() {
        $(this).parents(".flag-wrapper").removeClass("flag-open");
        return false;
    });
    $("a.flagno").click(function() {
        if ($(this).parents(".flag-wrapper").hasClass("flag-open")) {
            $(this).parents(".flag-wrapper").removeClass("flag-open");
        }
        {
            $(".flag-wrapper").each(function() {
                $(this).removeClass("flag-open");
            });
            $(this).parents(".flag-wrapper").addClass("flag-open");
        }
        return false;
    });
    $(".flag-buttons a").click(function() {
        $(this).parents(".flag-wrapper").removeClass("flag-open");
        return false;
    });
    $("a.chg-loc-toggle").toggle(function() {
        $(this).parents(".chg-loc-wrapper").addClass("chg-loc-open");
        if (ie) { $(".ad-sorter").css("visibility", "hidden"); }
        return false;
    }, function() {
        $(this).parents(".chg-loc-wrapper").removeClass("chg-loc-open");
        if (ie) { $(".ad-sorter").css("visibility", "visible"); }
        return false;
    });
    $(".chg-loc-buttons a").click(function() {
        $(this).parents(".chg-loc-wrapper").removeClass("chg-loc-open");
        if (ie) { $(".ad-sorter").css("visibility", "visible"); }
        return false;
    });
    $(".msg-close a").click(function() {
        $(this).parents(".msg-box").remove();
        return false;
    });

    $(".btn-back").click(function() {
        $('#btnaction').val('previous');
    });
    $(".btn-next").click(function() {
        $('#btnaction').val('next');
    });
    $(".btn-create-ad").click(function() {
        $('#btnaction').val('next');
    });
    $(".btn-checkout").click(function() {
        $('#btnaction').val('next');
    });
    $(".btn_savechanges").click(function() {
        $('#btnaction').val('SaveChanges');
    });
    $(".btn-ad-complete").click(function() {
        $('#btnaction').val('PreviewComplete');
    });
    $(".btn-ad-back").click(function() {
        $('#btnaction').val('PreviewBack');
    });
    $(".recoverpwd-btn").click(function() {
        document.getElementById("EmailMsg").innerHTML = "";
        var email = $("#Email").val();
        if (email != "") {
            if (!isValidEmailAddress(email)) {
                document.getElementById("EmailMsg").innerHTML = "Please enter a valid Email";
                //$("#EmailMsg").val("Please enter a valid Email");
                return false;
            }
        }
        else {
            document.getElementById("EmailMsg").innerHTML = "Please enter your Email";
            //$("EmailMsg").val("Please enter your Email");
            return false;
        }
    });
    /* search results/ad listing */
    //****************************************** Register View Validation **********************************************
    $("#btnRegister").click(function() {
        var emailRegEx = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
        var zipRegEx = /^\d{5}$/;
        var phoneAreaCodeRegEx = /^\d{3}$/;
        var phonePrefixRegEx = /^\d{3}$/;
        var phoneSuffixRegEx = /^\d{4}$/;
        var passwordRegEx = /^(?=.*\d)(?=.*[A-Za-z]).{6,32}$/

        var validationPass = true;

        //Validate password and confirm match
        if (document.getElementById("password").value != document.getElementById("confirmPassword").value) {
            document.getElementById("validationConfirm").innerHTML = "The passwords you've entered don't match.  Please retype them.";
            validationPass = false;
        }
        else {
            document.getElementById("validationConfirm").innerHTML = "";
        }

    });

    //logon page
    //    $('.logonpassword').keyup(function(e) {
    //        var radiobuttons = document.forms[0].accountExist;
    //        if ($('.logonpassword').val() != '') {
    //            radiobuttons[1].checked = true;
    //        }
    //        else {
    //            radiobuttons[0].checked = true;
    //        }
    //    });
    $('.logonpassword').focus(function(e) {
        var radiobuttons = document.forms[0].accountExist;
        radiobuttons[1].checked = true;
        radiobuttons[0].checked = false;
    });
    $('#login').focus(function(e) {
        var radiobuttons = document.forms[0].accountExist;
        if (document.forms[0].accountExist) {
            radiobuttons[1].checked = true;
            radiobuttons[0].checked = false;
        }
    });
    //**************************************************************************************************

    $(".single-ad").mouseover(function() {
        $(this).addClass("ad-hover");
    }).mouseout(function() {
        $(this).removeClass("ad-hover");
    });
    $(".ad-summary").mouseover(function() {
        $(this).addClass("ad-hover");
    }).mouseout(function() {
        $(this).removeClass("ad-hover");
    });
    $(".attributes li").mouseover(function() {
        $(this).prev("li").addClass("before");
    }).mouseout(function() {
        $(this).prev("li").removeClass("before");
    });
    $("#banner-bar input:text").focus(function() {
        $(this).addClass("active");
        var box = $(this).attr("id");
        var val = $(this).val();
        if ((box == "keyword" && val == "item") || (box == "location" && val == "city, state, or zip code")) {
            $(this).val("");
        }
    });
    $("#refine-location-slider label").css("display", "none");
    $("#refine-location-slider").slider({
        value: 6,
        min: 0,
        max: 6,
        step: 1,
        change: function(evt, ui) {
            if (ui.value == 0) ui.value = 1;
            var item = document.getElementById('locationSlider_' + ui.value);
            if (item != null)
                document.location = item.value;
        }
    });
    $(".refine-set label").click(function() {
        var thisSet = $(this).parent(".refine-set");
        if ($(thisSet).hasClass("open")) {
            $(thisSet).removeClass("open");
        } else {
            $(thisSet).addClass("open");
        }
    });
    $(".refine-more-toggle").click(function() {
        var set = $(this).parent(".refine-more");
        if ($(set).hasClass("refine-open")) {
            $(set).removeClass("refine-open");
        } else {
            $(set).addClass("refine-open");
            $(this).remove();
        }
        return false;
    });
    $("#show-more-extras a").click(function() {
        if ($(this).hasClass("show-more")) {
            $(this).removeClass("show-more");
            $(".preview-more-extras").css("display", "none");
        } else {
            $(this).addClass("show-more");
            $(".preview-more-extras").css("display", "block");
        }
        return false;
    });
    $(".check-all-ads").click(function() {
        if ($(this).hasClass("all-checked")) {
            $(".ad-list input:checkbox").attr("checked", "");
            $(".check-all-ads").text("Select all ads");
            $(this).removeClass("all-checked");
            $(".clear-ads-button").attr("src", "images/btn-clear-selected-ads-inactive.png").attr("disabled", "disabled");
        } else {
            $(".ad-list input:checkbox").attr("checked", "checked");
            $(".check-all-ads").text("Deselect all ads");
            $(this).addClass("all-checked");
            $(".clear-ads-button").attr("src", "images/btn-clear-selected-ads-active.png").attr("disabled", "");
        }
        return false;
    });
    $(".ad-checkbox").click(function() {
        var checkedInputs = $(".ad-list input:checked").length;
        if (checkedInputs == 0) {
            $(".clear-ads-button").attr("src", "images/btn-clear-selected-ads-inactive.png").attr("disabled", "disabled");
        } else {
            $(".clear-ads-button").attr("src", "images/btn-clear-selected-ads-active.png").attr("disabled", "");
        }
    });
    $("#show-active-ads").click(function() {
        if ($(this).hasClass("hide-expired")) {
            $(".ad-list div.ad-expired").css("display", "block");
            $(this).text("Show only active ads");
            $(this).removeClass("hide-expired");
        } else {
            $(".ad-list div.ad-expired").css("display", "none")
            $(this).text("Show all ads");
            $(this).addClass("hide-expired");
        }
        return false;
    });
    /* ad process */
    $("#preview-highlight").click(function() {
        if ($(this).hasClass("added")) {
            $(".single-ad").removeClass("ad-highlight");
            $(this).removeClass("added");
            $(this).text("Add this for $5");
            update_price(-5);
        } else {
            $(".single-ad").addClass("ad-highlight");
            $(this).addClass("added");
            $(this).text("Remove from your ad");
            update_price(5);
        }
        return false;
    });
    $("#preview-zoom").click(function() {
        if ($(this).hasClass("added")) {
            $("a.ad-zoom").css("display", "none");
            $(this).removeClass("added");
            $(this).text("Add this for $5");
            update_price(-5);
        } else {
            $("a.ad-zoom").css("display", "block");
            $(this).addClass("added");
            $(this).text("Remove from your ad");
            update_price(5);
        }
        return false;
    });
    $(".package-btn").click(function() {
        var pkgPrice = parseFloat($(this).val());
        var currPkgPrice = $(".current-price").text();
        if (currPkgPrice != "0.00") {
            $(".current-price").text("0.00");
        }
        $(".package-btn").attr("src", "/Images/btn-select.png").attr("alt", "Select");
        $(this).attr("src", "/Images/btn-selected.png");
        update_price(pkgPrice);

        var rateregionid = document.getElementById('PackageID');
        rateregionid.value = $(this).attr('id');
        $("#btnCreateAd").css("background-position", "0 0");
        $("#btnCreateAd").removeAttr("disabled");

        return false;
    });

    /* help */
    $(".question").click(function() {
        $(this).next(".answer").slideToggle("normal");
        return false;
    });
    $(".close-answer").click(function() {
        $(this).parents(".answer").slideToggle("normal");
        return false;
    });
    $("#top-questions li a").click(function() {
        var whichQ = $(this).attr("href");
        $(whichQ).children(".answer").slideToggle("normal");
    });
    /* ad detail */
    $("#thumb-current").text("1");
    var thumbsTotal = $("#ad-carousel li").length;
    $("#thumb-total").text(thumbsTotal);
    $("#ad-carousel").jcarousel({scroll: 2});
    $("#ad-carousel li a").click(function() {
        var parentLI = $(this).parents("li").prevAll().length;
        var rank = parentLI + 1;
        $("#thumb-current").text(rank);
        var newImg = $(this).attr("href");
        $("#ad-large-image img").attr({ src: newImg });
        return false;
    });
    /* select package */
    setupPackagesTable();

    /* create ad */
    // date picker ... be sure to update the image path for the calendar icon
    $(".datepicker").datepicker({ showOn: 'both', buttonImage: '/images/icn-calendar-16.png', buttonImageOnly: true });
    $(".text-max-50").attr("maxlength", "50");
    $(".text-max-150").attr("maxlength", "150");
    $(".text-max-140").attr("maxlength", "140");
    $(".text-max-900").attr("maxlength", "900");
    $(".create-ad-make-main").hover(
        function() {
            $(this).parents(".create-ad-photo").addClass("photo-hover");
        },
        function() {
            $(this).parents(".create-ad-photo").removeClass("photo-hover");
        }
    );


    $(".text-max-25").show_char_limit(25, {
        status_element_suffix: "-status",
        error_element_suffix: "-status",
        error_class: "char-error"
    });
    //    $("#onlinetext").show_char_limit({
    //        status_element_suffix: "-status",
    //        error_element_suffix: "-status",
    //        error_class: "char-error"
    //    });
    $("#onlinetext").keyup(function() {
        onlinecharlimit($("#maxOnlineChar").val(), "infoonline");
    });
    $("#printtext").keyup(function() {
        printcharlimit($("#maxPrintChar").val(), "infoprint");
    });
    $("#dyn_phone").keyup(function() {
        printcharlimit($("#maxPrintChar").val(), "infoprint");
        buildtext();
    });
    $("#chk_hidephone").change(function() {
        buildtext();
        //        onlinecharlimit($("#maxOnlineChar").val(), "infoonline");
        //        printcharlimit($("#maxPrintChar").val(), "infoprint");
    });
    //    $(".dyninp").mouseup(function() {
    //        onlinecharlimit($("#maxOnlineChar").val(), "infoonline");
    //        printcharlimit($("#maxPrintChar").val(), "infoprint");
    //    });
    $(".dyninp").change(function() {
        onlinecharlimit($("#maxOnlineChar").val(), "infoonline");
        printcharlimit($("#maxPrintChar").val(), "infoprint");
    });
    $(".dyninp").keyup(function() {
        onlinecharlimit($("#maxOnlineChar").val(), "infoonline");
        printcharlimit($("#maxPrintChar").val(), "infoprint");
    });
    $("#copy-ad-text").click(function() {
        var printDesc = "";
        if ($('#printleadin'))
            printDesc += $('#printleadin').val() + " ";
        printDesc += $("#printtext").val();
        if ($('#printleadout'))
            printDesc += " " + $('#printleadout').val();
        $("#onlinetext").val(printDesc);
        onlinecharlimit($("#maxOnlineChar").val(), "infoonline");

        return false;
    });
    $(".inline-help-toggle").click(function() {
        var parentHeight = $(this).parents("div").height();
        var whichHelp = $(this).attr("href");
        var thisTop = parentHeight - 10;
        $(whichHelp).css("top", thisTop);
        $(whichHelp).toggle("normal");
        return false;
    });
    $(".create-ad-make-main a").click(function() {
        $(".active-main").text("Make main photo").removeClass("active-main");
        $(this).addClass("active-main");
        $(this).text("Main photo");
        return false;
    });
    /* home page */
    //    $(".menu-cat h3").click(function() {
    //        $(this).parents(".menu-cat").toggleClass("cat-open");
    //        return false;
    //    });
    /* new 09-02-2009 */
    $(".cat-toggle").click(function() {
        $(this).parents(".menu-cat").toggleClass("cat-open");
        return false;
    });
    $(".cat-more-toggle").click(function() {
        $(this).siblings(".cat-more").css("display", "block");
        $(this).remove();
        return false;
    });
    $("#home-carousel").jcarousel({
        auto: 5,
        scroll: 1,
        wrap: 'last',
        initCallback: homecarousel_initCallback
    });
    //    $(".ad-5-photos").click(function() {
    //        update_price(20);
    //        return false;
    //    });

});

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    //\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
    //var pattern= "^[a-z0-9_\+-]+(\.[a-z0-9_\+-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,4})$"; 
    return pattern.test(emailAddress);
}
function setupPackagesTable() {
    var cols = $(".packages-table .column-head").length;
    if (cols == 4) {
        $(".packages-table .column-head").css("width", "127px");
        $(".recommended-notice").css("width", "127px");
    } else if (cols == 3) {
        $(".packages-table .column-head").css("width", "188px");
        $(".recommended-notice").css("width", "176px").addClass("three-col");
    } else if (cols == 2) {
        $(".packages-table .column-head").css("width", "283px");
        $(".recommended-notice").css("width", "271px").addClass("two-col");
    } else if (cols == 1) {
        $(".packages-table .column-head").css("width", "567px");
        $(".recommended-notice").css("width", "567px");
    };
}
function homecarousel_initCallback(carousel) {
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });
    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};
function update_price(addThis) {
    var currPrice = parseFloat($(".current-price").text());
    var newPrice = parseFloat(currPrice + parseFloat(addThis));
    var newPrice = Math.round(newPrice * 100) / 100;
    var newPrice = newPrice.toFixed(2);
    $(".current-price").text(newPrice);
}
function setClass(id,cls) {
    var el = document.getElementById(id);
    if (el == null) return;
    el.className = cls;
}
function setInnerHTML(id, ih) {
    var el = document.getElementById(id);
    if (el == null) return;
    el.innerHTML = ih;
}
function setInvisible(id) {
    var el = document.getElementById(id);
    if (el == null) return;
    el.style.display = "none"; //false;
}
function setVisible(id) {
    var el = document.getElementById(id);
    if (el == null) return;
    el.style.display = "block"; //false;
}
function clickedCancel(accID, adID, prrIDs) {
    var ids = prrIDs.split(",");
    var prrIDsChecked = "";
    for (var i = 0; i < ids.length; i++) {
        var chkBox = document.getElementById(ids[i]);
        if (chkBox != null && chkBox.checked) {
            var subid = ids[i].split("_");
            prrIDsChecked += subid[2] + ",";
        }
    }
        
    var dataString =
                    'accID=' + accID.toString() +
                    '&adID=' + adID.toString() +
                    '&prrIDs=' + prrIDsChecked;
    $.ajax({
        type: "POST",
        url: "/Account/ManageAd",
        async: false,
        data: dataString,
        dataType: 'json',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert(genericErrorMsg);
        },
        success: function(data, textStatus) {
            setInvisible("cancelAdWrapper_" + adID);
        }
    });
}

function onSortResult(opt) {
    //var sortbySel = document.getElementById("sortbySel");
    if (opt != null && opt.value != null && opt.selectedIndex >= 0) {
        document.location = opt.value;

    }
}

function onSearchSubmit() {        

    var want = document.getElementById('keyword').value;
    var near = document.getElementById('location').value;
    near = near.replace("city, state, or zip code", "");
    if (near.length <= 0 && want == "item") return false;
    if(want == "item") want = want.replace("item", "");
    document.getElementById('location').value = near;
    document.getElementById('keyword').value = want;
    return true;       
}

function onFlagAd(id,flagIds) {
    var ids = flagIds.split(",");
    var idsChecked = "";
    for (var i = 0; i < ids.length; i++) {
        var chkBox = document.getElementById('flagad_'+ids[i]);
        if (chkBox != null && chkBox.checked) {
            var subid = ids[i].split("_");
            idsChecked += subid[1] + "|";
        }
    }
    if (idsChecked == "") return false;
        
    var dataString =
                    'id=' + id.toString() +
                    '&reasons=' + idsChecked;
    $.ajax({
        type: "GET",
        url: "/Details/"+id+"?ajax=flag",
        async: false,
        data: dataString,
        dataType: 'json',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert(genericErrorMsg);
        },
        success: function(data, textStatus) {
        adFlag("/Details/" + id + "?ajax=flag", id);
            //hides the div that contains flaging logic/code
            setInvisible('ad_flag_' + id);
          //  setInvisible('ad1_' + id);
        }
    });
    
}

function onSaveAd(id) {
    var itemID = 'savead_' + id;
    setClass(itemID, "saving");
    var dataString =
                    'id=' + id;

    $.ajax({
        type: "GET",
        url: "/Details/" + id + "?ajax=savead",
        async: false,
        data: dataString,
        dataType: 'json',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(genericErrorMsg);
        },
        success: function(data, textStatus) {
            adSave("/Details/" + id + "?ajax=savead", id);
            setClass(itemID, "saved");
            setInnerHTML(itemID, "Saved");
            
        }
    });
    return false;
}
function viewedDealer(dealerID, actionID) {
    $.ajax({
        type: "GET",
        url: "/Viewed/Dealer/" + dealerID + "?actid=" + actionID,
        dataType: 'json',
        success: function(data, textStatus) {
        }
    });
}
function viewedAd(adID, actionID) {
    $.ajax({
        type: "GET",
        url: "/Viewed/Ad/" + adID + "?actid=" + actionID,
        dataType: 'json',
        success: function(data, textStatus) {
        }
    });
}
function filterphonenumber() {
    var temp = $('#dyn_phone').val();
    var result = '';
    for (var i = 0; i < temp.length; i++) {

        if (isDigit(temp[i])) {
            result += temp[i];
        }
    }
    $('#dyn_phone').val(result);
}
function isDigit(c) {
    return ((c >= "0") && (c <= "9"))
}
function sortBins(bincls) {
    var li = $('#' + bincls + 'id li.refinem').get();
    li.sort(function(a, b) {
        return a.innerHTML > b.innerHTML ? 1 : -1;
    });
    $('#' + bincls + 'id').html('');

    $('#' + bincls + 'id').append(li);
    $('#' + bincls + 'id div.refine-more').html('');
    return false;
}