﻿

String.prototype.trim = function () {
    var str = this.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
};

// http://stackoverflow.com/questions/1718878/convert-to-currency-format
// Tyler Allen modified the code to allow for proper formatting of trailing decimal places that contain 0.
Number.prototype.toCurrency = function ($O) { // extending Number prototype

    String.prototype.separate_thousands = function () { // Thousands separation
        $val = this;
        var rx = new RegExp('(-?[0-9]+)([0-9]{3})');
        while (rx.test($val)) { $val = $val.replace(rx, '$1' + $O.thousands_separator + '$2'); }
        return $val;
    }

    Number.prototype.toFixed = function () { // Rounding
        var m = Math.pow(10, $O.use_fractions.fractions);
        return Math.round(this * m, 0) / m;
    }

    String.prototype.times = function (by) { // String multiplication
        by = (by >> 0);
        var t = (by > 1 ? this.times(by / 2) : '');
        return t + (by % 2 ? t + this : t);
    }

    var $A = this;

    /* I like to keep all options, as the name would sugesst, **optional** :) so, let me make tham as such */
    $O ? null : $O = new Object;
    /* If no thousands_separator is present default to "," */
    $O.thousands_separator ? null : $O.thousands_separator = ",";
    /* If no currency_symbol is present default to "$" */
    $O.currency_symbol ? null : $O.currency_symbol = "$";

    // Fractions use is separated, just in case you don't want them
    if ($O.use_fractions) {
        $O.use_fractions.fractions ? null : $O.use_fractions.fractions = 2;
        $O.use_fractions.fraction_separator ? null : $O.use_fractions.fraction_separator = ".";
    } else {
        $O.use_fractions = new Object;
        $O.use_fractions.fractions = 0;
        $O.use_fractions.fraction_separator = " ";
    }
    // We round this number
    $A.round = $A.toFixed();

    // We convert rounded Number to String and split it to integrer and fractions
    $A.arr = ($A.round + "").split(".");
    // First part is an integrer
    $A._int = $A.arr[0].separate_thousands();
    // Second part, if exists, are rounded decimals
    $A.arr[1] == undefined ? $A._dec = $O.use_fractions.fraction_separator + "0".times($O.use_fractions.fractions) : $A._dec = $O.use_fractions.fraction_separator + $A.arr[1] + "0".times($O.use_fractions.fractions - $A.arr[1].length);

    /* If no symbol_position is present, default to "front" */
    $O.symbol_position ? null : $O.symbol_position = "front";
    $O.symbol_position == "front" ? $A.ret = $O.currency_symbol + $A._int + $A._dec : $A.ret = $A._int + $A._dec + " " + $O.currency_symbol;
    return $A.ret;
}

$("document").ready(function () {

    $.ajaxSetup({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });

    $(".box").addClass("box_border box_gradient box_round");

    $('.favorite-link').click(function () {
        saveFav($(this));
    });

    $('#search_image').click(function () {
        var query = $(this).siblings('#query').val();
        var placeholder = $(this).siblings('#query').attr('placeholder');

        if (query === placeholder) {
            $(this).siblings('#query').val('');
        }
        $(this).parents('form').submit();
    });
    //    $("address").each(function (index) {
    //        var address = $(this);
    //        setZipcodeAddress(address);
    //    });

    //validation default
    jQuery.validator.setDefaults({
        errorElement: "span",
        errorPlacement: function (error, element) {
            error.appendTo(element.prev("label"));
        }
    });
    //validation extensions
    //Zipcode
    jQuery.validator.addMethod("postalCode", function (postalcode, element) {
        return this.optional(element) || postalcode.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnpstvxy]{1}\d{1}[A-Za-z]{1} ?\d{1}[A-Za-z]{1}\d{1})$/);
    }, "Please specify a valid postal/zip code");
    //US Phone #
    jQuery.validator.addMethod("phoneUS", function (phone_number, element) {
        phone_number = phone_number.replace(/\s+/g, "");
        return this.optional(element) || phone_number.length > 9 &&
		phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
    }, "Please specify a valid phone number");
    //US Currency
    jQuery.validator.addMethod("currencyUS", function (currency, element) {
        currency = currency.replace(/\s+/g, "");
        return this.optional(element) || currency.match(/^\$?[0-9][0-9]{0,2}(,[0-9]{3})*(\.[0-9]{2})?$/); 

    }, "Please specify a valid $ amount");

});

//function setZipcodeAddress(address) {
//    var zipCode = address.html();
//    var data = { Zipcode: zipCode };
//    $.ajax({
//        url: "/static/services/shared/service.asmx/GetAddressInfo",
//        data: $.toJSON(data),
//        success: function (msg) {
//            address.html(msg.d.City + ", " + msg.d.StateProvince + " " + msg.d.ZipCode);
//        }
//    });
//}


function saveFav(sender) {
    var listingKey = sender.attr('listingkey');
    var userKey = getUserKey();

    var favUrl = "/user/SaveFavorite?userKey=" + userKey + "&listingKey=" + listingKey;
    $.ajax({
        url: favUrl,
        success: function (jsonData) {
            if (jsonData.success) {            
                if (sender.children('img').length) {
                    sender.children('img').attr('src', "/static/img/icons/accept.png");
                    sender.attr('title', $('#fav_success').text().trim());
                }
                else {
                    sender.text($("#fav_success").text());
                    sender.addClass('saved');
                }
            }
        },
        error: function (jsonData) {
            $("#fav_fail").dialog({
                closeOnEscape: true,
                draggable: false,
                modal: true,
                resizable: false
            });
        }
    });
}

function styleFavorites() {
    var userKey = getUserKey();
    if (userKey) {
        //get favs from database
        $.ajax({
            url: '/user/userfavorites?userKey=' + userKey,
            success: function (jsonData) {
                if (jsonData.length > 0) {
                    $.each(jsonData, function (index, listing) {
                        var favLink = $('.favorite-link[listingKey=' + listing + ']');
                        if (!favLink.hasClass('saved')) {
                            favLink.addClass('saved');
                            favLink.text($("#fav_success").text());
                        }
                    });
                }
            },
            error: function (jsonData) {
                //alert("Problem retrieving favorites.");
            }
        });
    }
    else {
        //anonymous - get favs from cookie
        var favs = $.cookie("Favs");

        if (favs) {
            $.each($('.favorite-link'), function (index, listing) {
                var listingKey = $(this).attr("listingkey");
                if (contains(favs, listingKey)) {
                    var favLink = $(this);

                    if (!favLink.hasClass('saved')) {
                        favLink.addClass('saved');
                        favLink.text($("#fav_success").text());
                    }
                }
            });

        }
    }
}

function contains(string, subString) {
    return (string.indexOf(subString) != -1);
}

function isEmpty(val) {
    return val.length === 0;
}

function isNumericOrEmpty(n) {
    return isEmpty(n)|| (n.length > 0 && isNumeric(n));
}

function isNumeric(n) {
    n = n.replace( /,/ , "."); //replace commas with periods
    return !isNaN(parseFloat(n)) && isFinite(n);
}

function validZipcode(zip) {
    var zipRegEx = /^\d{5}$/;

    return isNumeric(zip) && zipRegEx.test(zip);
}

$.fn.digits = function() {
    return this.each(function() {
        $(this).text($(this).text().replace( /(\d)(?=(\d\d\d)+(?!\d))/g , "$1,"));
    });
};

function ClearDropDown(ddl, type) {
    ddl.empty();
    if (type != "") {
        PrependDefaultOption(ddl, type);
    }
}

function PopulateDropDown(ddl, type, data) {
    ddl.empty();

    if (type != "") {
        PrependDefaultOption(ddl, type);
    }

    $.each(data, function (index, optionData) {
        ddl.append("<option value='"
            + optionData.Value
            + "'>" + optionData.Text
            + "</option>");
    });

    if (type != "") {
        ddl.val("");
    }
}
