// truncates a string to a specified length applying "..." at the end if needed
function truncate_string(s,len) {
    t_s = s;
    if (t_s.length > len) {
        t_s = t_s.substring(0, len);
        try {
            if (s.substring(t_s.length, t_s.length + 1) != " ") {
                idx_last_space = t_s.lastIndexOf(" ");
                if (idx_last_space != -1) {
                    t_s = t_s.substring(0, idx_last_space);
                }
            }
        }
        catch (e) { }
    }

    if (s.length > len) {
        t_s += "...";
    }
    return t_s;
};


// formats a datetime into a short date with time ("1/1/2009 9:00 AM")
function format_datetime(dt) {
    var strAM = 'AM';
    var strMin;
    var strSec;
    var strDte = ''

    strDte = (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
    strDte += '<br/>';

    if (dt.getHours() - 12 > 0) {
        strAM = 'PM';
        strDte += (dt.getHours() - 12);
    } else {
        if (dt.getHours() == "0") {
            strDte += "12";
        } else {
            strDte += dt.getHours();
        }
    }

    if (dt.getSeconds() < 10) {
        strSec = '0' + dt.getSeconds();
    } else {
        strSec = dt.getSeconds();
    }

    if (dt.getMinutes() < 10) {
        strMin = '0' + dt.getMinutes();
    } else {
        strMin = dt.getMinutes()
    }

    strDte += ':' + strMin + ' ' + strAM;
    return strDte;
};


// produces an elaped time message from the datetime passed ("2 days 35 mins ago")
function make_elapsed_time(dt) {
    if (dt.getFullYear() == "1900") {
        return "never"
    }

    var now = new Date();
    var mins = Math.round((now.getTime() - dt.getTime()) / 60000); // 60000 ms in a minute
    var hrs = 0;
    var days = 0;
    
    // determine proper hrs
    if (mins >= 60) {
        hrs = Math.floor(mins / 60);
        mins = Math.floor(mins - (hrs * 60));
    }

    // determine proper days
    if (hrs >= 24) {
        days = Math.floor(hrs / 24);
        hrs = Math.floor(hrs - (days * 24));
    }

    var day_msg = " days";
    var hr_msg = " hrs";
    var min_msg = " mins";

    var msg_parts = new Array();
    var formatted_elapsed_time = "";

    // set days part
    if (days > 0) {
        if (days == 1) {
            day_msg = day_msg.replace("s", "");
        }
        else if (days >= 90) {
            // if the date is older than 90 days ago
            // just show a typical formatted date
            return format_datetime(dt);
        }
        msg_parts[0] = days + day_msg;
    }
    // set hours part
    if (hrs > 0) {
        if (hrs == 1) {
            hr_msg = hr_msg.replace("s", "");
        }
        msg_parts[1] = hrs + hr_msg;
    }
    // set minutes part
    if (mins > 0) {
        if (mins == 1) {
            min_msg = min_msg.replace("s", "");
        }
        msg_parts[2] = mins + min_msg;
    }

    formatted_elapsed_time = msg_parts.join(" ");

    // if they're all zero set a better message
    if (formatted_elapsed_time.replace(" ", "") == "") {
        formatted_elapsed_time = "a moment";
    }

    return formatted_elapsed_time + " ago";
}

function format_currency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
        cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

function format_checked_attr(bool) {
    return (bool) ? "checked='checked'" : "";
}

function get_table_checks(tbl_id) {
    chks = new Array();
    index = 0;
    $('#' + tbl_id + ' > tbody input[type=\'checkbox\']').each(function() {
        if ($(this)[0].checked) {
            chks[index] = $(this).attr('value');
            index++;
        }
    });
    return chks;
}


//
// Overall SiteWrench javascript namespace
//
sw = {
    setup_site_search: function(field_id, btn_id) {
        $("#" + btn_id).click(function() {
            val = $("#" + field_id)[0].value;
            if (val != "") {
                window.location = "/searchresults.aspx?s=" + escape(val);
            }
            return false;
        });
        $("#" + field_id).click(function() { $(this)[0].value = ""; });
    },
    setup_list_signup: function(field_id, btn_id) {
        $("#" + btn_id).click(function() {
            val = $("#" + field_id)[0].value;
            if (val != "") {
                window.location = "/signup.aspx?e=" + escape(val);
            }
            return false;
        });
        $("#" + field_id).click(function() { $(this)[0].value = ""; });
    },
    locator_map: function(pp_id) {
        util.load("/javascripts/locator-map.js");
        if (pp_id != "") {
            if (GBrowserIsCompatible()) {
                PublicSiteServices.LocatorMap_getData(pp_id, function(ajax_item) {
                    if (!util.is_ajax_error(ajax_item)) {
                        // render map if there is no error
                        locator_map.setup(ajax_item);
                    }
                });
            }
        }
    },
    file_cabinet: function(pp_id, token) {
        util.load("/javascripts/file-cabinet.js");
        if (pp_id != "") {
            PublicSiteServices.FileCabinet_getData(pp_id, token, function(ajax_item) {
                if (!util.is_ajax_error(ajax_item)) {
                    // render file cabinet if there is no error
                    file_cabinet.setup(ajax_item, token);
                }
            });
        }
    }
}

//
// SiteWrench utility javascript namespace
//
util = {
    load: function(path) {
        html_doc = document.getElementsByTagName('head').item(0);
        js = document.createElement('script');
        js.setAttribute('language', 'javascript');
        js.setAttribute('type', 'text/javascript');
        js.setAttribute('src', path);
        html_doc.appendChild(js);
        return false;
    },
    is_ajax_error: function(ajax_item) {
        var strErr = '';
        var intIndex = 0;

        if (ajax_item.IsError) {
            for (intIndex = 0; intIndex <= ajax_item.Errors.length - 1; intIndex++) {
                strErr += '- ' + ajax_item.Errors[intIndex] + '\n';
            }
            alert(strErr);
            return true;
        }

        return false;
    },
    clean_for_int: function(val) {
        reg = /[^\d]/gi;
        val = val.toString();
        return val.replace(reg, "");
    },
    clean_for_decimal: function(val, allow_neg) {
        if (allow_neg) reg = /[^\d\.-]/gi;
        else reg = /[^\d\.]/gi;
        val = val.toString();
        return val.replace(reg, "");
    },
    clean_for_slug: function(val) {
        reg = /[^a-zA-Z|\d\-_]/gi;
        return val.replace(reg, "");
    },
    clean_for_subdomain: function(val) {
        reg = /[^a-zA-Z|\d]/gi;
        return val.replace(reg, "");
    },
    round_number: function(num, dec) {
        var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
        return result;
    },
    get_table_checks: function(tbl_id) {
        chks = new Array();
        index = 0;
        $('#' + tbl_id + ' > tbody input[type=\'checkbox\']').each(function() {
            if ($(this)[0].checked) {
                chks[index] = $(this).attr('value');
                index++;
            }
        });
        return chks;
    },
    format_percentage: function(val) {
        val = util.clean_for_decimal(val, true);
        if (val > 0) {
            return util.round_number((val * 100), 2).toString() + " %";
        }
        else {
            return "0 %";
        }
    },
    format_datetime: function(dt, include_time) {
        var strAM = 'AM';
        var strMin;
        var strSec;
        var strDte = ''

        strDte = (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();

        if (include_time) {
            strDte += '<br/>';
            strDte += util.format_time(dt);
        }

        return strDte;
    },
    format_time: function(dt) {
        var strAM = 'am';
        var strMin;
        var strSec;
        var strDte = '';
        if (dt.getHours() - 12 > 0) {
            strAM = 'pm';
            strDte += (dt.getHours() - 12);
        } else {
            if (dt.getHours() == "0") {
                strDte += "12";
            } else {
                strDte += dt.getHours();
            }
        }

        if (dt.getSeconds() < 10) {
            strSec = '0' + dt.getSeconds();
        } else {
            strSec = dt.getSeconds();
        }

        if (dt.getMinutes() < 10) {
            strMin = '0' + dt.getMinutes();
        } else {
            strMin = dt.getMinutes()
        }

        strDte += ':' + strMin + ' ' + strAM;
        return strDte;
    },
    format_currency: function(num) {
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num))
            num = "0";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num * 100 + 0.50000000001);
        cents = num % 100;
        num = Math.floor(num / 100).toString();
        if (cents < 10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
        return (((sign) ? '' : '-') + '$' + num + '.' + cents);
    },
    format_filesize: function(size) {
        if (size < 1048576) {
            if (size == 0) return "-";
            return util.round_number(size * 0.001, 2) + " KB";
        }
        else
            return util.round_number(size / 1048576, 2) + " MB";
    },
    round_number: function(num, dec) {
	    return Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
    },
    contenttype_data: function(type) {
        types = [];
        types[0] = { content_type: "image/jpeg", name: "JPG image", icon: "" };
        types[1] = { content_type: "image/jpg", name: "JPG image", icon: "" };
        types[2] = { content_type: "image/gif", name: "GIF image", icon: "" };
        types[3] = { content_type: "image/png", name: "PNG image", icon: "" };
        types[4] = { content_type: "image/bmp", name: "BMP image", icon: "" };
        types[5] = { content_type: "image/tiff", name: "TIFF image", icon: "" };
        types[6] = { content_type: "audio/mpeg", name: "Audio file", icon: "/sitefiles/global/images/file_audio.jpg" };
        types[7] = { content_type: "audio/x-aiff", name: "Audio file", icon: "/sitefiles/global/images/file_audio.jpg" };
        types[8] = { content_type: "audio/x-wav", name: "Audio file", icon: "/sitefiles/global/images/file_audio.jpg" };
        types[9] = { content_type: "application/zip", name: "ZIP file", icon: "/sitefiles/global/images/file_zip.jpg" };
        types[10] = { content_type: "application/rar", name: "RAR file", icon: "/sitefiles/global/images/file_rar.jpg" };
        types[11] = { content_type: "application/vnd.ms-excel", name: "EXCEL document", icon: "/sitefiles/global/images/file_excel.jpg" };
        types[12] = { content_type: "application/msword", name: "WORD document", icon: "/sitefiles/global/images/file_word.png" };
        types[13] = { content_type: "application/vnd.ms-powerpoint", name: "POWERPOINT document", icon: "/sitefiles/global/images/file_powerpoint.jpg" };
        types[14] = { content_type: "application/pdf", name: "PDF", icon: "/sitefiles/global/images/file_pdf.png" };
        types[15] = { content_type: "text/plain", name: "Text file", icon: "/sitefiles/global/images/file_txt.jpg" };
        types[16] = { content_type: "text/html", name: "HTML file", icon: "/sitefiles/global/images/file_html.jpg" };
        types[17] = { content_type: "text/css", name: "CSS file", icon: "/sitefiles/global/images/file_css.jpg" };
        types[18] = { content_type: "application/rtf", name: "Richtext file", icon: "/sitefiles/global/images/file_richtext.jpg" };
        types[19] = { content_type: "video/mpeg", name: "Video file", icon: "/sitefiles/global/images/file_video.jpg" };
        types[20] = { content_type: "video/x-m4v", name: "Video file", icon: "/sitefiles/global/images/file_video.jpg" };
        types[21] = { content_type: "video/quicktime", name: "Video file", icon: "/sitefiles/global/images/file_video.jpg" };
        types[22] = { content_type: "video/x-msvideo", name: "Video file", icon: "/sitefiles/global/images/file_video.jpg" };
        types[23] = { content_type: "", name: "Folder", icon: "/sitefiles/global/images/file_folder.jpg" };
        types[24] = { content_type: "-", name: "Unknown file", icon: "/sitefiles/global/images/file_unknown.jpg" };

        for (var i = 0; i < types.length; i++) {
            if (types[i].content_type == type)
                return types[i];
        }

        return types[24];
    },
    truncate_string: function(s, len) {
        t_s = s;
        if (t_s.length > len) {
            t_s = t_s.substring(0, len);
            try {
                if (s.substring(t_s.length, t_s.length + 1) != " ") {
                    idx_last_space = t_s.lastIndexOf(" ");
                    if (idx_last_space != -1) {
                        t_s = t_s.substring(0, idx_last_space);
                    }
                }
            }
            catch (e) { }
        }

        if (s.length > len) {
            t_s += "...";
        }
        return t_s;
    },
    set_cookie_value: function(key, value) {
        var current = new Date();
        current.setDate(current.getDate() + 3);
        document.cookie = escape(key) + '=' + escape(value) + '; expires=' + escape(current.toGMTString());
    },
    get_cookie_value: function(key) {
        var s, e;
        var value = '';

        if (document.cookie.length > 0) {
            s = document.cookie.indexOf(key + '=');
            if (s != -1) {
                e = document.cookie.indexOf(';', s);
                s += key.length + 1;
                value = unescape(document.cookie.substring(s, e));
                return value;
            }
        }

        return value;
    }
}