﻿var DOWNLOADER_FRAME_NAME = '_trp_downloader_frame';

Function.prototype.newClass = function(cls) {
	this._class = cls;
	if (this._class == null) this._class = new function() { };
	if (this._baseClass != null) this._class.prototype = this._baseClass.prototype;
	this.prototype = new this._class(this._baseClass != null ? this._baseClass.prototype : null);
	return this;
}

Function.prototype.inheritFrom = function(baseClass) {
	this._baseClass = baseClass;
	return this;
}


function compareStrings(a, b) {
    var re = new RegExp('\\b' + b.replace(/\W+/g, '\\W*'), 'gi');
    return re.test(a);
}

function go(url) {
    document.location = url;
}

function updateHash(hash) {
	var link = document.location.href;
	var idx = link.indexOf('#');
	if (idx >= 0) link = link.substr(0, idx);
    document.location.href = link + hash;
}

function getHash() {
    var link = document.location.href;
    var idx = link.indexOf('#');
    if (idx >= 0) return link.substr(idx + 1, link.length - idx);
    return '';
}

function getCookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if (!start && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

function setCookie(name,value,expires,path,domain,secure) {
    document.cookie = name + "=" +escape(value) +
        (expires ? ";expires=" + expires.toGMTString() : "") +
        (path ? ";path=" + path : "") +
        (domain ? ";domain=" + domain : "") +
        (secure ? ";secure" : "");
}

function deleteCookie(name,path,domain) {
    if (getCookie(name)) document.cookie = name + "=" +
        (path ? ";path=" + path : "") +
        (domain ? ";domain=" + domain : "") +
        ";expires=Thu, 01-Jan-70 00:00:01 GMT";
} 

function getCellBoundary(id) {
    var lat = ((Math.floor(id/36000)-9000)*100 - 49)/10000;
    var lon = ((id%36000-18000)*100 - 49)/10000;
    return {lat1:lat,lon1:lon,lat2:lat+0.01,lon2:lon+0.01};
}

function getCellCentroid(id) {
	var lat = ((Math.floor(id / 36000) - 9000) * 100 - 49) / 10000;
	var lon = ((id % 36000 - 18000) * 100 - 49) / 10000;
	return { lat: lat + 0.005, lon: lon + 0.005 };
}

function getCellID(lat, lon) {
    return (Math.round(lat * 100) + 9000) * 36000 + Math.round(lon * 100) + 18000;
}

function getNeighborCellID(cellid, dlat, dlon) {
    var c = getCellCentroid(cellid);
    return getCellID(c.lat + dlat, c.lon + dlon);
}

function getCellSide(cellid, dlat, dlon) {
    var c = getCellCentroid(cellid);
    if (dlat > 0) return { lat1: c.lat + 0.005, lon1: c.lon - 0.005, lat2: c.lat + 0.005, lon2: c.lon + 0.005 };
    if (dlat < 0) return { lat1: c.lat - 0.005, lon1: c.lon - 0.005, lat2: c.lat - 0.005, lon2: c.lon + 0.005 };
    if (dlon > 0) return { lat1: c.lat - 0.005, lon1: c.lon + 0.005, lat2: c.lat + 0.005, lon2: c.lon + 0.005 };
    if (dlon < 0) return { lat1: c.lat - 0.005, lon1: c.lon - 0.005, lat2: c.lat + 0.005, lon2: c.lon - 0.005 };
    return null;
}

function getContainer(container) {
	return (typeof (container) == 'string' ? document.getElementById(container) : container);
}

function trim(str) {
    return (str ? str.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : '');
}


var MAP_SHADING_COLOR = ['#ffffff', '#44cc2e', '#ffff66', '#ffcc00', '#ff9900', '#ff0000', '#6600ff'];

var MAP_RETAILER_COLOR = ['#ff6923', '#e23f4a', '#b04b4b', '#8a2077', '#ff70e5', '#ff23cb', '#dd23ff', '#c7cdff', '#a023ff', 
    '#5931ef', '#3a88af', '#70a3ff', '#70d7ff', '#70ffe6', '#517c44', '#8cc25e', '#88ef31', '#ddef31', '#fdff70', '#ffde3b', 
    '#ffb770', '#e2963f', '#b0974b', '#bf6d6d', '#b2b4a0'];

var Control = function() {
} .newClass(function() {
	this.container = null;

	this.init = function(container) {
		this.container = getContainer(container);
		this.container._kvv_ctrl = this;
	}
});

function getControl(container) {
	return getContainer()._kvv_ctrl;
}

var MapControl = function() {
    Control._baseClass.call(this);
} .inheritFrom(Control).newClass(function(_baseClass) {
    this.resizeCalcDelegate = null;
    this.map = null;
    this.defaultRegion = 'us';

    this.init = function(container, param, resizeCalcDelegate) {
        _baseClass.init(container);

        this.resizeCalcDelegate = resizeCalcDelegate;
        if (this.resizeCalcDelegate) {
            $(window).bind('resize', this, function(e) { e.data.onResize(); });
            this.onResize();
        }

        this.map = new google.maps.Map(this.container, {
            zoom: param.Zoom,
            center: new google.maps.LatLng(param.Lat, param.Lon),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL }
        });

    }

    this.onResize = function() {
        var sz = this.resizeCalcDelegate();
        var c = $('#' + this.container.id);
        if (sz.height) c.css('height', sz.height + 'px');
        if (sz.width) c.css('width', sz.width + 'px');
    }

    this.geocode = function(address, onready) {
        if (address && address.length > 0) {
            var gc = new google.maps.Geocoder();
            gc.geocode({ address: address, region: this.defaultRegion }, function(result, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    var r = result[0];
                    if (onready) onready({ geometry: r.geometry });
                } else {
                    if (onready) onready({ error: 'Failed to locate ' + address });
                }
            });
        } else {
            if (onready) onready({ error: 'Address can\'t be empty' });
        }
    }

    this.searchAddress = function(address, onready) {
        var self = this;

        if (address && address.length > 0) {
            this.geocode(address, function(result) {
                if (result.error) _HINT.show(result.error);
                else if (result.geometry) {
                    self.map.fitBounds(result.geometry.viewport);
                    if (onready) {
                        var accurate = (result.geometry.location_type == google.maps.GeocoderLocationType.ROOFTOP || result.geometry.location_type == google.maps.GeocoderLocationType.RANGE_INTERPOLATED);
                        onready(result.geometry, accurate);
                    }
                }
            });
        } else {
            if (onready) onready();
        }
    }
});

function showErrorMessage(msg) {
    var err = $('<div><span class="error-message-text">' + msg + '</span></div>');
    err.dialog({
        title: 'Error',
        height: 140,
        width: 380,
        resizable: false,
        autoOpen: true,
        buttons: [{ text: "OK", click: function() { $(this).dialog('close'); } }],
        modal: true
    }); //.bind('clickoutside', function() { if ($(this).is(':visible')) $(this).dialog('close'); });
}

function showMessageBox(title, msg) {
    var err = $('<div>' + msg + '</div>');
    err.dialog({
        title: title,
        height: 140,
        width: 380,
        resizable: false,
        autoOpen: true,
        buttons: [{ text: "OK", click: function() { $(this).dialog('close'); } }],
        modal: true
    }); //.bind('clickoutside', function() { if ($(this).is(':visible')) $(this).dialog('close'); });
}

function showQuestionDialog(title, msg, buttons, onclose) {
    var dlg = $('<div><span class="error-message-text">' + msg + '</span></div>');
    var btns = new Array();
    $.each(buttons, function(idx, val) {
        btns[btns.length] = { text: val, click: function() { $(this).dialog('close'); onclose(val); } };
    });
    
    dlg.dialog({
        title: title,
        height: 140,
        width: 380,
        resizable: false,
        autoOpen: true,
        buttons: btns,
        modal: true
    });
}


var _defaultErrorHandler = function(err) { if (err.text && err.text.length) showErrorMessage(err.text); }
var _api_request_id = 0;

$.api = function(apiClass, apiMethod, data, handler, errorHandler) {
    if (!errorHandler) errorHandler = _defaultErrorHandler;

    data.api_request_id = _api_request_id;
    $.ajax({ url: '/api/' + apiClass + '-' + apiMethod + '.ajax', data: $.toJSON(data), type: "POST", cache: false, processData: false, dataType: 'text',
        success: function(data, textStatus, xhr) {
            var res = $.parseJSON(data);
            if (res && res.result && res.result.errCode) {
                switch (res.result.errCode) {
                    case 401:
                        window.location.href = '/' + window.location.hash;
                        break;

                    case 10001:
                        window.location.href = 'SiteMaintenance.aspx';
                        break;

                    default:
                        errorHandler({ code: res.result.errCode, text: res.result.error }, _defaultErrorHandler);
                        break;
                }
            }
            else if (handler) handler(res.result, res.api_request_id);
        },
        error: function(xhr, textStatus, errorThrown) {
            errorHandler({ code: xhr.status, text: xhr.statusText }, _defaultErrorHandler);
        }
    });

    return _api_request_id++;
}


function Hint(id) {
    this.id = id;
    
    this.show = function(html) {
        var h = $('#' + this.id);
        if (!h.length) {
            h = $('<div id="' + this.id + '"></div>');
            h.appendTo($(document.body));
        }

        h.css('position', 'absolute');
        h.css('top', '5px');
        h.css('left', '0px');
        h.css('width', '100%');
        h.css('z-index', '10000');
        h.css('text-align', 'center');
        h.html('<span>' + html + '</span>');        
        h.show();
    }
    
    this.hide = function() {
        $('#' + this.id).hide();
    }
}


var _HINT = new Hint('hint');

$(document).ajaxStart(function() {
    _HINT.show('Loading...');
});

$(document).ajaxStop(function() {
    _HINT.hide();
});

var _enter_email_txt = 'enter e-mail';

function initHints(container) {
    $.each(container, function(idx, val) {
        var hint_text = $(val).attr('title');
        if (hint_text && hint_text.length) {
            $(val).removeAttr('title');

            var hint_element = $('<div style="position:absolute; display:none;" class="ui-frame hhint_text">' + hint_text + '</div>').appendTo(val);
            $('a', hint_element).attr('target', '_blank').addClass('hhint_text');

            hint_element.data('hint_parent', $(val)).mouseout(function(e) {
                if (!$(e.relatedTarget).hasClass('hhint_text')) $(this).hide().detach().appendTo($(this).data('hint_parent'));
            });

            $(val).data('hint', hint_element).mousedown(function() { $(this).trigger('mouseout'); });

            $(val).mouseover(function() {
                var pos = $(this).offset();
                $(this).data('hint').detach().css('top', pos.top + $(this).outerHeight() - 2 + 'px').css('left', pos.left + 'px').appendTo(document.body).show();
            }).mouseout(function(e) {
                if (!$(e.relatedTarget).hasClass('hhint_text')) $(this).data('hint').hide().detach().appendTo(this);
            });
            
        }
    });
    
}


$(document).ready(function() {
    $('#btn_subscribe')
        .mouseover(function() { $(this).attr('src', _THEME_PATH + 'images/btn-arrow-hover.png'); })
        .mouseout(function() { $(this).attr('src', _THEME_PATH + 'images/btn-arrow.png'); });

    $('.hoverable').mouseover(function() { $(this).toggleClass('hoverable', false).toggleClass('hoverable-hover', true); })
        .mouseout(function() { $(this).toggleClass('hoverable', true).toggleClass('hoverable-hover', false); });


    initHints($('.hhint'));


    $('#txt_subscribe').textbox({ hint: 'enter e-mail' });

    $('#form_subscribe')
        .attr('action', 'https://app.icontact.com/icp/signup.php')
        .submit(function(e) {
            if (!validateEmail($('#txt_subscribe').val())) {
                e.preventDefault();
                e.stopPropagation();
                $('#txt_subscribe').data('textbox').error();
                return false;
            } else {
                window.open('http://icontact.com', 'vr_optin_popup', 'scrollbars=yes,width=600,height=320');
                setTimeout('$(\'#txt_subscribe\').data(\'textbox\').reset()', 500);
                return true;
            }
        });


    DoPing(true);
});

function DoPing(initialize) {
    if (!initialize) $.api('WebAPI', 'Ping', {}, function() { }, function() { });
    setTimeout('DoPing()', 300000);
}

function validateEmail(txt) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(txt);

} 

function createDownloaderFrame() {
    var downloader = $('#' + DOWNLOADER_FRAME_NAME);
    if (downloader.length == 0) {
        downloader = $('<iframe width="1" height="1" style="display:none" name="' + DOWNLOADER_FRAME_NAME + '" id="' + DOWNLOADER_FRAME_NAME + '"></iframe>');
        downloader.appendTo(document.body);
    }
    return downloader;
}

function downloadFile(url) {
    createDownloaderFrame().attr('src', url);
}

var _preloaded_images = new Array();
function preload_img(rootPath, list) {
    for (var i=0; i<list.length; i++) {
        var img = new Image();
        img.src = rootPath + list[i];
        _preloaded_images[_preloaded_images.length] = img;
    }
}

function parseFormatedInt(str) {
    var ret = NaN;
    if (str) {
        var rx = new RegExp('^(\\d{1,3}(\\,\\d{3})*(\\,\\d+)?|(\\d+))(\\,\\d+)?$');
        var val = str.replace(/^\s*|\s*$/, '');
        if (rx.test(val)) ret = parseInt(val.replace(/\,/g, ''));
    }
    return ret;
}

function formatNumber(number) {
    var num = Math.max(0, number);
    var dec = (Math.floor(num) != num ? 2 : 0);
    return num.toFixed(dec).replace(/(?=(?:\d{3})+$)(?!^)/g, ',');
}

function zeroPad(number, length) {
    var str = number.toString();
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

function getReverseGeocodingAddress(results) {
    var stno = null, route = null;
    for (var i = 0; i < results.address_components.length; i++) {
        var comp = results.address_components[i];
        for (var j = 0; j < comp.types.length; j++) {
            switch (comp.types[j]) {
                case 'street_number': stno = comp.long_name; break;
                case 'route': route = comp.long_name; break;
            }
            if (stno && route) break;
        }
        if (stno && route) break;
    }
    var addr = new Array();
    if (stno) addr[addr.length] = stno;
    if (route) addr[addr.length] = route;

    return addr.join(' ');
}



function SyncTrigger(fn, counter) {
    this._counter = counter;
    this.trigger = function() {
        this._counter--;
        if (this._counter <= 0) {
            fn.apply(null, arguments);
        }
    }
}


jQuery.fn.sort = function() {
    return this.pushStack([].sort.apply(this, arguments), []);
};

jQuery.fn.sortOptions = function(sortCallback) {
    jQuery('option', this)
		.sort(sortCallback)
		.appendTo(this);
    return this;
};

jQuery.fn.sortOptionsByText = function() {
    var byTextSortCallback = function(x, y) {
        var xText = jQuery(x).text().toUpperCase();
        var yText = jQuery(y).text().toUpperCase();
        return (xText < yText) ? -1 : (xText > yText) ? 1 : 0;
    };
    return this.sortOptions(byTextSortCallback);
};

jQuery.fn.sortOptionsByValue = function() {
    var byValueSortCallback = function(x, y) {
        var xVal = jQuery(x).val();
        var yVal = jQuery(y).val();
        return (xVal < yVal) ? -1 : (xVal > yVal) ? 1 : 0;
    };

    return this.sortOptions(byValueSortCallback);
};

jQuery.fn.extend({
    highlight: function(text, cls) {
        var regex = new RegExp("(<[^>]*>)|(\\b" + text.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1") + ")", "ig");
        this.each(function() {
            var cont = $(this);
            cont.html(cont.html().replace(regex, function(a, b, c) {
                return (a.charAt(0) == '<') ? a : '<span class="' + cls + '">' + c + '</span>';
            }));
        });
    }
});

jQuery.fn.extend({
    removeHighlight: function(cls) {
        this.each(function() {
            $('span.' + cls, $(this)).each(function() {
                $(this).after($(this).html()).remove();
            });
        });
    }
});
/*
jQuery.fn.extend({
    disableSelection: function() {
        this.each(function() {
            if (typeof this.onselectstart != 'undefined') {
                this.onselectstart = function() { return false; };
            } else if (typeof this.style.MozUserSelect != 'undefined') {
                this.style.MozUserSelect = 'none';
            } else {
                this.onmousedown = function() { return false; };
            }
        });
    }
});
*/
