﻿function intAsCurrency(value) {
    var i = parseFloat(value);
    if (isNaN(i)) { i = 0; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    //if (s.indexOf('.') < 0) { s += ',-'; }
    s = minus + s;
    return formatNumberBy3(s, null, ',');
}

function formatNumberBy3(num, decpoint, sep) {
    // check for missing parameters and use defaults if so
    if (arguments.length == 2) {
        sep = ".";
    }
    if (arguments.length == 1) {
        sep = ".";
        decpoint = ",";
    }
    // need a string for operations
    num = num.toString();
    // separate the whole number and the fraction if possible
    a = num.split(decpoint);
    x = a[0]; // decimal
    y = a[1]; // fraction
    z = "";


    if (typeof (x) != "undefined") {
        // reverse the digits. regexp works from left to right.
        for (i = x.length - 1; i >= 0; i--)
            z += x.charAt(i);
        // add seperators. but undo the trailing one, if there
        z = z.replace(/(\d{3})/g, "$1" + sep);
        if (z.slice(-sep.length) == sep)
            z = z.slice(0, -sep.length);
        x = "";
        // reverse again to get back the number
        for (i = z.length - 1; i >= 0; i--)
            x += z.charAt(i);
        // add the fraction back in, if it was there
        if (typeof (y) != "undefined" && y.length > 0)
            x += decpoint + y;
    }
    return x;
}

function formatListingUrl(listUrl) {
    var _url = listUrl.replace('/?', '+');
    return _url;
}
function reversedString(str) {
    var split = str.split('');
    split = split.reverse();
    return split.join('');
}
function getMarketCode(mp) {
    switch (mp.toLowerCase()) {
        case "autotrader":
            return "at";
        case "cars":
            return "cc";
        case "vehix":
            return "vx";
        case "ebay":
            return "eb";
        case "craigslist":
            return "cl";
        case "mota":
            return "mt";
        default:
            return "na";
    }
}
function getListingImgUrl(inum, hasThumbnail, imgUrl, vClass, mp) {
    if (hasThumbnail) {
        var str = "";
        var rinum = reversedString(inum);
        if (rinum.length > 8) {
            for (var i = 0; i < 8; i++)
                str += rinum.charAt(i) + "/";
            str += rinum.substr(8, rinum.length - 8);
        }
        return static_url + "/b/i/vp/tn/" + getMarketCode(mp) + "/" + formatListingUrl(str) + ".jpg";
    } else {
        if ($.trim(imgUrl).length > 0)
            return imgUrl;
        else {
            switch (vClass.toLowerCase()) {
                case "convertible":
                    return "../sc/i/no-photo-th-convertible.gif";
                    break;
                case "coupe":
                    return "../sc/i/no-photo-th-coupe.gif";
                    break;
                case "crew cab":
                case "extra cab":
                case "regular cab":
                case "pickup":
                    return "../sc/i/no-photo-th-pickup.gif";
                    break;
                case "hatchback":
                case "hatchback coupe":
                case "hatchback sedan":
                case "sport wagon":
                case "wagon":
                    return "../sc/i/no-photo-th-wagon.gif";
                    break;
                case "minivan":
                case "van":
                    return "../sc/i/no-photo-th-minivan.gif";
                    break;
                case "sedan":
                    return "../sc/i/no-photo-th-luxury.gif";
                    break;
                case "suv":
                case "sport utility":
                    return "../sc/i/no-photo-th-utility.gif";
                    break;
                default:
                    return "../sc/i/no-photo.gif";
                    break;
            }
        }
    }
}
function getKeyFromString(key, str) {
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex;
    regex = new RegExp("[\\/;]" + key + "=([^;#]*)");
    var qs = regex.exec(str);
    if (qs == null)
        return "";
    else
        return qs[1];
}
function upsertKeyInQueryString(key, value) {
    var _str = window.location.href;
    var _hash = window.location.hash;
    _str = _str.replace(_hash, "");
    var re = new RegExp("([?|&])" + key + "=.*?(&|$)", "i");
    if (_str.match(re))
        _str = _str.replace(re, '$1' + key + "=" + value + '$2');
    else if (_str.indexOf("?") == -1)
        _str = _str + '?' + key + "=" + value;
    else
        _str = _str + '&' + key + "=" + value;

    return _str + _hash;
}
function getKey(key, default_, fromHash) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex;
    var str = "";
    if (fromHash) {
        str = window.location.hash;
        regex = new RegExp("[\\#;]" + key + "=([^;]*)");
    }
    else {
        str = window.location.href;
        regex = new RegExp("[\\/;]" + key + "=([^;#]*)");
    }
    var qs = regex.exec(str);
    if (qs == null)
        return default_;
    else
        return qs[1];
}
function getHashKey(key) {
    var result = getKey(key, null, true);
    if (result.length > 0)
        return result;
    else
        return null;
}
function upsertHashKey(key, value) {
    var _hash = window.location.hash;
    var re = new RegExp("([?|;])" + key + "=.*?(;|$)", "i");
    if (_hash.match(re))
        _hash = _hash.replace(re, '$1' + key + "=" + value + '$2');
    else
        _hash = _hash + ';' + key + "=" + value;
    window.location.hash = _hash;
}

function upsertKey(key, value) {
    var _str = window.location.href;
    var _hash = window.location.hash;
    _str = _str.replace(_hash, "");
    var re = new RegExp("([?|;])" + key + "=.*?(;|$)", "i");
    if (_str.match(re))
        _str = _str.replace(re, '$1' + key + "=" + value + '$2');
    else
        _str = _str + ';' + key + "=" + value;

    return _str + _hash;
}

function setCookie(szName, szValue, szExpires, szPath, szDomain, bSecure) {
    var szCookieText = escape(szName) + '=' + escape(szValue);
    szCookieText += (szExpires ? '; EXPIRES=' + szExpires.toGMTString() : '');
    szCookieText += (szPath ? '; PATH=' + szPath : '');
    szCookieText += (szDomain ? '; DOMAIN=' + szDomain : '');
    szCookieText += (bSecure ? '; SECURE' : '');

    document.cookie = szCookieText;
}
function getCookie(szName) {
    var szValue = null;
    if (document.cookie)	   //only if exists
    {
        var arr = document.cookie.split((escape(szName) + '='));
        if (2 <= arr.length) {
            var arr2 = arr[1].split(';');
            szValue = unescape(arr2[0]);
        }
    }
    return szValue;
}

function deleteCookie(szName) {
    var tmp = getCookie(szName);
    if (tmp)
    { setCookie(szName, tmp, (new Date(1))); }
}
//Adds new uniqueArr values to temp array
function uniqueArr(a) {
    temp = new Array();
    for (i = 0; i < a.length; i++) {
        if (!contains(temp, a[i])) {
            temp.length += 1;
            temp[temp.length - 1] = a[i];
        }
    }
    return temp;
}

//Will check for the Uniqueness
function contains(a, e) {
    for (j = 0; j < a.length; j++) if (a[j] == e) return true;
    return false;
}

function showRecaptcha(element, themeName, tabIndex) {
    Recaptcha.create(recaptcha_key, element, {
        theme: themeName,
        tabindex: tabIndex,
        callback: null//Recaptcha.focus_response_field
    });
}

//Async loading images
function loadImage(loader) {
    var image_src = loader.attr('rev');
    var img = new Image();

    $(img)
        .load(function() {
            $(this).hide();
            loader
            .empty()
            .append(this);
            $(this).fadeIn();
        })
        .error(function() {
            //$(this).attr('src', failedImage).show(); 
        })
        .attr('src', image_src)
        .show();
}

function resizeImage(img, maxWidth, maxHeight) {
    var width = img.naturalWidth;
    var height = img.naturalHeight;
    if (!width || !height) {
        // Ooops you are an IE user, let's fix it.
        var _img = document.createElement('img');
        _img.src = img.src;

        width = _img.width;
        height = _img.height;
    }

    var pWidth = 1;
    if (maxWidth != null) {
        pWidth = width / maxWidth;
    }
    var pHeight = 1;
    if (maxHeight != null) {
        pHeight = height / maxHeight;
    }
    var reduce = 1;

    if (pWidth < pHeight) {
        reduce = pHeight;
    } else {
        reduce = pWidth;
    }

    if (reduce < 1) {
        reduce = 1;
    }

    var newWidth = width / reduce;
    var newHeight = height / reduce;

    var dim = Object();
    dim.h = newHeight;
    dim.w = newWidth;

    return dim;

}
