﻿// 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) {
        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
                        sw.setup_locator_map(ajax_item);
                    }
                });
            }
        }
    },
    setup_locator_map: function(data) {
        // store off the objects from the service
        var module = data.CurrentObject[0];
        var categories = data.CurrentObject[1];
        var locations = data.CurrentObject[2];

        // are we showing the list of links?
        var show_location_list = module.ShowLocationList;

        // are we showing the categories?
        var show_category_list = module.ShowCategoryList;

        // what is the location finder??
        var show_location_finder = module.ShowLocationFinder;

        var id = "#placesmap_" + module.PagePartId;
        var canvas = $(id + " .places-app-map-canvas")[0];
        // set the canvas width and height
        $(canvas).css({ 'width': module.MapWidth + 'px', 'height': module.MapHeight + 'px' });

        // set the map object
        var map = new GMap2(canvas);

        // set the geocoder object
        var geocoder = new GClientGeocoder();

        // set the global point variable
        //var point;

        // set the markers array
        var map_markers = [];

        // set the map's origin center
        map.setCenter(new GLatLng(module.CenterPointLat, module.CenterPointLong), module.ZoomLevel);

        if (module.ShowLargeMapControl) {
            map.addControl(new GLargeMapControl3D());
        }
        if (module.ShowMapTypeControl) {
            map.addControl(new GMapTypeControl());
        }


        // set the map type
        switch (module.MapViewType) {
            case "G_SATELLITE_MAP":
                map.setMapType(G_SATELLITE_MAP);
                break;
            case "G_HYBRID_MAP":
                map.setMapType(G_HYBRID_MAP);
                break;
            default:
                map.setMapType(G_NORMAL_MAP);
                break;
        }

        // hide message popup on click of the map itself
        GEvent.addListener(map, "click", function() {
            $(id + " .places-app-location-popup").hide();
        });

        // build markers
        for (var i = 0; i < locations.length; i++) {
            build_marker(locations[i], i);
        }


        // what to do with the categories
        check_item_tmp = "<li class='places-app-category-item' id='cat-{LocatorMapCategoryId}'>";
        check_item_tmp += "<input id='chk-{LocatorMapCategoryId}' type='checkbox' value='{LocatorMapCategoryId}' checked='checked'>";
        check_item_tmp += "<label for='chk-{LocatorMapCategoryId}'>{Name}</label>";
        check_item_tmp += "</li>";

        // bind up the categories to the checkbox list
        $(id + " .places-app-category-list").DataBind({
            ClearContent: true,
            Data: categories,
            BindItem: check_item_tmp
        });

        // bind the click event to each of the checkboxes
        $(id + " .places-app-category-list input[type='checkbox']").click(function() { update_view(); });

        // now show/hide the category list
        if (!show_category_list) {
            $(id + " .places-app-category-list").hide();
        }

        // what to do with the link list
        if (!show_location_list) {
            $(id + " .places-app-location-list").hide();
        }

        // add message float to map system
        $(id + " .places-app-location-popup").appendTo(map.getPane(G_MAP_FLOAT_SHADOW_PANE));


        //////////
        // internal sw.setup_locator_map() methods
        //////////

        // build the map marker
        function build_marker($location, $i) {
            var point = new GLatLng(parseFloat($location.CenterPointLat), parseFloat($location.CenterPointLong));
            
            // grab the category for the location
            category = get_category($location.LocatorMapCategoryId);

            // Create our marker icon
            icon = new GIcon(G_DEFAULT_ICON);

            if (category != null) {
                if (category.MarkerIconURL != "") {
                    icon.image = category.MarkerIconURL;
                    icon.iconSize = new GSize(32, 37);
                    icon.imageMap = [0, 0, 32, 0, 32, 37, 0, 37]; //x1,y1,x2,y2,x3,y3...
                }
                if (category.MarkerIconShadowURL != "") {
                    icon.shadow = category.MarkerIconShadowURL;
                    icon.iconSize = new GSize(32, 37);
                }
            }

            map_markers[$i] = {};
            map_markers[$i].category = category;
            map_markers[$i].location = $location;
            map_markers[$i].marker = new GMarker(point, icon);

            map.addOverlay(map_markers[$i].marker);
            GEvent.addListener(map_markers[$i].marker, "click", function() { display_info(map_markers[$i]); });

            // set the marker link
            map_markers[$i].link = $("<li class='places-app-location-item'></li>").text(map_markers[$i].location.Name);
            map_markers[$i].link.attr('id', 'loc-' + map_markers[$i].location.LocatorMapLocationId);
            map_markers[$i].link.click(function() { display_info(map_markers[$i]); });
            map_markers[$i].link.appendTo(id + " .places-app-location-list");
        }

        // grabs a category from those returned by the service based on it's ID
        function get_category($id) {
            for (var i = 0; i < categories.length; i++) {
                if (categories[i].LocatorMapCategoryId == $id) {
                    return categories[i];
                }
            }
            return null;
        }

        // display the info balloon for the location
        function display_info($map_marker) {
            // check to see if its within the map view if not, pan to it
            bounds = map.getBounds();
            if (!bounds.containsLatLng($map_marker.marker.getLatLng())) {
                map.panTo($map_marker.marker.getLatLng());
            }

            offset = map.fromLatLngToDivPixel($map_marker.marker.getLatLng());
            msg = "";
            if ($map_marker.location.Name != "") {
                msg += "<h4 class='places-app-location-name'>" + $map_marker.location.Name + "</h4>";
            }
            if ($map_marker.location.Description != "") {
                msg += "<p class='places-app-location-description'>" + $map_marker.location.Description + "</p>";
            }
            msg += "<p class='places-app-location-address'>" + $map_marker.location.Address + "</p>";
            $(id + " .places-app-location-popup").hide();
            $(id + " .places-app-location-popup").fadeIn().css({ top: offset.y, left: offset.x }).html(msg);
        }

        function update_view() {
            $(id + " .places-app-location-popup").hide();
            $(id + " .places-app-location-list li").hide();

            // get checked categories
            cat_ids = [];
            x = 0;
            $(id + " .places-app-category-list input[type='checkbox']").each(function() {
                if ($(this)[0].checked) {
                    cat_ids[x] = util.clean_for_int($(this)[0].id);
                    x++;
                }
            });

            for (var i = 0; i < map_markers.length; i++) {
                loc_cat_id = map_markers[i].location.LocatorMapCategoryId;
                if ((cat_ids.indexOf(loc_cat_id.toString()) != -1) || (loc_cat_id == 0)) {
                    if (show_location_list) {
                        map_markers[i].link.show();
                    }
                    map_markers[i].marker.show();
                }
                else {
                    map_markers[i].marker.hide();
                }
            }
        }
    }
}

//
// SiteWrench utility javascript namespace
//
util = {
    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, "");
    },
    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/>';

            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;
    },
    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;
    }
}