/// <reference path="../jquery-1.3.2.min-vsdoc.js" />

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() {
    /* 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");
    });
    $("#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() {
        $('#EmailMsg').html('');
        var email = $("#Email").val();
        if (email != "") {
            $('EmailMsg').html('Please enter your Email');
            return false;
        }
        else if (!isValidEmailAddress(email)) {
            $('#EmailMsg').html('Please enter a valid 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 ($("#password").val() != $("#confirmPassword").val()) {
            $("#validationConfirm").html("The passwords you've entered don't match.  Please retype them.");
            validationPass = false;
        }
        else {
            $("#validationConfirm").html("");
        }

    });

    $('.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-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;
    });


    /* 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");

    /* select package */
    setupPackagesTable();

    /* create ad */
    $(".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");
        }
    );
    $("#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();
    });
    $(".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;
    });
    $(".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).parents(".menu-cat").children(".cat-top-list").css("display", "none");
        $(this).remove();
        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);
    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", "177px").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 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) {
    $("#" + id).html(ih);
}
function setInvisible(id) {
    $("#" + id).css("display", "none")
}
function setVisible(id) {
    $("#" + id).css("display", "block")
}
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 close_alert(alID, accID){
    $.ajax({
        type: "POST",
        url: "/Account/AccountAlertClose",
        async: false,
        data: { aaid : alID, accid : accID } ,
        success: function(data) {
        }
    });
}
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 = $('#keyword').val();
    var near = $('#location').val();
    near = near.replace("city, state, or zip code", "");
    if (near.length <= 0 && want == "item") return false;
    if (want == "item") want = want.replace("item", "");
    $('#location').val(near);
    $('#keyword').val(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);
            setInvisible('ad_' + 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 sortBinsNs(bincls) {
    var li = $('#' + bincls + 'id li.refinem').get();
    var ns = li.pop();
    li.sort(function(a, b) {
        return a.innerHTML > b.innerHTML ? 1 : -1;
    });
    li.push(ns);
    $('#' + bincls + 'id').html(li);
    $('#' + bincls + 'id div.refine-more').remove();
    return false;
}

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').html(li);
    $('#' + bincls + 'id div.refine-more').remove();
    return false;
}
