/** * * Color picker * Author: Stefan Petre www.eyecon.ro * * Dual licensed under the MIT and GPL licenses * */ (function ($) { var ColorPicker = function () { var ids = {}, inAction, charMin = 65, visible, tpl = '
', defaults = { eventName: 'click', onShow: function () {}, onBeforeShow: function(){}, onHide: function () {}, onChange: function () {}, onSubmit: function () {}, color: 'ff0000', livePreview: true, flat: false }, fillRGBFields = function (hsb, cal) { var rgb = HSBToRGB(hsb); $(cal).data('colorpicker').fields .eq(1).val(rgb.r).end() .eq(2).val(rgb.g).end() .eq(3).val(rgb.b).end(); }, fillHSBFields = function (hsb, cal) { $(cal).data('colorpicker').fields .eq(4).val(hsb.h).end() .eq(5).val(hsb.s).end() .eq(6).val(hsb.b).end(); }, fillHexFields = function (hsb, cal) { $(cal).data('colorpicker').fields .eq(0).val(HSBToHex(hsb)).end(); }, setSelector = function (hsb, cal) { $(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100})); $(cal).data('colorpicker').selectorIndic.css({ left: parseInt(150 * hsb.s/100, 10), top: parseInt(150 * (100-hsb.b)/100, 10) }); }, setHue = function (hsb, cal) { $(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10)); }, setCurrentColor = function (hsb, cal) { $(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb)); }, setNewColor = function (hsb, cal) { $(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb)); }, keyDown = function (ev) { var pressedKey = ev.charCode || ev.keyCode || -1; if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) { return false; } var cal = $(this).parent().parent(); if (cal.data('colorpicker').livePreview === true) { change.apply(this); } }, change = function (ev) { var cal = $(this).parent().parent(), col; if (this.parentNode.className.indexOf('_hex') > 0) { cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value)); } else if (this.parentNode.className.indexOf('_hsb') > 0) { cal.data('colorpicker').color = col = fixHSB({ h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10), s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10), b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10) }); } else { cal.data('colorpicker').color = col = RGBToHSB(fixRGB({ r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10), g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10), b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10) })); } if (ev) { fillRGBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); } setSelector(col, cal.get(0)); setHue(col, cal.get(0)); setNewColor(col, cal.get(0)); cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]); }, blur = function (ev) { var cal = $(this).parent().parent(); cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus'); }, focus = function () { charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65; $(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus'); $(this).parent().addClass('colorpicker_focus'); }, downIncrement = function (ev) { var field = $(this).parent().find('input').focus(); var current = { el: $(this).parent().addClass('colorpicker_slider'), max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255), y: ev.pageY, field: field, val: parseInt(field.val(), 10), preview: $(this).parent().parent().data('colorpicker').livePreview }; $(document).bind('mouseup', current, upIncrement); $(document).bind('mousemove', current, moveIncrement); }, moveIncrement = function (ev) { ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10)))); if (ev.data.preview) { change.apply(ev.data.field.get(0), [true]); } return false; }, upIncrement = function (ev) { change.apply(ev.data.field.get(0), [true]); ev.data.el.removeClass('colorpicker_slider').find('input').focus(); $(document).unbind('mouseup', upIncrement); $(document).unbind('mousemove', moveIncrement); return false; }, downHue = function (ev) { var current = { cal: $(this).parent(), y: $(this).offset().top }; current.preview = current.cal.data('colorpicker').livePreview; $(document).bind('mouseup', current, upHue); $(document).bind('mousemove', current, moveHue); }, moveHue = function (ev) { change.apply( ev.data.cal.data('colorpicker') .fields .eq(4) .val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10)) .get(0), [ev.data.preview] ); return false; }, upHue = function (ev) { fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); $(document).unbind('mouseup', upHue); $(document).unbind('mousemove', moveHue); return false; }, downSelector = function (ev) { var current = { cal: $(this).parent(), pos: $(this).offset() }; current.preview = current.cal.data('colorpicker').livePreview; $(document).bind('mouseup', current, upSelector); $(document).bind('mousemove', current, moveSelector); }, moveSelector = function (ev) { change.apply( ev.data.cal.data('colorpicker') .fields .eq(6) .val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10)) .end() .eq(5) .val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10)) .get(0), [ev.data.preview] ); return false; }, upSelector = function (ev) { fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0)); $(document).unbind('mouseup', upSelector); $(document).unbind('mousemove', moveSelector); return false; }, enterSubmit = function (ev) { $(this).addClass('colorpicker_focus'); }, leaveSubmit = function (ev) { $(this).removeClass('colorpicker_focus'); }, clickSubmit = function (ev) { var cal = $(this).parent(); var col = cal.data('colorpicker').color; cal.data('colorpicker').origColor = col; setCurrentColor(col, cal.get(0)); cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el); }, show = function (ev) { var cal = $('#' + $(this).data('colorpickerId')); cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]); var pos = $(this).offset(); var viewPort = getViewport(); var top = pos.top + this.offsetHeight; var left = pos.left; if (top + 176 > viewPort.t + viewPort.h) { top -= this.offsetHeight + 176; } if (left + 356 > viewPort.l + viewPort.w) { left -= 356; } cal.css({left: left + 'px', top: top + 'px'}); if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) { cal.show(); } $(document).bind('mousedown', {cal: cal}, hide); return false; }, hide = function (ev) { if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) { if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) { ev.data.cal.hide(); } $(document).unbind('mousedown', hide); } }, isChildOf = function(parentEl, el, container) { if (parentEl == el) { return true; } if (parentEl.contains) { return parentEl.contains(el); } if ( parentEl.compareDocumentPosition ) { return !!(parentEl.compareDocumentPosition(el) & 16); } var prEl = el.parentNode; while(prEl && prEl != container) { if (prEl == parentEl) return true; prEl = prEl.parentNode; } return false; }, getViewport = function () { var m = document.compatMode == 'CSS1Compat'; return { l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft), t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop), w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth), h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight) }; }, fixHSB = function (hsb) { return { h: Math.min(360, Math.max(0, hsb.h)), s: Math.min(100, Math.max(0, hsb.s)), b: Math.min(100, Math.max(0, hsb.b)) }; }, fixRGB = function (rgb) { return { r: Math.min(255, Math.max(0, rgb.r)), g: Math.min(255, Math.max(0, rgb.g)), b: Math.min(255, Math.max(0, rgb.b)) }; }, fixHex = function (hex) { var len = 6 - hex.length; if (len > 0) { var o = []; for (var i=0; i -1) ? hex.substring(1) : hex), 16); return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)}; }, HexToHSB = function (hex) { return RGBToHSB(HexToRGB(hex)); }, RGBToHSB = function (rgb) { var hsb = { h: 0, s: 0, b: 0 }; var min = Math.min(rgb.r, rgb.g, rgb.b); var max = Math.max(rgb.r, rgb.g, rgb.b); var delta = max - min; hsb.b = max; if (max != 0) { } hsb.s = max != 0 ? 255 * delta / max : 0; if (hsb.s != 0) { if (rgb.r == max) { hsb.h = (rgb.g - rgb.b) / delta; } else if (rgb.g == max) { hsb.h = 2 + (rgb.b - rgb.r) / delta; } else { hsb.h = 4 + (rgb.r - rgb.g) / delta; } } else { hsb.h = -1; } hsb.h *= 60; if (hsb.h < 0) { hsb.h += 360; } hsb.s *= 100/255; hsb.b *= 100/255; return hsb; }, HSBToRGB = function (hsb) { var rgb = {}; var h = Math.round(hsb.h); var s = Math.round(hsb.s*255/100); var v = Math.round(hsb.b*255/100); if(s == 0) { rgb.r = rgb.g = rgb.b = v; } else { var t1 = v; var t2 = (255-s)*v/255; var t3 = (t1-t2)*(h%60)/60; if(h==360) h = 0; if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3} else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3} else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3} else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3} else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3} else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3} else {rgb.r=0; rgb.g=0; rgb.b=0} } return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)}; }, RGBToHex = function (rgb) { var hex = [ rgb.r.toString(16), rgb.g.toString(16), rgb.b.toString(16) ]; $.each(hex, function (nr, val) { if (val.length == 1) { hex[nr] = '0' + val; } }); return hex.join(''); }, HSBToHex = function (hsb) { return RGBToHex(HSBToRGB(hsb)); }, restoreOriginal = function () { var cal = $(this).parent(); var col = cal.data('colorpicker').origColor; cal.data('colorpicker').color = col; fillRGBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); setSelector(col, cal.get(0)); setHue(col, cal.get(0)); setNewColor(col, cal.get(0)); }; return { init: function (opt) { opt = $.extend({}, defaults, opt||{}); if (typeof opt.color == 'string') { opt.color = HexToHSB(opt.color); } else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) { opt.color = RGBToHSB(opt.color); } else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) { opt.color = fixHSB(opt.color); } else { return this; } return this.each(function () { if (!$(this).data('colorpickerId')) { var options = $.extend({}, opt); options.origColor = opt.color; var id = 'collorpicker_' + parseInt(Math.random() * 1000); $(this).data('colorpickerId', id); var cal = $(tpl).attr('id', id); if (options.flat) { cal.appendTo(this).show(); } else { cal.appendTo(document.body); } options.fields = cal .find('input') .bind('keyup', keyDown) .bind('change', change) .bind('blur', blur) .bind('focus', focus); cal .find('span').bind('mousedown', downIncrement).end() .find('>div.colorpicker_current_color').bind('click', restoreOriginal); options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector); options.selectorIndic = options.selector.find('div div'); options.el = this; options.hue = cal.find('div.colorpicker_hue div'); cal.find('div.colorpicker_hue').bind('mousedown', downHue); options.newColor = cal.find('div.colorpicker_new_color'); options.currentColor = cal.find('div.colorpicker_current_color'); cal.data('colorpicker', options); cal.find('div.colorpicker_submit') .bind('mouseenter', enterSubmit) .bind('mouseleave', leaveSubmit) .bind('click', clickSubmit); fillRGBFields(options.color, cal.get(0)); fillHSBFields(options.color, cal.get(0)); fillHexFields(options.color, cal.get(0)); setHue(options.color, cal.get(0)); setSelector(options.color, cal.get(0)); setCurrentColor(options.color, cal.get(0)); setNewColor(options.color, cal.get(0)); if (options.flat) { cal.css({ position: 'relative', display: 'block' }); } else { $(this).bind(options.eventName, show); } } }); }, showPicker: function() { return this.each( function () { if ($(this).data('colorpickerId')) { show.apply(this); } }); }, hidePicker: function() { return this.each( function () { if ($(this).data('colorpickerId')) { $('#' + $(this).data('colorpickerId')).hide(); } }); }, setColor: function(col) { if (typeof col == 'string') { col = HexToHSB(col); } else if (col.r != undefined && col.g != undefined && col.b != undefined) { col = RGBToHSB(col); } else if (col.h != undefined && col.s != undefined && col.b != undefined) { col = fixHSB(col); } else { return this; } return this.each(function(){ if ($(this).data('colorpickerId')) { var cal = $('#' + $(this).data('colorpickerId')); cal.data('colorpicker').color = col; cal.data('colorpicker').origColor = col; fillRGBFields(col, cal.get(0)); fillHSBFields(col, cal.get(0)); fillHexFields(col, cal.get(0)); setHue(col, cal.get(0)); setSelector(col, cal.get(0)); setCurrentColor(col, cal.get(0)); setNewColor(col, cal.get(0)); } }); } }; }(); $.fn.extend({ ColorPicker: ColorPicker.init, ColorPickerHide: ColorPicker.hidePicker, ColorPickerShow: ColorPicker.showPicker, ColorPickerSetColor: ColorPicker.setColor }); })(jQuery)/*** snippet ***/ var global_bg = ""; var locateY= null; var default_snippet_fixed_size = 'sizel'; var snippet_hd_mode; var snippet_type_val; var snippet_zoom_val; var snippet_width_val; var snippet_height_val; var snippet_latitude_val; var snippet_longitude_val; var snippet_title_val; var snippet_detail_val; var snippet_locale_val; var snippet_mapversion_val; var snippet_zoombar_val; var snippet_toolbar_val; var snippet_mapselector_val; var snippet_scalebar_val; var snippet_centermark_val; var snippet_mapmode_val; var snippet_bgcolor_val; var snippet_bgurl_val; var snippet_bgpadding_val = 10; var snippet_marker_val; var snippet_marker_position_val; var snippet_marker_offsetx_val; var snippet_marker_offsety_val; var snippet_poiid_val; var snippet_position_type_val; var snippet_theme_type_val; var snippet_theme_val; var snippet_fixed_size; var snippet_search_val; var snippet_tag_val; var forcepoi = ''; function initSnippetForm() { $('#snippet-selectcode-text').click(function() { $('#code-html-map-snippet').focus().select(); }); $('#code-html-map-snippet').change(function() { showPreviewSnippet(); }); $('#colorSelector').ColorPicker({ color: '#ffb7d9', onShow: function (colpkr) { $(colpkr).fadeIn(500); return false; }, onHide: function (colpkr) { $(colpkr).fadeOut(500); generateSnippetCode(); return false; }, onChange: function (hsb, hex, rgb) { $('#colorSelector div').css('backgroundColor', '#' + hex); $("#urlbg").val(""); $("#snippet-bg-color").val('#' + hex); } }); $('#checktool, #checkzoomer, #checkscale, #checkselector, #checkcentermark').change(function(){ generateSnippetCode(); }); $('#sizes').click(function(){ $('#snippet-width-setting').val('300'); $('#snippet-height-setting').val('200'); }); $('#sizem').click(function(){ $('#snippet-width-setting').val('450'); $('#snippet-height-setting').val('300'); }); $('#sizel').click(function(){ $('#snippet-width-setting').val('600'); $('#snippet-height-setting').val('400'); }); $('.mapsize').click(function(){ if($(this).val() == 'sizecustom') { enableCustomSnippetSize(); setSnippetTheme('default'); } else { disableCustomSnippetSize(); } generateSnippetCode(); }); $("#pattern > div").each(function(i){ $("#box"+(i+1)).click(function(){ $("#urlbg").val("//map.longdo.com/mmmap/images/snippet/p-"+(i+1)+".png"); $("#snippet-bg-color").val(""); $("#colorSelector div").css('background-color', '#FFFFFF'); $(".boxstyle").removeClass('selected-snippet-bgimg'); $(this).addClass('selected-snippet-bgimg'); generateSnippetCode(); }); }); $("#select-pinmark > div").each(function(i){ if(!$("#pinmark"+i) || $("#pinmark"+i).length == 0) return; $("#pinmark"+i).click(function(){ var icon_img = i==0 ? '' : window.location.protocol+"//map.longdo.com/mmmap/images/snippet/pin_style_"+i+".png"; $("#marker").val(icon_img); $("#pin-position").val("center-bottom"); $("#snippet-pin-offset-x").val(17); $("#snippet-pin-offset-y").val(40); $("#marker-pin").attr('checked', 'checked'); $(".pinMark").removeClass("snippet-selected-pinmark"); $(this).addClass("snippet-selected-pinmark"); generateSnippetCode(); }); }); $('.snippet-location-type-setting').change(function(){ generateSnippetCode(); }); $('.location-marker, #snippet-hd-mode').click(function(){ generateSnippetCode(); }); $('#theme-option-background').change(function(){ setSnippetTheme(); }); $("#animate").click(function(){ setSnippetTheme(); }); $('#snippet-theme-type-setting').change(function(){ var snippet_theme_type_val = $(this).val(); $('.snippet-theme-type-setting').hide(); if(snippet_theme_type_val == "bg_theme") { $('#bg-theme-config').show(); } else if(snippet_theme_type_val == "bg_deco") { $('#deco-config').show(); } if(snippet_theme_type_val != "bg_theme") { $('.snippet-thumbnail-theme').removeClass('snippet-thumbnail-theme-selected'); $('.snippet-theme-default').parent().addClass('snippet-thumbnail-theme-selected'); } generateSnippetCode(); }); $("#show-style-config, #show-advance-config, #show-basic-config").unbind( "click" ); $("#show-basic-config").bind('click',function(){ if($("#config-basic").css('display') != 'none') { $("#show-basic-config").removeClass('accordion-active'); $("#config-basic").slideUp(); } else { var offset_top = $('#content-left-tools-print').height()+$('#content-left-tools-permalink').height()+60+$("#snippet-content").height()+15+$("#snippetform").height()-$("#accordion-snippet").height(); $('#content-menu-tools-area').animate({ scrollTop: offset_top }, 'slow'); $("#show-basic-config").addClass('accordion-active'); $("#config-basic").slideDown(); } }); $("#show-advance-config").bind('click',function(){ if($("#config-advance").css('display') != 'none') { $("#show-advance-config").removeClass('accordion-active'); $("#config-advance").slideUp(); } else { var offset_top = $('#content-left-tools-print').height()+$('#content-left-tools-permalink').height()+60+$("#snippet-content").height()+$("#show-basic-config").height()+$("#config-basic")[0].scrollHeight+30+ $("#snippetform").height()-$("#accordion-snippet").height(); $('#content-menu-tools-area').animate({ scrollTop: offset_top }, 'slow'); $("#show-advance-config").addClass('accordion-active'); $("#config-advance").slideDown(); } }); $("#show-style-config").bind('click',function(){ if($("#config-style-advance").css('display') != 'none') { $("#show-style-config").removeClass('accordion-active'); $("#config-style-advance").slideUp(); } else { var offset_top = $('#content-left-tools-print').height()+$('#content-left-tools-permalink').height()+60+$("#snippet-content").height()+$("#show-basic-config").height()+$("#config-basic")[0].scrollHeight+40+ $("#snippetform").height()-$("#accordion-snippet").height() + $("#show-advance-config").height() + $("#config-advance")[0].scrollHeight; $('#content-menu-tools-area').animate({ scrollTop: offset_top }, 'slow'); $("#show-style-config").addClass('accordion-active'); $("#config-style-advance").slideDown(); } }); $(".snippet-type-setting").click(function() { if($(this).val() == 'iframe-snippet') { $(".snippet-image-setting").hide(); $(".snippet-iframe-setting").show(); } else { $(".snippet-image-setting").show(); $(".snippet-iframe-setting").hide(); } generateSnippetCode(0); }); $("#longdomapid").keyup(function(){ $("#snippet-location-by-poiid").attr('checked', 'checked'); }); $("#latitude, #longitude").keyup(function(){ $("#snippet-location-by-latlon").attr('checked', 'checked'); }); $("#snippet-detail, #snippet-title").keyup(function(){ $("#marker-popup").attr('checked', 'checked'); }); $(".location-marker").click(function(){ if(!$("#marker-pin").is(':checked')) { $(".pinMark").removeClass('snippet-selected-pinmark'); } }) $("#marker").keyup(function(){ $("#marker-pin").attr('checked', 'checked'); }); $("#snippet-width-setting, #snippet-height-setting, #snippet-search, #snippet-tag, #snippet-pin-offset-x, #snippet-pin-offset-y").keyup(function(){ generateSnippetCode(); }); $("#longdomapid, #mode-selector-select, #maplang, #zoom, #map-version, #snippet-title, #snippet-detail, #marker, #deco_img").change(function(){ generateSnippetCode(); }); $("#latitude, #longitude").change(function(){ if($("#snippet-location-by-latlon").is(":checked") ) { generateSnippetCode(); } }); $("#pin-position").change(function(){ generateSnippetCode(); preview_pin_position(); }); $("#urlbg, #snippet-bg-padding").keyup(function(){ generateSnippetCode(); }); $("#"+default_snippet_fixed_size).click(); if(snippet_type_val == 'iframe') { // change default for snippet image $('#pinmark0').click(); } else { $('#pinmark1').click(); } } //function toggleSnippetForm(generate_button) { // // createDefaultSnippetCode(); // // if($(generate_button).val() == 'Generate') { // $(generate_button).val('Cancel') // $(generate_button).addClass('cancel-button'); // $("#code-html-map-snippet").focus().select(); // var snippet_form_offset_top = ($('#content-left-tools-print').height()+$('#content-left-tools-permalink').height()+60); // 60: padding // $('#content-menu-tools-area').animate({ scrollTop: snippet_form_offset_top}, 'slow'); // showPreviewSnippet(); // } else { // $(generate_button).val('Generate'); // $(generate_button).removeClass('cancel-button'); // hidePreviewSnippet(); // } //} function preview_pin_position() { $(".snippet-preview-pinmark-position span").attr('class', ''); $(".snippet-preview-pinmark-position span").addClass($("#pin-position").val()); } function createDefaultSnippetCode(){ $(".snippet-image-setting").hide(); if(forcepoi == '') { $("#zoom").val(mapZoom()); var map_location = getCenterLocation(); $("#longitude").val(map_location.lon); $("#latitude").val(map_location.lat); } if($("#sizecustom").is(":checked")) { enableCustomSnippetSize(); } else { disableCustomSnippetSize(); } setSnippetTheme('default', 0); preview_pin_position(); } function getMarkerPostionParam(position) { switch(position) { case 'center-bottom': return ';offsetX:center;offsetY:bottom;'; case 'center-top': return ';offsetX:center;offsetY:top;'; case 'left-middle': return ';offsetX:left;offsetY:middle;'; case 'right-middle': return ';offsetX:right;offsetY:middle;'; case 'left-bottom': return ';offsetX:left;offsetY:bottom;'; case 'right-bottom': return ';offsetX:right;offsetY:bottom;'; case 'left-top': return ';offsetX:left;offsetY:top;'; case 'right-top': return ';offsetX:right;offsetY:top;'; case 'center-middle': default: return ''; } } function generateSnippetTheme(snippet_code) { if(snippet_theme_val == 'leather') { var width_div,height_div,width_div_2,height_div_2,style_top,style_left,bg_size; if(snippet_fixed_size == "size-s") { width_div = 361; height_div = 261; width_div_2 = 357; height_div_2 = 60; style_top = 195; style_left = 3; bg_size = 'S'; } else if(snippet_fixed_size == "size-m") { width_div = 541; height_div = 383; width_div_2 = 534; height_div_2 = 88; style_top = 287; style_left = 4; bg_size = 'M'; } else if(snippet_fixed_size == "size-l") { width_div = 713; height_div = 501; width_div_2 = 713; height_div_2 = 117; style_top = 383; style_left = 0; // auto ? bg_size = 'L'; } snippet_code = "
"+snippet_code+"
"; } else if(snippet_theme_val == 'airmail') { var width_div, height_div, width_div_bg_top, height_div_bg_top, width_div_bg_left, height_div_bg_left, width_div_bg_right, height_div_bg_right, width_div_bg_bottom, height_div_bg_bottom, style_left_bg_top, style_top_bg_right, style_left_bg_right, style_top_bg_bottom, stamp_img, width_stamp_img, height_stamp_img, style_top_stamp_img, style_left_stamp_img, bg_size; if(snippet_fixed_size == "size-s") { width_div = 342; height_div = 239; width_div_bg_top = 342; height_div_bg_top = 14; width_div_bg_left = 21; height_div_bg_left = 199; width_div_bg_right = 21; height_div_bg_right = 199; width_div_bg_bottom = 342; height_div_bg_bottom = 26; style_top_bg_left = 14; style_top_bg_right = 14; style_left_bg_right = 321; style_top_bg_bottom = 213; stamp_img = '-s'; width_stamp_img = 71; height_stamp_img = 51; style_top_stamp_img = 20; style_left_stamp_img = 245; bg_size = 'S'; } else if(snippet_fixed_size == "size-m") { width_div = 512; height_div = 356; width_div_bg_top = 505; height_div_bg_top = 20; width_div_bg_left = 31; height_div_bg_left = 299; width_div_bg_right = 31; height_div_bg_right = 299; width_div_bg_bottom = 512; height_div_bg_bottom = 38; style_top_bg_left = 20; style_top_bg_right = 20; style_left_bg_right = 480; style_top_bg_bottom = 318; stamp_img = ''; width_stamp_img = 122; height_stamp_img = 90; style_top_stamp_img = 22; style_left_stamp_img = 354; bg_size = 'M'; } else if(snippet_fixed_size == "size-l") { width_div = 682; height_div = 466; width_div_bg_top = 682; height_div_bg_top = 27; width_div_bg_left = 42; height_div_bg_left = 399; width_div_bg_right = 41; height_div_bg_right = 399; width_div_bg_bottom = 682; height_div_bg_bottom = 40; style_top_bg_left = 27; style_top_bg_right = 27; style_left_bg_right = 641; style_top_bg_bottom = 426; stamp_img = ''; width_stamp_img = 122; height_stamp_img = 90; style_top_stamp_img = 30; style_left_stamp_img = 515; bg_size = 'L'; } snippet_code = "
"+snippet_code+"
"; } else if(snippet_theme_val == 'standwood') { if(snippet_fixed_size == "size-s") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-m") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-l") { snippet_code = "
"+snippet_code+"
"; } } else if(snippet_theme_val == 'woodframe') { if(snippet_fixed_size == "size-s") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-m") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-l") { snippet_code = "
"+snippet_code+"
"; } } else if(snippet_theme_val == 'pinkframe') { if(snippet_fixed_size == "size-s") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-m") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-l") { snippet_code = "
"+snippet_code+"
"; } } else if(snippet_theme_val == 'darkvi') { if(snippet_fixed_size == "size-s") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-m") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-l") { snippet_code = "
"+snippet_code+"
"; } } else if(snippet_theme_val == 'blueframe') { if(snippet_fixed_size == "size-s") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-m") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-l") { snippet_code = "
"+snippet_code+"
"; } } else if(snippet_theme_val == 'tear') { if(snippet_fixed_size == "size-s") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-m") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-l") { snippet_code = "
"+snippet_code+"
"; } } else if(snippet_theme_val == 'ontable') { if(snippet_fixed_size == "size-s") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-m") { snippet_code = "
"+snippet_code+"
"; } else if(snippet_fixed_size == "size-l") { snippet_code = "
"+snippet_code+"
"; } } else if(snippet_theme_val == 'shop') { var animate = $("#animate").is(":checked"); if(animate) { setTimeout(function(){rollup();}, 1000); // koB ?? } if(snippet_fixed_size == "size-s") { snippet_code = "
"+snippet_code+"
"; if(animate) { snippet_code = "function rollup(){if ($('.boxAB').height() == '0'){$('.boxA').animate({height:235},'slow');$('.boxAB').animate({height:205},'slow');$('.boxA').animate({height:225},'slow');$('.boxAB').animate({height:200},'slow');}else {$('.boxA').animate({height:230},'slow');$('.boxAB').animate({height:205},'slow');$('.boxA').animate({height:30},'slow');$('.boxAB').animate({height:0},'slow');}}" + snippet_code; } } else if(snippet_fixed_size == "size-m") { snippet_code = "
"+snippet_code+"
"; if(animate) { snippet_code = "function rollup(){if ($('.boxAB').height() == '0'){$('.boxA').animate({height:375},'slow');$('.boxAB').animate({height:310},'slow');$('.boxA').animate({height:365},'slow');$('.boxAB').animate({height:300},'slow');}else {$('.boxA').animate({height:375},'slow');$('.boxAB').animate({height:310},'slow');$('.boxA').animate({height:60},'slow');$('.boxAB').animate({height:0},'slow');}}" + snippet_code; } } else if(snippet_fixed_size == "size-l") { snippet_code = "
"+snippet_code+"
"; if(animate) { snippet_code = "function rollup(){if ($('.boxAB').height() == '0'){$('.boxA').animate({height:500},'slow');$('.boxAB').animate({height:410},'slow');$('.boxA').animate({height:490},'slow');$('.boxAB').animate({height:400},'slow');}else {$('.boxA').animate({height:500},'slow');$('.boxAB').animate({height:410},'slow');$('.boxA').animate({height:85},'slow');$('.boxAB').animate({height:0},'slow');}}" + snippet_code; } } } return snippet_code; } function generateSnippetStyle() { var snippet_bg_style = ''; if(snippet_theme_type_val == 'bg_deco') { if(snippet_bgpadding_val != '') { snippet_bg_style += 'padding:'+snippet_bgpadding_val+'px;'; } if(snippet_bgurl_val != '') { snippet_bg_style += 'background:url('+snippet_bgurl_val+') transparent;'; } else if(snippet_bgcolor_val != '') { snippet_bg_style += 'background:'+snippet_bgcolor_val+';'; } if(snippet_bg_style != '') { snippet_bg_style = ' style="'+snippet_bg_style+'"'; } } else if(snippet_theme_type_val == 'bg_theme') { if(snippet_theme_val == 'leather') { if(snippet_fixed_size == "size-s") { snippet_bg_style += ' style="position:absolute;left:31px;top:25px;"'; } else if(snippet_fixed_size == "size-m") { snippet_bg_style += ' style="position:absolute;left:47px;top:36px;"'; } else if(snippet_fixed_size == "size-l") { snippet_bg_style += ' style="position:absolute;left:56px;top:49px;"'; } } else if(snippet_theme_val == 'airmail') { if(snippet_fixed_size == "size-s") { snippet_bg_style += ' style="position:absolute;left:20px;top:16px;"'; } else if(snippet_fixed_size == "size-m") { snippet_bg_style += ' style="position:absolute;left:30px;top:20px;"'; } else if(snippet_fixed_size == "size-l") { snippet_bg_style += ' style="position:absolute;left:41px;top:27px;"'; } } else if(snippet_theme_val == 'standwood') { if(snippet_fixed_size == "size-s") { snippet_bg_style += ' style="position:absolute;left:20px;top:16px;"'; } else if(snippet_fixed_size == "size-m") { snippet_bg_style += ' style="position:absolute;left:29px;top:24px;"'; } else if(snippet_fixed_size == "size-l") { snippet_bg_style += ' style="position:absolute;left:39px;top:34px;"'; } } else if(snippet_theme_val == 'woodframe') { if(snippet_fixed_size == "size-s") { snippet_bg_style += ' style="position:absolute;left:15px;top:15px;"'; } else if(snippet_fixed_size == "size-m") { snippet_bg_style += ' style="position:absolute;left:19px;top:19px;"'; } else if(snippet_fixed_size == "size-l") { snippet_bg_style += ' style="position:absolute;left:25px;top:25px;"'; } } else if(snippet_theme_val == 'pinkframe') { if(snippet_fixed_size == "size-s") { snippet_bg_style += ' style="position:absolute;left:20px;top:16px;"'; } else if(snippet_fixed_size == "size-m") { snippet_bg_style += ' style="position:absolute;left:22px;top:22px;"'; } else if(snippet_fixed_size == "size-l") { snippet_bg_style += ' style="position:absolute;left:30px;top:31px;"'; } } else if(snippet_theme_val == 'darkvi') { if(snippet_fixed_size == "size-s") { snippet_bg_style += ' style="position:absolute;left:20px;top:16px;"'; } else if(snippet_fixed_size == "size-m") { snippet_bg_style += ' style="position:absolute;left:22px;top:22px;"'; } else if(snippet_fixed_size == "size-l") { snippet_bg_style += ' style="position:absolute;left:30px;top:31px;"'; } } else if(snippet_theme_val == 'blueframe') { if(snippet_fixed_size == "size-s") { snippet_bg_style += ' style="position:absolute;left:20px;top:16px;"'; } else if(snippet_fixed_size == "size-m") { snippet_bg_style += ' style="position:absolute;left:22px;top:22px;"'; } else if(snippet_fixed_size == "size-l") { snippet_bg_style += ' style="position:absolute;left:30px;top:31px;"'; } } else if(snippet_theme_val == 'tear') { if(snippet_fixed_size == "size-s") { snippet_bg_style += ' style="position:absolute;top:16px;"'; } else if(snippet_fixed_size == "size-m") { snippet_bg_style += ' style="position:absolute;top:22px;"'; } else if(snippet_fixed_size == "size-l") { snippet_bg_style += ' style="position:absolute;top:31px;"'; } } else if(snippet_theme_val == 'ontable') { if(snippet_fixed_size == "size-s") { snippet_bg_style += ' style="position:absolute;left:18px;top:10px;opacity:0.85;filter: alpha(opacity = 85);"'; } else if(snippet_fixed_size == "size-m") { snippet_bg_style += ' style="position:absolute;left:27px;top:6px;opacity:0.85;filter: alpha(opacity = 85);"'; } else if(snippet_fixed_size == "size-l") { snippet_bg_style += ' style="position:absolute;left:37px;top:20px;opacity:0.85;filter: alpha(opacity = 85);"'; } } else if(snippet_theme_val == 'shop') { if(snippet_fixed_size == "size-s") { snippet_bg_style += ' class="boxAB" style="margin:15px 0px 0px 1px;background:black;"'; } else if(snippet_fixed_size == "size-m") { snippet_bg_style += ' class="boxAB" style="margin:45px 0px 0px 1px;background:black;"'; } else if(snippet_fixed_size == "size-l") { snippet_bg_style += ' class="boxAB" style="margin:70px 0px 0px 1px;background:black;"'; } } } return snippet_bg_style; } function generateDecoration(snippet_code) { var deco_img_val = $("#deco_img").val(); if(deco_img_val == '') return snippet_code; var widthpoint = snippet_width_val; var heightpoint = snippet_height_val+snippet_bgpadding_val+20; snippet_code = "
"+snippet_code+"
"; if(deco_img_val == 'deco01') { snippet_code += "
"; } else if(deco_img_val == 'deco02') { var top = snippet_bgpadding_val-11; snippet_code += "
"; } else if(deco_img_val == "deco03"){ var width = snippet_width_val+(snippet_bgpadding_val*2); snippet_code += "
"; } else if(deco_img_val == "deco04"){ var width = snippet_width_val+snippet_bgpadding_val+4; var top = snippet_bgpadding_val-3; snippet_code += "
"; } else if(deco_img_val == "deco05"){ var width = snippet_width_val+snippet_bgpadding_val; var top = snippet_bgpadding_val+(snippet_height_val-70); snippet_code += "
"; } snippet_code += "
"; return snippet_code; } var gen_snippet_timeout = false; function generateSnippetCode(timeout) { if(gen_snippet_timeout) clearTimeout(gen_snippet_timeout); if(typeof timeout == 'undefined') timeout = 1000; getInputValue(); if(snippet_type_val == 'image') { if(snippet_width_val > 2000 || snippet_height_val > 2000 ) { $("#code-html-map-snippet").val(""); alert("ไม่สามารถกำหนดขนาดแผนที่เกิน 2000 x 2000 px ได้"); return; } if(snippet_hd_mode == 1) { setHdSizeText(snippet_width_val*2, snippet_height_val*2); } else { setHdSizeText(); } } gen_snippet_timeout = setTimeout(function() { getInputValue(); var snippet_code = ''; var param = '' var snippet_bg_style = generateSnippetStyle(); if(snippet_locale_val != '') { param += '&locale='+snippet_locale_val; } if(snippet_zoom_val != '') { param += '&zoom='+snippet_zoom_val; } if(snippet_mapmode_val != '') { param += '&mode='+snippet_mapmode_val; } if(snippet_mapversion_val != '') { param += '&map='+snippet_mapversion_val; } if(snippet_position_type_val == 'latlon') { param += '&lat='+snippet_latitude_val+'&long='+snippet_longitude_val; if(snippet_title_val != '') { param += '&title='+snippet_title_val; } if(snippet_detail_val != '') { param += '&detail='+snippet_detail_val; } } else { // snippet_position_type_val == 'poi' param += '&ooi='+snippet_poiid_val; if(snippet_title_val != '') { param += '&title='+snippet_title_val; } if(snippet_detail_val != '') { param += '&detail='+snippet_detail_val; } } if(snippet_type_val == 'iframe') { if(snippet_search_val != '') { param += '&search='+snippet_search_val; } if(snippet_tag_val != '') { param += '&tag='+snippet_tag_val; } if(snippet_zoombar_val != '') { param += '&zoombar='+snippet_zoombar_val; } if(snippet_toolbar_val != '') { param += '&toolbar='+snippet_toolbar_val; } if(snippet_mapselector_val != '') { param += '&mapselector='+snippet_mapselector_val; } if(snippet_scalebar_val != '') { param += '&scalebar='+snippet_scalebar_val; } if(snippet_centermark_val != '') { param += '¢ermark='+snippet_centermark_val; } if(snippet_marker_val) { param += '&tagicon='+snippet_marker_val+(snippet_marker_offsetx_val && snippet_marker_offsety_val ? '&iconposx='+snippet_marker_offsetx_val+'&iconposy='+snippet_marker_offsety_val : ''); } //if(param != '') { // param += '&hidepopup=true'; //} param = param.replace(/^&/, "?"); snippet_code = ''; } else { // snippet_type_val == 'image' var img_size_param = ""; if(snippet_width_val != '') { param += '&width='+snippet_width_val; } if(snippet_height_val != '') { param += '&height='+snippet_height_val; } if(snippet_marker_val) { var param_marker_position = getMarkerPostionParam(snippet_marker_position_val); if(snippet_position_type_val == 'latlon') { param += '&marker=position:'+snippet_latitude_val+','+snippet_longitude_val+';icon:'+snippet_marker_val+param_marker_position; } else { // poi param += '&pinmark=icon:'+snippet_marker_val+param_marker_position; } } if(snippet_hd_mode == 1) { param += '&HD=1'; img_size_param = ' width="'+snippet_width_val+'" height="'+snippet_height_val+'"'; } param = param.replace(/^&/, "?"); snippet_code = ''; } if(snippet_theme_type_val == 'bg_deco') { snippet_code = generateDecoration(snippet_code); } else if(snippet_theme_type_val == 'bg_theme') { snippet_code = generateSnippetTheme(snippet_code); } previewSnippet(snippet_code); }, timeout); } function setHdSizeText(width, height) { var size_txt = ""; if(width && height) { size_txt = "ขนาดไฟล์ที่ได้ "+width+" x "+height+" px"; } $("#snippet-hd-mode-size").html(size_txt); } function previewSnippet(snippet_code) { showLoading(); $("#code-html-map-snippet").val(snippet_code); if($("#preview-snippet-div").length == 1 && $("#preview-snippet-div").css('left') == "0px") { showPreviewSnippet(snippet_code); } hideLoading(); //showPreviewSnippet(); } function hidePreviewSnippet() { if(gen_snippet_timeout) clearTimeout(gen_snippet_timeout); $div = $("#preview-snippet-div"); if($div.length < 1) return; $div.animate({left: -$div.outerWidth()}); /*if($("#tools-snippet-button").val() == 'Cancel') { $("#tools-preview-snippet-button").show(); } else { $("#tools-preview-snippet-button").hide(); }*/ $("#tools-preview-snippet-button").show(); $("#tools-hide-snippet-button").hide(); } function showPreviewSnippet(snippet_code) { if(typeof snippet_code == 'undefined' && $("#code-html-map-snippet").val() == "") return; if($("#preview-snippet-div").length == 0) { $('#longdomap-tab').append('
\
\
Snippet Preview
\ \
\
\
\
\
\
'); } $div = $("#preview-snippet-div"); if($div.length < 1) return; $div.animate({left: $('#content-left').width()+23}); $div.width(snippet_width_val); $div.height(snippet_height_val); $("#tools-preview-snippet-button").hide(); $("#tools-hide-snippet-button").show(); if(typeof snippet_code == 'undefined') { snippet_code = $("#code-html-map-snippet").val(); } $("#preview-snippet").html(''+snippet_code+''); $("#preview-snippet").ready(function(){ //$("#preview-snippet-div .loading").hide(); //$("#preview-snippet-code-div").css('visibility', 'visible'); $("#preview-snippet").removeAttr("style"); $("#preview-snippet").css('position', 'absolute'); var preview_snippet_width = $("#preview-snippet")[0].scrollWidth+20; var preview_snippet_height = $("#preview-snippet")[0].scrollHeight+45; $("#preview-snippet").removeAttr("style"); var fit_width = $('#longdomap-tab').width()*(4/5); var fit_height = $('#longdomap-tab').height() - $("#preview-snippet-header").height() - 22; // 22: padding + border if(preview_snippet_width > fit_width) { $("#preview-snippet").width(fit_width); } if(preview_snippet_height > fit_height) { $("#preview-snippet").height(fit_height); } $("#preview-snippet-div").removeAttr("style"); }); } function showLoading() { $("#preview-snippet-div .loading").show(); } function enableCustomSnippetSize() { $("#snippet-width-setting, #snippet-height-setting").removeAttr("disabled"); $("#snippet-width-setting, #snippet-height-setting").removeClass('disabled'); } function disableCustomSnippetSize() { $("#snippet-width-setting, #snippet-height-setting").attr("disabled",true); $("#snippet-width-setting, #snippet-height-setting").addClass('disabled'); } function hideLoading() { $("#preview-snippet").find("iframe, img").one('load', function() { $("#preview-snippet-div .loading").hide(); }).each(function() { if(this.complete) $(this).load(); }); } function getInputValue() { snippet_type_val = $("#iframe-snippet").is(":checked") ? 'iframe' : 'image'; snippet_hd_mode = $("#snippet-hd-mode").is(":checked") ? '1' : '0'; snippet_zoom_val = Number($("#zoom").val()); snippet_width_val = Number($("#snippet-width-setting").val()); snippet_height_val = Number($("#snippet-height-setting").val()); snippet_title_val = $("#marker-popup").is(":checked") ? $("#snippet-title").val() : ''; snippet_detail_val = $("#marker-popup").is(":checked") ? $("#snippet-detail").val() : ''; snippet_locale_val = $("#maplang").val(); snippet_mapversion_val = $("#map-version").val(); snippet_zoombar_val = $("#checkzoomer").val(); snippet_toolbar_val = $("#checktool").val(); snippet_mapselector_val = $("#checkselector").val(); snippet_scalebar_val = $("#checkscale").val(); snippet_centermark_val = $("#checkcentermark").val(); snippet_mapmode_val = encodeURIComponent($("#mode-selector-select").val()+(snippet_locale_val=='en' ? '-en' : '')); snippet_bgcolor_val = $("#snippet-bg-color").val(); snippet_bgurl_val = $("#urlbg").val(); snippet_bgpadding_val = Number($("#snippet-bg-padding").val()); snippet_marker_val = $("#marker-pin").is(":checked") ? $("#marker").val() : ''; snippet_marker_position_val = $("#marker-pin").is(":checked") ? $("#pin-position").val() : ''; snippet_marker_offsetx_val = Number($("#snippet-pin-offset-x").val()); snippet_marker_offsety_val = Number($("#snippet-pin-offset-y").val()); snippet_latitude_val = Number($("#latitude").val()); snippet_longitude_val = Number($("#longitude").val()); snippet_poiid_val = $("#longdomapid").val(); snippet_position_type_val = $("#snippet-location-by-poiid").is(":checked") ? 'poi' : 'latlon'; snippet_theme_type_val = $("#snippet-theme-type-setting").val(); snippet_theme_val = $("#theme-option-background").val(); snippet_fixed_size = $("#sizes").is(":checked") ? 'size-s' : ($("#sizem").is(":checked") ? 'size-m' : ($("#sizel").is(":checked") ? 'size-l' : 'size-custom') ); snippet_search_val = $("#snippet-search").val(); snippet_tag_val = $("#snippet-tag").val(); } function setSnippetTheme(theme, timeout) { if(typeof theme == 'undefined') { theme = $("#theme-option-background").val(); } if(theme == 'nonetype') { theme = 'default'; } $('.snippet-thumbnail-theme').removeClass('snippet-thumbnail-theme-selected') $('.snippet-theme-'+theme).parent().addClass('snippet-thumbnail-theme-selected'); if($("#theme-option-background option[value='"+theme+"']").length !== 0) { $("#theme-option-background").val(theme); } var theme_type_snippet = (theme == 'default' ? "none-theme" : "bg_theme"); $("#snippet-theme-type-setting").val(theme_type_snippet); if(theme == 'default') { $("#bg-theme-config").hide(); } else { $("#bg-theme-config").show(); } if(theme_type_snippet == 'bg_theme' && $("#sizecustom").is(":checked")) { $("#"+default_snippet_fixed_size).click(); } if(theme != "colorframe") { $("#deco-config").hide(); } if(theme == 'shop') { $("#theme-animation").show(); } else { $("#theme-animation").hide(); } generateSnippetCode(timeout); } function createSnippetCodeByOOIID(ooiid) { if(!$("#content-menu-tools").hasClass('menu-top-active')) { $("#content-menu-tools").click(); setcontent_whenclicktab('menu-tools') } if($("#tools-snippet-button").val() != 'Cancel') { $("#tools-snippet-button").click(); } $("#snippet-location-by-poiid").click(); $("#longdomapid").val(ooiid); $("#zoom").val(16); generateSnippetCode(0); setTimeout('$("#code-html-map-snippet").focus();$("#code-html-map-snippet").select(); showPreviewSnippet();', 100); }// $Id: autocomplete.js,v 1.17 2007/01/09 07:31:04 drumm Exp $ /** * Attaches the autocomplete behaviour to all required fields */ Drupal.autocompleteAutoAttach = function () { var acdb = []; $('input.autocomplete').each(function () { var uri = this.value; if (!acdb[uri]) { acdb[uri] = new Drupal.ACDB(uri); } var input = $('#' + this.id.substr(0, this.id.length - 13)) .attr('autocomplete', 'OFF')[0]; $(input.form).submit(Drupal.autocompleteSubmit); new Drupal.jsAC(input, acdb[uri]); }); } /** * Prevents the form from submitting if the suggestions popup is open * and closes the suggestions popup when doing so. */ Drupal.autocompleteSubmit = function () { return $('#autocomplete').each(function () { this.owner.hidePopup(); }).size() == 0; } /** * An AutoComplete object */ Drupal.jsAC = function (input, db) { var ac = this; this.input = input; this.db = db; $(this.input) .keydown(function (event) { return ac.onkeydown(this, event); }) .keyup(function (event) { ac.onkeyup(this, event) }) .blur(function () { ac.hidePopup(); ac.db.cancel(); }); }; /** * Handler for the "keydown" event */ Drupal.jsAC.prototype.onkeydown = function (input, e) { if (!e) { e = window.event; } switch (e.keyCode) { case 40: // down arrow this.selectDown(); return false; case 38: // up arrow this.selectUp(); return false; default: // all other keys return true; } } /** * Handler for the "keyup" event */ Drupal.jsAC.prototype.onkeyup = function (input, e) { if (!e) { e = window.event; } switch (e.keyCode) { case 16: // shift case 17: // ctrl case 18: // alt case 20: // caps lock case 33: // page up case 34: // page down case 35: // end case 36: // home case 37: // left arrow case 38: // up arrow case 39: // right arrow case 40: // down arrow return true; case 9: // tab case 13: // enter case 27: // esc this.hidePopup(e.keyCode); return true; default: // all other keys if (input.value.length > 0) this.populatePopup(); else this.hidePopup(e.keyCode); return true; } } /** * Puts the currently highlighted suggestion into the autocomplete field */ Drupal.jsAC.prototype.select = function (node) { this.input.value = node.autocompleteValue; } /** * Highlights the next suggestion */ Drupal.jsAC.prototype.selectDown = function () { if (this.selected && this.selected.nextSibling) { this.highlight(this.selected.nextSibling); } else { var lis = $('li', this.popup); if (lis.size() > 0) { this.highlight(lis.get(0)); } } } /** * Highlights the previous suggestion */ Drupal.jsAC.prototype.selectUp = function () { if (this.selected && this.selected.previousSibling) { this.highlight(this.selected.previousSibling); } } /** * Highlights a suggestion */ Drupal.jsAC.prototype.highlight = function (node) { if (this.selected) { $(this.selected).removeClass('selected'); } $(node).addClass('selected'); this.selected = node; } /** * Unhighlights a suggestion */ Drupal.jsAC.prototype.unhighlight = function (node) { $(node).removeClass('selected'); this.selected = false; } /** * Hides the autocomplete suggestions */ Drupal.jsAC.prototype.hidePopup = function (keycode) { // Select item if the right key or mousebutton was pressed if (this.selected && ((keycode && keycode != 46 && keycode != 8 && keycode != 27) || !keycode)) { this.input.value = this.selected.autocompleteValue; } // Hide popup var popup = this.popup; if (popup) { this.popup = null; $(popup).fadeOut('fast', function() { $(popup).remove(); }); } this.selected = false; } /** * Positions the suggestions popup and starts a search */ Drupal.jsAC.prototype.populatePopup = function () { // Show popup if (this.popup) { $(this.popup).remove(); } this.selected = false; this.popup = document.createElement('div'); this.popup.id = 'autocomplete'; this.popup.owner = this; $(this.popup).css({ marginTop: this.input.offsetHeight +'px', width: (this.input.offsetWidth - 4) +'px', display: 'none' }); $(this.input).before(this.popup); // Do search this.db.owner = this; this.db.search(this.input.value); } /** * Fills the suggestion popup with any matches received */ Drupal.jsAC.prototype.found = function (matches) { // If no value in the textfield, do not show the popup. if (!this.input.value.length) { return false; } // Prepare matches var ul = document.createElement('ul'); var ac = this; for (key in matches) { if(typeof matches[key] != "string") continue; var li = document.createElement('li'); $(li) .html('
'+ matches[key] +'
') .mousedown(function () { ac.select(this); }) .mouseover(function () { ac.highlight(this); }) .mouseout(function () { ac.unhighlight(this); }); li.autocompleteValue = key; $(ul).append(li); } // Show popup with matches, if any if (this.popup) { if (ul.childNodes.length > 0) { $(this.popup).empty().append(ul).show(); } else { $(this.popup).css({visibility: 'hidden'}); this.hidePopup(); } } } Drupal.jsAC.prototype.setStatus = function (status) { switch (status) { case 'begin': $(this.input).addClass('throbbing'); break; case 'cancel': case 'error': case 'found': $(this.input).removeClass('throbbing'); break; } } /** * An AutoComplete DataBase object */ Drupal.ACDB = function (uri) { this.uri = uri; this.delay = 300; this.cache = {}; } /** * Performs a cached and delayed search */ Drupal.ACDB.prototype.search = function (searchString) { var db = this; this.searchString = searchString; // See if this key has been searched for before if (this.cache[searchString]) { return this.owner.found(this.cache[searchString]); } // Initiate delayed search if (this.timer) { clearTimeout(this.timer); } this.timer = setTimeout(function() { db.owner.setStatus('begin'); // Ajax GET request for autocompletion $.ajax({ type: "GET", url: db.uri +'/'+ Drupal.encodeURIComponent(searchString), success: function (data) { // Parse back result var matches = Drupal.parseJson(data); if (typeof matches['status'] == 'undefined' || matches['status'] != 0) { db.cache[searchString] = matches; // Verify if these are still the matches the user wants to see if (db.searchString == searchString) { db.owner.found(matches); } db.owner.setStatus('found'); } }, error: function (xmlhttp) { alert('An HTTP error '+ xmlhttp.status +' occured.\n'+ db.uri); } }); }, this.delay); } /** * Cancels the current autocomplete request */ Drupal.ACDB.prototype.cancel = function() { if (this.owner) this.owner.setStatus('cancel'); if (this.timer) clearTimeout(this.timer); this.searchString = ''; } // Global Killswitch if (Drupal.jsEnabled) { $(document).ready(Drupal.autocompleteAutoAttach); } /*** ajax-client.js ***/ function checkPositiveInt(val){ var result = val.match(/^\d+$/); return (result != null && result != 0); } function createRequestObject() { var ro; var browser = navigator.appName; if(browser == "Microsoft Internet Explorer"){ ro = new ActiveXObject("Microsoft.XMLHTTP"); }else{ ro = new XMLHttpRequest(); } return ro; } function handleResponse(myhttp, overlay) { if(myhttp.readyState == 4){ var response = myhttp.responseText; var update = new Array(); if(response.indexOf("?xml") == 1 ) { // not use the less-than bracket to avoid PHP problem // parse the XML var xmlresponse = myhttp.responseXML.documentElement; if ( xmlresponse.getElementsByTagName('searchresult') ) { var param = xmlresponse.getElementsByTagName('param'); var request=param[0].getAttribute("request"); var imgid=param[0].getAttribute("imgid"); var dispimg=param[0].getAttribute("dispimg"); var zoom=param[0].getAttribute("zoom"); var resultname=param[0].getAttribute("resultname"); var resultname_en=param[0].getAttribute("resultname_en"); var bookmark=parseInt(param[0].getAttribute("bookmark")); var hasmore=param[0].getAttribute("hasmore"); var forcezoom=param[0].getAttribute("forcezoom"); var search_key=param[0].getAttribute("search"); var pois = xmlresponse.getElementsByTagName('searchobject'); var servicesearch = param[0].getAttribute('service'); var servicelongdosearch = (typeof servicesearch == 'undefined' || servicesearch == '' || servicesearch == null || servicesearch == 'longdo'); var next_token = param[0].getAttribute('nexttoken'); var gg_html_attribute = servicesearch=='google' ? param[0].getAttribute('gghtmlattribute') : ''; var searchdiv = param[0].getAttribute('searchdiv'); var searchform = searchdiv == 'routing-result' ? 'routing' : 'location'; var prefixdiv = searchdiv == 'routing-result' ? 'routing-' : ''; var title_hilight_location = (mylang == 'th' ? 'คลิกเพื่อดูสถานที่นี้' : 'Click to hi-light this location'); var title_zoom_location = (mylang == 'th' ? 'คลิกเพื่อซูมไปยังสถานที่นี้' : 'Click to hi-light and ZOOM to this location'); var title_image_location = (mylang == 'th' ? 'คลิกเพื่อดูภาพของสถานที่นี้' : 'Click to view this location\'s images'); var title_event_location = (mylang == 'th' ? 'คลิกเพื่อดูเหตุการณ์ของสถานที่นี้' : 'Click to view this location\'s events'); var title_add_destination = (mylang == 'th' ? 'คลิกเพื่อเลือกเป็นจุดหมายการเดินทาง' : 'Click to add destination'); var title_view_road = (mylang == 'th' ? 'คลิกเพื่อดูสายทาง' : 'Click to hi-light this alley/road'); var title_see_more_result = (mylang == 'th' ? 'คลิกเพื่อดูผลลัพธ์การค้นหาเพิ่มเติม' : 'Click to see more search results'); var type_road_text = (mylang == "en" ? 'Alley/Road' : 'ถนน/ซอย'); var type_khet_text = (mylang == "en" ? 'Boundary of Administrator' : 'ขอบเขตการปกครอง'); var type_place_text = (mylang == "en" ? 'Place' : 'สถานที่'); var type_water_text = (mylang == "en" ? 'River/Canal' : 'แม่น้ำ/คลอง'); var type_layer_text = (mylang == "en" ? 'Layer' : 'เลเยอร์แผนที่'); //var type_panorama_text = (mylang == "en" ? 'Panorama' : 'ภาพพาโนรามา'); var txt_no_search_result = (mylang == "en" ? 'Sorry, no result found.' : 'ไม่พบผลลัพธ์การค้นหา'); var txt_enter_more_info = (mylang == "en" ? 'Please enter at least %d characters' : 'โปรดระบุอย่างน้อย %d ตัวอักษร'); var txt_search_other_services = (mylang == "en" ? 'Other search services' : 'ค้นหาจากบริการอื่น'); var txt_more = (mylang == "en" ? 'more' : 'เพิ่มเติม'); if(servicelongdosearch) servicesearch = 'longdo'; var search_by = mylang == 'en' ? ' by ' : 'จาก '; switch(servicesearch) { case 'osm': search_by += 'Open Street Map'; break; case 'google': search_by += 'Google'; break; case 'foursquare': search_by += 'Foursquare'; break; case 'longdo': search_by += 'Longdo Map'; break; default: search_by += servicesearch; break; } var points = xmlresponse.getElementsByTagName('pointobject'); // for showobject n_points = points ? points.length : 0; var n_pois=0; if (pois) n_pois = pois.length; if (request == "getpois") { poi_saved[zoom][imgid] = new Array(); poi_num[zoom][imgid] = n_pois; for (var i = 0 ; i < n_pois; i++) { var item = pois[i]; var id=item.getAttribute("id"); var name=item.getAttribute("name"); var lat=item.getAttribute("lat"); var mylong=item.getAttribute("long"); var type=item.getAttribute("type"); var status=item.getAttribute("status"); var showlevel=item.getAttribute("showlevel"); var name_en=item.getAttribute("name_en"); var contributor=item.getAttribute("contributor"); var imagefile=item.getAttribute("imagefile"); var iconlabel=item.getAttribute("iconlabel"); var iconlabel_en=item.getAttribute("iconlabel_en"); var iconlabel_en=item.getAttribute("iconlabel_en"); // save to poi array poi_saved[zoom][imgid][i] = new Array(); var usename = name; if (mylang == "en") { usename = name_en; if (name_en == "") { usename = "(Thai) " + name; } } var useiconlabel = iconlabel; if (mylang == "en") { useiconlabel = iconlabel_en; } poi_saved[zoom][imgid][i][0] = id; poi_saved[zoom][imgid][i][1] = usename; poi_saved[zoom][imgid][i][2] = lat; poi_saved[zoom][imgid][i][3] = mylong; poi_saved[zoom][imgid][i][4] = status; poi_saved[zoom][imgid][i][5] = contributor; poi_saved[zoom][imgid][i][6] = imagefile; poi_saved[zoom][imgid][i][7] = useiconlabel; //drawPOI(id,name,lat,mylong,status,zoom,dispimg,i); } drawPOIFromArray(zoom,imgid,dispimg); // hide the unused image var oldnum = poi_images_num[dispimg]; if (n_pois < oldnum ) { for (var i = n_pois ; i < oldnum ; i++) { //poi_images[dispimg][i].style.visibility = "hidden"; mymap.removeChild(poi_images[dispimg][i]); // remove and recreate seems to be faster! //poi_images_label[dispimg][i].style.visibility = "hidden"; //poi_images_label[dispimg][i].style.width = "0px"; //poi_images_label[dispimg][i].innerHTML = ""; mymap.removeChild(poi_images_label[dispimg][i]); } } poi_images_num[dispimg] = n_pois; } else if ( request == "searchresultsxml") { search_results_poi = new Array(); var shortdesc_limit = mylang == 'th' ? 60 : 70; var searchresultshtml = ''; var rs_table_id = prefixdiv+'search-result-list'+(servicesearch ? '-'+servicesearch : ''); //if (!servicelongdosearch && n_pois == 0) { //return; //} if(bookmark == 0) { if(!servicelongdosearch) { searchresultshtml += '
'+(mylang=='en' ? 'Search results' : 'ผลลัพธ์')+search_by+'
'; } searchresultshtml += ''; } var flipflop = 'odd'; if (n_pois > 0) { // google mode // if (currentmode == "gmap") { // gmap.clearMarkers(); // } for (var i = 0 ; i < n_pois; i++) { var item = pois[i]; var id=item.getAttribute("id"); var name=item.getAttribute("name"); var lat=item.getAttribute("lat"); var mylong=item.getAttribute("long"); var type=item.getAttribute("objecttype"); var showlevel=item.getAttribute("showlevel"); var name_en=item.getAttribute("name_en"); var shortdesc=item.getAttribute("shortdesc"); var shortdesc_en=item.getAttribute("shortdesc_en"); var markicon = item.getAttribute('markicon'); var geocode = item.getAttribute('geocode'); var lucene_sign = item.getAttribute('bylucene') == 1 ? ' *' : ''; var showonmap = parseFloat(item.getAttribute('showonmap')); if(typeof showonmap == 'undefined' || showonmap == null || isNaN(showonmap)) showonmap = 0; markicon = markicon.split("^", 2); var markicon_title = typeof markicon[1] == "string" ? markicon[1] : ''; if(markicon_title != '') { markicon_title = markicon_title.replace(/'/g, "'"); markicon_title = markicon_title.replace(/"/g, """); markicon_title = ' title="'+markicon_title+'"'; } markicon = markicon[0]; var num_location_image=item.getAttribute("num_location_image"); var num_location_event=item.getAttribute("num_location_event"); var countlabel = bookmark + 1 + i; var search_result_icon = ""; //alert(id+","+name+","+lat+","+mylong+","+ showlevel + ", " +i); // save to poi array search_results_poi[i] = new Array(); var usename = mylang == "en" ? ( name_en ? name_en : name) : (name ? name : name_en); usename_org = usename+lucene_sign; usename = usename.replace(/'/g, "\\'"); usename = usename.replace(/"/g, """); var usedesc = mylang=='th' ? (shortdesc ? shortdesc : shortdesc_en) : (shortdesc_en ? shortdesc_en : shortdesc); usedesc = stripHtml(usedesc); search_results_poi[i][0] = id; search_results_poi[i][1] = usename; search_results_poi[i][2] = lat; search_results_poi[i][3] = mylong; search_results_poi[i][4] = type; search_results_poi[i][5] = showlevel; search_results_poi[i][6] = showonmap; // google mode // if (currentmode == "gmap") { // gmap.addMarker(lat,mylong,usename); // } var type_text = ''; switch(type) { case 'road': type_text = type_road_text; break; case 'tag': type_text = 'Tag'; break; case 'khet': type_text = type_khet_text; break; case 'water-line': case 'water-area': type_text = type_water_text; break; case 'layer': type_text = type_layer_text; break; //case 'panorama': // type_text = type_panorama_text; // break; default: type_text = type_place_text; break; } searchresultshtml += ''; flipflop = (flipflop == 'even' ? 'odd' : 'even'); searchresultshtml += ""; // countlabel searchresultshtml += '"; } // pager //searchresultshtml += ""; //if (n_pois > 20) { if (hasmore == "true") { searchresultshtml += ""; searchresultshtml += ""; } if(gg_html_attribute) { gg_html_attribute = gg_html_attribute.replace(/"; } } else { // no result if(bookmark == 0) { var at_least_characters = 2; if(search_key.length >= at_least_characters) { searchresultshtml += ""; } else { searchresultshtml += ""; } } } if(bookmark == 0) { searchresultshtml += "
'; var zoom = mapZoom(); var zoomimg = ""; if(searchdiv != 'routing-result') { zoomimg = (browser=='IE' && version<=6) ? "" : ""; } var viewimg = ""; if(searchdiv != 'routing-result' && num_location_image>0) { viewimg += (browser=='IE' && version<=6) ? "" : " "; } var eventimg = ""; if(searchdiv != 'routing-result' && num_location_event>0) { eventimg += (browser=='IE' && version<=6) ? "" : " "; } var routeimg = false; if(searchdiv == 'routing-result') { routeimg = true; } if (type == "poi" || type == "foursquare-poi" || type == "google-poi" || type == "osm-poi") { var name_padded = id; var markpoijs = 'selectMapTab();'; var markpoiandzoomjs = 'selectMapTab();'; if(type == "poi") { while (name_padded.length < 8) name_padded = "0" + name_padded; if (n_pois == 1) { markpoijs += 'markPOIandZoom(' + '\''+id+'\'' + ",'" + usename + "'," + lat +',' + mylong + ", 17 , '', 1);"; } else { markpoijs += 'markPOI(' + '\''+id+'\'' + ",'" + usename + "'," + lat +',' + mylong + ", " + zoom + " , '');"; } markpoiandzoomjs += 'markPOIandZoom(' + '\''+id+'\'' + ",'" + usename + "'," + lat +',' + mylong + "," + showlevel + ", '', 1);"; } else { //if(type == "foursquare-poi") { if (n_pois == 1) { markpoijs += 'markPOIandZoom(' + '\''+id+'\'' + ",'" + usename + "'," + lat +',' + mylong + ", 17 , '', 1);"; } else { markpoijs += 'markOtherServiceSearchPOI(' + '\''+id+'\'' + ",'" + usename + "'," + lat +',' + mylong + ", " + zoom + ");"; } markpoiandzoomjs += 'markOtherServiceSearchPOI(' + '\''+id+'\'' + ",'" + usename + "'," + lat +',' + mylong + "," + showlevel + ", 1);"; } searchresultshtml += '' + usename_org + ""; if(zoomimg!="") { search_result_icon += ' ' + zoomimg + ""; } if(viewimg!="") { search_result_icon += ' ' + viewimg + ''; } if(eventimg!="") { search_result_icon += ' ' + eventimg + ''; } if(routeimg) { search_result_icon += ' '; } } else if (type == "road") { searchresultshtml += '' + usename_org + ""; if(zoomimg!="") { search_result_icon += ' ' + zoomimg + ""; } if(routeimg) { search_result_icon += ' '; } } else if (type == "khet") { var js_func = ''; var zoom_js_func = ''; if(geocode) { js_func = 'focusLongdoPOI('+lat+', '+mylong+', '+geocode+', false, \'IG\');'; zoom_js_func = 'focusLongdoPOI('+lat+', '+mylong+', '+geocode+', true, \'IG\');'; } else { js_func = 'markPOI(-1 ,\'' + usename + '\',' + lat +',' + mylong + ', ' + zoom + ', \'
'+usedesc+'\');'; zoom_js_func = 'markPOIandZoom(-1 ,\'' + usename + '\',' + lat +',' + mylong + ', ' + zoom + ', \'
'+usedesc+'\');'; } if (lat && mylong) { searchresultshtml += '' + usename_org + ""; } else { // probably only KWANG here searchresultshtml += '' + usename_org + ""; } if(zoomimg!="") { search_result_icon += ' ' + zoomimg + ""; } if(routeimg) { search_result_icon += ' '; } } else if (type == "tag") { var tagname = name.replace(/^tag: /, ""); searchresultshtml += '' + name + ""; } else if (type == "geom") { var name_padded = id; while (name_padded.length < 8) name_padded = "0" + name_padded; searchresultshtml += '' + name + ""; if(viewimg!="") { search_result_icon += ' ' + viewimg + ''; } if(eventimg!="") { search_result_icon += ' ' + eventimg + ''; } if(routeimg) { search_result_icon += ' '; } } else if (type == "map" || type == "layer") { var name_padded = id; var ooi_prefix = (type == "map") ? 'M' : 'Y'; while (name_padded.length < 8) name_padded = "0" + name_padded; searchresultshtml += '' + name + ""; if(viewimg!="") { search_result_icon += ' ' + viewimg + ''; } if(eventimg!="") { search_result_icon += ' ' + eventimg + ''; } // } else if (type == "Panorama") { // var name_padded = id; // var ooi_prefix = 'P'; // while (name_padded.length < 8) name_padded = "0" + name_padded; // searchresultshtml += '' + name + ""; } else { var name_padded = id; var ds_type = ""; if (type == "water-line") { ooi_prefix = 'X'; ds_type = ooi_prefix + "ID"; } else if(type == "water-area") { ooi_prefix = 'W'; ds_type = ooi_prefix + "ID"; } else if(type == "building") { ooi_prefix = 'B'; ds_type = ooi_prefix + "ID"; } else if(type == "bus") { ooi_prefix = 'S'; ds_type = ooi_prefix + "ID"; } if (ds_type != '') { while (name_padded.length < 8) name_padded = "0" + name_padded; searchresultshtml += '' + name + ""; if(zoomimg!="") { search_result_icon += ' ' + zoomimg + ""; } } } if(search_result_icon != '') { search_result_icon = '
'+search_result_icon+'
'; searchresultshtml += search_result_icon; } if(typeof(usedesc) != "undefined" && usedesc != "") { searchresultshtml += "
"+ usedesc.substr(0,shortdesc_limit) + (usedesc.length > shortdesc_limit ? "..." : "") + ""; } searchresultshtml += "
"; var nextbookmark = bookmark + n_pois; var more_result_func = 'setBookmark('+ nextbookmark + ', false, \''+searchform+'\'); doPreviousSearch(\''+search_key+'\', \''+searchform+'\');'; if(typeof(servicesearch) == 'string' && servicesearch == 'google') more_result_func = 'setBookmark('+ nextbookmark + ', \''+servicesearch+'\', \''+searchform+'\'); searchOtherService(\''+search_key+'\', \'google\', \''+next_token+'\', \''+searchform+'\');'; else if(typeof(servicesearch) == 'string' && servicesearch == 'foursquare') more_result_func = 'setBookmark('+ nextbookmark + ', \''+servicesearch+'\', \''+searchform+'\'); searchOtherService(\''+search_key+'\', \'foursquare\', \''+next_token+'\', \''+searchform+'\');'; else if(typeof(servicesearch) == 'string' && servicesearch == 'osm') more_result_func = 'setBookmark('+ nextbookmark + ', \''+servicesearch+'\', \''+searchform+'\'); searchOtherService(\''+search_key+'\', \'osm\', \''+next_token+'\', \''+searchform+'\');'; searchresultshtml += '
 '+txt_more+'
'; searchresultshtml += "
"+txt_no_search_result+"
"+txt_enter_more_info.replace('%d', at_least_characters)+"
"; if(servicelongdosearch) { searchresultshtml += "
"+txt_search_other_services+": "; if(typeof(servicesearch) == 'string' && servicesearch != 'longdo') searchresultshtml += ""; if(typeof(servicesearch) != 'string' || servicesearch != 'foursquare') searchresultshtml += ""; if(typeof(servicesearch) != 'string' || servicesearch != 'google') searchresultshtml += ""; if(typeof(servicesearch) != 'string' || servicesearch != 'osm') searchresultshtml += ""; searchresultshtml += "
"; showDiv(searchdiv, searchresultshtml); } else { $('#'+prefixdiv+'search-with-other-services').before(searchresultshtml); } } else if(document.getElementById(prefixdiv+'search-result-list'+(servicesearch ? '-'+servicesearch : ''))) { if(document.getElementById(prefixdiv+"more-search-result-loading"+(servicesearch ? '-'+servicesearch : ''))) { document.getElementById(prefixdiv+"more-search-result-loading"+(servicesearch ? '-'+servicesearch : '')).style.display = 'none'; } $(searchresultshtml).appendTo('#'+prefixdiv+'search-result-list'+(servicesearch ? '-'+servicesearch : '')); } //var isMMSnippet = false; if (document.getElementById('isMMMapSnippet') != null) { // isMMSnippet = true; mapZoom(20); // for set appropriate zoom } var showingmark = true; //if (showingmark != -1 && showingmark && (isMMSnippet || forcezoom == 1)) { if (showingmark != -1 && showingmark && (forcezoom == 1)) { _setAllSearchResultsPOIVisible(false, searchform); }else if (showingmark != -1 && showingmark){ var longdo_num_pois = 0; if(!servicelongdosearch) longdo_num_pois = document.getElementById('search-result-list-longdo') ? document.getElementById('search-result-list-longdo').getAttribute("num_pois") : 0; var auto_zoomout = servicelongdosearch ? true : (longdo_num_pois > 0 ? false : true); _setAllSearchResultsPOIVisible(auto_zoomout, searchform); } // if (showingmark != -1 && showingmark){ // setAllSearchResultsPOIVisible(true); // } if(servicelongdosearch) { if (n_pois == 1) { /* if(document.getElementById('search_result_zoom_0')) document.getElementById('search_result_zoom_0').onclick(); else document.getElementById('search_result_0').onclick(); */ if(searchform == 'location') document.getElementById('search_result_0').onclick(); else if (searchform == 'routing') { document.getElementById('search_result_route_0').onclick(); } } if(n_pois <= 3) { searchOtherService(search_key, 'all', false, searchform); } } if (currentactive_tab == "pois") { adjust_searchresult('false',pois.length) } } else if ( request == "showpoi") { if (n_pois > 0) { var item = pois[0]; var id=item.getAttribute("id"); var name=item.getAttribute("name"); var lat=item.getAttribute("lat"); var mylong=item.getAttribute("long"); var type=item.getAttribute("type"); var status=item.getAttribute("status"); var showlevel=item.getAttribute("showlevel"); var name_en=item.getAttribute("name_en"); var dozoom=item.getAttribute("dozoom"); var hidepopup=item.getAttribute("hidepopup"); var forcezoomlevel=item.getAttribute("forcezoomlevel"); if(forcezoomlevel > 0) { showlevel = forcezoomlevel; dozoom = 2; // forcezoom } var usename = name; if (mylang == "en") { if (name_en != "") usename = name_en; else usename = "(Thai) " + name; } if(hidepopup == "1") { markPoint(id,usename,lat,mylong); if((dozoom && dozoom != '0') || forcezoomlevel > 0) { if ( showlevel > mapZoom() || forcezoomlevel > 0) { mapZoom(showlevel); } } moveLocation(lat,mylong); } else { markPOIandZoom(id,usename,lat,mylong,showlevel,"",dozoom); } /* markPOI(id,usename,lat,mylong,showlevel,""); if (dozoom == "1") { mapZoom(showlevel); } */ } } else if ( request == "showobject") { if (n_pois > 0) { var item = pois[0]; var id=item.getAttribute("id"); var dozoom=item.getAttribute("dozoom"); var hidepopup=item.getAttribute("hidepopup"); var forcezoomlevel=item.getAttribute("forcezoomlevel"); var ds='LONGDO'; if(/^L/.test(id)) { ds = 'RID'; } dozoom = (dozoom && dozoom != '0'); if(forcezoomlevel > 0) { mapZoom(forcezoomlevel); } hidePopup = (hidepopup == "1") ? true : false; showLongdoPOI(id, dozoom, ds, hidePopup); //mmmap.showObject({"id":id, "dozoom":1, "ds":ds}); } } } } else if(response.indexOf('|') != -1) { update = response.split('|'); var elementname = removeNL(update[0]); showDiv(elementname, removeNL(update[1])); // SUPER HACK if (elementname == "locationdetails_contents") { showLocationdetailsDiv(overlay, removeNL(update[1])); } } myhttp = null; // garbage collection } } function removeNL(s) { /* ** Remove NewLine, CarriageReturn and Tab characters from a String ** s string to be processed ** returns new string */ r = ""; for (i=0; i < s.length; i++) { if (s.charAt(i) != '\n' && s.charAt(i) != '\r' && s.charAt(i) != '\t') { r += s.charAt(i); } } return r; } function showDiv(divname, contents) { if (window.document.getElementById(divname) != null) { window.document.getElementById(divname).innerHTML = contents; } } function showLocationdetailsDiv(overlay, contents) { updateActivePopupContent(contents, overlay); setTimeout(function(){ if($('.ldmap_popup_detail a[rel^="prettyText"]') && $('.ldmap_popup_detail a[rel^="prettyText"]').length > 0) { if($('.ldmap_popup_detail a[rel^="prettyText"]').prettyPhoto) { $('.ldmap_popup_detail a[rel^="prettyText"]').removeAttr("target"); $('.ldmap_popup_detail a[rel^="prettyText"]').prettyPhoto({default_width: 400,default_height: 60}); } } //if($("#location_popup_title") && $("#location_popup_title").length > 0 && $("#detail_0") && $("#detail_0").length > 0) { // $("#location_popup_title").removeAttr('onclick'); // $("#location_popup_title").unbind('click').click(function(){ // eval($("#detail_0").attr('href').replace('javascript:', '')); // }); //} if($("#snippet_0") && $("#snippet_0").length > 0) { $("#snippet_0").click(function(event){ event.stopPropagation(); var ooiid = $("#snippet_0").attr('rel'); createSnippetCodeByOOIID(ooiid); return false; }); } if($("#link_0") && $("#link_0").length > 0 && typeof $.prettyPhoto == 'object') { var permalink_href = $("#link_0").attr('href') + '#?permalink=true'; $("#link_0").attr('href', permalink_href); } }, 500); _resizeLongdoMapLocationPopupContent(); setTimeout(function(){ _resizeLongdoMapLocationPopupContent(); }, 200); } function _resizeLongdoMapLocationPopupContent() { var main_popup_h = $(".ldmap_popup_mini").length > 0 ? $(".ldmap_popup_mini").height() : 224; if($(".longdomap-popup-contents") && $(".longdomap-popup-contents").length > 0 && $(".longdomap-popup-footer") && $(".longdomap-popup-footer").length > 0) { var max_h = main_popup_h; var footer_h = $(".longdomap-popup-footer").height(); if ($(".ldmap_popup_detail") && $(".ldmap_popup_detail").length > 0 && $(".ldmap_popup_detail").css('max-height') && isInt($(".ldmap_popup_detail").css('max-height'))) { max_h = $(".ldmap_popup_detail").css('max-height') - footer_h; } else if ($(".ldmap_popup_mini").length > 0) { var title_h = $(".ldmap_popup_title").height(); max_h = max_h - footer_h - title_h - 8 - 3 - 8 - 2; // 8, 3, 8 : padding } if ($.browser && ($.browser.msie || !!navigator.userAgent.match(/Trident\/7\./))) { $(".longdomap-popup-contents").width($(".longdomap-popup-contents").width()+15); } $(".longdomap-popup-contents").css('overflow-y', 'auto'); $(".longdomap-popup-contents").css('max-height', max_h+'px'); $(".ldmap_popup_detail").addClass('longdomap-popup-location-detail'); } } function _setAllSearchResultsPOIVisible(allowed_zoomout, searchform) { if ( ! search_results_poi || search_results_poi.length <= 0 ) return; var resetSearchAndTagResults = isResetSearchAndTagResults(); if(resetSearchAndTagResults) { clearAllSearchLocationPin(); } clearAllPopup(); var sumlat = 0; var sumlong = 0; var all_points_on_screen = true; var some_point_on_screen = false; var points = new Array(); var num_poi = search_results_poi.length; var center_poi = getCenterLocation(); var distance = 0; var min_distance = 0; var nearestpoi_onmap = false; var type = false; for (var i=0; i=0; i--) { var id = search_results_poi[i][0]; var name = search_results_poi[i][1]; var lat = search_results_poi[i][2]; var mylong = search_results_poi[i][3]; var type = search_results_poi[i][4]; var showlevel = search_results_poi[i][5]; var showonmap = search_results_poi[i][6]; lat = parseFloat(lat); mylong = parseFloat(mylong); if (type == "poi" || type == "foursquare-poi" || type == "google-poi" || type == "osm-poi") { if(type == "poi") { if(searchform && searchform == 'location' && resetSearchAndTagResults) { showIconLongdoPOI(id); // draw locations' icon. } if (!(num_poi == 1 && searchform == 'routing')) { markPoint(id,name,lat,mylong,marker_op); } } else { //if(type == "foursquare-poi") { markPointOtherServiceSearch(id,name,lat,mylong); } if(showonmap == '1') { if (nearestpoi_onmap) { distance = longdo.Util.distance([nearestpoi_onmap, {lat: lat, lon:mylong}]); } if (distance < 1000) { points.push({lat: lat, lon:mylong}); } //if (all_points_on_screen) { // if ( isOutOfBoundary(lat, mylong) ) { // all_points_on_screen = false; // } //} if (!some_point_on_screen) { if ( !isOutOfBoundary(lat, mylong) ) { some_point_on_screen = true; } } } } } if(points.length > 0) { //if (allowed_zoomout && !all_points_on_screen) { if (allowed_zoomout && !some_point_on_screen) { //if (document.getElementById('isMMMapSnippet') == null) { appropriateZoom(points, center_poi); //} } } } function markPointOtherServiceSearch(id,name,lat,mylong) { var imageObject = document.createElement('div'); var marker_op = {'longdomap': {'markertype': 'search-result'}}; imageObject.mark_lat = lat; imageObject.mark_long = mylong; var bg_pos = ''; if(/^foursquare/.test(id)) { bg_pos = '0px -44px'; } else if(/^osm/.test(id)) { bg_pos = '0px -88px'; } else { // google bg_pos = '0px 0px'; } imageObject.style.width = '25px'; imageObject.style.height = '44px'; imageObject.style.background = 'url(/mmmap/images/pin_mark_other_services.png) '+bg_pos+' no-repeat'; imageObject.poi_id = id; imageObject.title = name; imageObject.onmousedown = poiClicked; imageObject.border=0; imageObject.style.zIndex = 1000; imageObject.style.cursor = 'pointer'; imageObject.innerHTML = ' '; //var attr = {"centerOffsetX" : "12px", "centerOffsetY" : "44px"}; //mmmap.drawCustomDivWithPopup(imageObject, lat, mylong, name, '', attr); drawMarker(imageObject, lat, mylong, name, '', id, {offset: { x: 12, y: 44 }},marker_op); return; } function markOtherServiceSearchPOI(id,name,lat,mylong,showlevel,dozoom) { if (id != -1) { markPointOtherServiceSearch(id,name,lat,mylong); } //showlevel = Math.pow(2,showlevel); if ( dozoom == 1 ) { if (showlevel > mapZoom()) { mapZoom(showlevel); } moveLocation(lat,mylong); } else { moveLocationWhenOutOfBoundary(lat,mylong); } // FIXME now supports only popup_idx = 0 var popup_idx = 0; showLocationDetailPopup(id,name,mylong,lat,'',popup_idx); } /* ------------------------------------------------------------------------ Class: prettyPhoto Use: Lightbox clone for jQuery Author: Stephane Caron (http://www.no-margin-for-errors.com) Version: 3.1.4 ------------------------------------------------------------------------- */ (function($) { $.prettyPhoto = {version: '3.1.4'}; $.fn.prettyPhoto = function(pp_settings) { pp_settings = jQuery.extend({ hook: 'rel', /* the attribute tag to use for prettyPhoto hooks. default: 'rel'. For HTML5, use "data-rel" or similar. */ animation_speed: 'fast', /* fast/slow/normal */ ajaxcallback: function() {}, slideshow: false, /* false OR interval time in ms [default: 5000] */ autoplay_slideshow: false, /* true/false */ opacity: 0.60, /* Value between 0 and 1 */ show_title: true, /* true/false */ show_description: true, /* true/false */ allow_resize: true, /* Resize the photos bigger than viewport. true/false */ allow_expand: true, /* Allow the user to expand a resized image. true/false */ default_width: 500, default_height: 344, counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */ theme: 'facebook pp-longdo', /* light_rounded / dark_rounded / light_square / dark_square / facebook / pp_default [default: pp_default] */ horizontal_padding: 20, /* The padding on each side of the picture */ hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */ wmode: 'opaque', /* Set the flash wmode attribute */ autoplay: true, /* Automatically start videos: True/False */ modal: false, /* If set to true, only the close button will close the window */ deeplinking: false, /* Allow prettyPhoto to update the url to enable deeplinking. [default: true] */ overlay_gallery: true, /* If set to true, a gallery will overlay the fullscreen image on mouse over */ overlay_gallery_max: 30, /* Maximum number of pictures in the overlay gallery */ keyboard_shortcuts: true, /* Set to false if you open forms inside prettyPhoto */ changepicturecallback: function(){}, /* Called everytime an item is shown/changed */ callback: function(){}, /* Called when prettyPhoto is closed */ ie6_fallback: true, markup: '
\
 
\
\
\
\
\
\
\
\
\
\ Close \
\
\ Expand \
\ next \ previous \
\
\
\
\ Previous \

0/0

\ Next \
\

\
{pp_social}
\
\
\
\
\
\
\
\
\
\
\
\
\
', gallery_markup: '', image_markup: '', flash_markup: '', quicktime_markup: '', iframe_markup: '', inline_markup: '
{content}
', custom_markup: '', permalink_markup: ' ', textarea_markup: ' ', login_markup: '
\
\
\ \ \
Enter your longdo.com username.
\
\
\ \ \
Enter the password that accompanies your username.
\
\ \ \
\
\
\
', social_tools: false /* html or false to disable [default: ''] */ }, pp_settings); // Global variables accessible only by prettyPhoto var matchedObjects = this, percentBased = false, pp_dimensions, pp_open, // prettyPhoto container specific pp_contentHeight, pp_contentWidth, pp_containerHeight, pp_containerWidth, // Window size windowHeight = $(window).height(), windowWidth = $(window).width(), // Global elements pp_slideshow; doresize = true, scroll_pos = _get_scroll(); // Window/Keyboard events $(window).unbind('resize.prettyphoto').bind('resize.prettyphoto',function(){ _center_overlay(); _resize_overlay(); }); if(pp_settings.keyboard_shortcuts) { $(document).unbind('keydown.prettyphoto').bind('keydown.prettyphoto',function(e){ if(typeof $pp_pic_holder != 'undefined'){ if($pp_pic_holder.is(':visible')){ switch(e.keyCode){ case 37: if(_getFileType(pp_images[set_position])=="image") { $.prettyPhoto.changePage('previous'); e.preventDefault(); } break; case 39: if(_getFileType(pp_images[set_position])=="image") { $.prettyPhoto.changePage('next'); e.preventDefault(); } break; case 27: if(!settings.modal) { $.prettyPhoto.close(); } e.preventDefault(); break; }; // return false; }; }; }); }; /** * Initialize prettyPhoto. */ $.prettyPhoto.initialize = function() { settings = pp_settings; if(settings.theme == 'pp_default') settings.horizontal_padding = 16; if(settings.ie6_fallback && $.browser.msie && parseInt($.browser.version) == 6) settings.theme = "light_square"; // Fallback to a supported theme for IE6 // Find out if the picture is part of a set theRel = $(this).attr(settings.hook); galleryRegExp = /\[(?:.*)\]/; isSet = (galleryRegExp.exec(theRel)) ? true : false; // Put the SRCs, TITLEs, ALTs into an array. pp_images = (isSet) ? jQuery.map(matchedObjects, function(n, i){ if($(n).attr(settings.hook).indexOf(theRel) != -1) return $(n).attr('href'); }) : $.makeArray($(this).attr('href')); pp_titles = (isSet) ? jQuery.map(matchedObjects, function(n, i){ if($(n).attr(settings.hook).indexOf(theRel) != -1) return ($(n).find('img').attr('alt')) ? $(n).find('img').attr('alt') : ""; }) : $.makeArray($(this).find('img').attr('alt')); if(settings.show_description) { pp_descriptions = (isSet) ? jQuery.map(matchedObjects, function(n, i){ if($(n).attr(settings.hook).indexOf(theRel) != -1) return ($(n).attr('title')) ? $(n).attr('title') : ""; }) : $.makeArray($(this).attr('title')); } else { pp_descriptions = $.makeArray(""); } if(pp_images.length > settings.overlay_gallery_max) settings.overlay_gallery = false; set_position = jQuery.inArray($(this).attr('href'), pp_images); // Define where in the array the clicked item is positionned rel_index = (isSet) ? set_position : $("a["+settings.hook+"^='"+theRel+"']").index($(this)); _build_overlay(this); // Build the overlay {this} being the caller if(settings.allow_resize) $(window).bind('scroll.prettyphoto',function(){ _center_overlay(); }); $.prettyPhoto.open(); return false; } /** * Opens the prettyPhoto modal box. * @param image {String,Array} Full path to the image to be open, can also be an array containing full images paths. * @param title {String,Array} The title to be displayed with the picture, can also be an array containing all the titles. * @param description {String,Array} The description to be displayed with the picture, can also be an array containing all the descriptions. */ $.prettyPhoto.open = function(event) { if(typeof settings == "undefined"){ // Means it's an API call, need to manually get the settings and set the variables settings = pp_settings; if($.browser.msie && $.browser.version == 6) settings.theme = "light_square"; // Fallback to a supported theme for IE6 pp_images = $.makeArray(arguments[0]); pp_titles = (arguments[1]) ? $.makeArray(arguments[1]) : $.makeArray(""); pp_descriptions = (arguments[2]) ? $.makeArray(arguments[2]) : $.makeArray(""); isSet = (pp_images.length > 1) ? true : false; set_position = (arguments[3])? arguments[3]: 0; _build_overlay(event.target); // Build the overlay {this} being the caller } if($.browser.msie && $.browser.version == 6) $('select').css('visibility','hidden'); // To fix the bug with IE select boxes if(settings.hideflash) $('object,embed,iframe[src*=youtube],iframe[src*=vimeo]').css('visibility','hidden'); // Hide the flash _checkPosition($(pp_images).size()); // Hide the next/previous links if on first or last images. $('.pp_loaderIcon').show(); if(settings.deeplinking) setHashtag(); // Rebuild Facebook Like Button with updated href if(settings.social_tools){ facebook_like_link = settings.social_tools.replace('{location_href}', encodeURIComponent(location.href)); $pp_pic_holder.find('.pp_social').html(facebook_like_link); } // Fade the content in if($ppt.is(':hidden')) $ppt.css('opacity',0).show(); $pp_overlay.show().fadeTo(settings.animation_speed,settings.opacity); // Display the current position $pp_pic_holder.find('.currentTextHolder').text((set_position+1) + settings.counter_separator_label + $(pp_images).size()); // Set the description if(typeof pp_descriptions[set_position] != 'undefined' && pp_descriptions[set_position] != ""){ $pp_pic_holder.find('.pp_description').show().html(unescape(pp_descriptions[set_position])); }else{ $pp_pic_holder.find('.pp_description').hide(); } // Get the dimensions movie_width = ( parseFloat(getParam('width',pp_images[set_position])) ) ? getParam('width',pp_images[set_position]) : settings.default_width.toString(); movie_height = ( parseFloat(getParam('height',pp_images[set_position])) ) ? getParam('height',pp_images[set_position]) : settings.default_height.toString(); // If the size is % based, calculate according to window dimensions percentBased=false; if(movie_height.indexOf('%') != -1) { movie_height = parseFloat(($(window).height() * parseFloat(movie_height) / 100) - 150); percentBased = true; } if(movie_width.indexOf('%') != -1) { movie_width = parseFloat(($(window).width() * parseFloat(movie_width) / 100) - 150); percentBased = true; } // Fade the holder $pp_pic_holder.fadeIn(function(){ // Set the title (settings.show_title && pp_titles[set_position] != "" && typeof pp_titles[set_position] != "undefined") ? $ppt.html(unescape(pp_titles[set_position])) : $ppt.html(' '); imgPreloader = ""; skipInjection = false; // Inject the proper content switch(_getFileType(pp_images[set_position])){ case 'image': imgPreloader = new Image(); // Preload the neighbour images nextImage = new Image(); if(isSet && set_position < $(pp_images).size() -1) nextImage.src = pp_images[set_position + 1]; prevImage = new Image(); if(isSet && pp_images[set_position - 1]) prevImage.src = pp_images[set_position - 1]; $pp_pic_holder.find('#pp_full_res')[0].innerHTML = settings.image_markup.replace(/{path}/g,pp_images[set_position]); imgPreloader.onload = function(){ // Fit item to viewport pp_dimensions = _fitToViewport(imgPreloader.width,imgPreloader.height); _showContent(); }; imgPreloader.onerror = function(){ alert('Image cannot be loaded. Make sure the path is correct and image exist.'); $.prettyPhoto.close(); }; imgPreloader.src = pp_images[set_position]; break; case 'youtube': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport // Regular youtube link movie_id = getParam('v',pp_images[set_position]); // youtu.be link if(movie_id == ""){ movie_id = pp_images[set_position].split('youtu.be/'); movie_id = movie_id[1]; if(movie_id.indexOf('?') > 0) movie_id = movie_id.substr(0,movie_id.indexOf('?')); // Strip anything after the ? if(movie_id.indexOf('&') > 0) movie_id = movie_id.substr(0,movie_id.indexOf('&')); // Strip anything after the & } movie = 'http://www.youtube.com/embed/'+movie_id; (getParam('rel',pp_images[set_position])) ? movie+="?rel="+getParam('rel',pp_images[set_position]) : movie+="?rel=1"; if(settings.autoplay) movie += "&autoplay=1"; toInject = settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,movie); break; case 'vimeo': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport movie_id = pp_images[set_position]; var regExp = /http:\/\/(www\.)?vimeo.com\/(\d+)/; var match = movie_id.match(regExp); movie = 'http://player.vimeo.com/video/'+ match[2] +'?title=0&byline=0&portrait=0'; if(settings.autoplay) movie += "&autoplay=1;"; vimeo_width = pp_dimensions['width'] + '/embed/?moog_width='+ pp_dimensions['width']; toInject = settings.iframe_markup.replace(/{width}/g,vimeo_width).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,movie); break; case 'quicktime': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport pp_dimensions['height']+=15; pp_dimensions['contentHeight']+=15; pp_dimensions['containerHeight']+=15; // Add space for the control bar toInject = settings.quicktime_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,pp_images[set_position]).replace(/{autoplay}/g,settings.autoplay); break; case 'flash': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport flash_vars = pp_images[set_position]; flash_vars = flash_vars.substring(pp_images[set_position].indexOf('flashvars') + 10,pp_images[set_position].length); filename = pp_images[set_position]; filename = filename.substring(0,filename.indexOf('?')); toInject = settings.flash_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{wmode}/g,settings.wmode).replace(/{path}/g,filename+'?'+flash_vars); break; case 'iframe': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport frame_url = pp_images[set_position]; frame_url = frame_url.substr(0,frame_url.indexOf('iframe')-1); toInject = settings.iframe_markup.replace(/{width}/g,pp_dimensions['width']).replace(/{height}/g,pp_dimensions['height']).replace(/{path}/g,frame_url); settings.allow_expand = false; break; /*case 'ajax': // koB hack 20120830 doresize = false; // Make sure the dimensions are not resized. pp_dimensions = _fitToViewport(movie_width,movie_height); doresize = true; // Reset the dimensions skipInjection = true; $.get(pp_images[set_position],function(responseHTML){ toInject = settings.inline_markup.replace(/{content}/g,responseHTML); $pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject; _showContent(); }); break;*/ case 'ajax': skipInjection = true; $.get(pp_images[set_position], function (responseHTML) { toInject = settings.inline_markup.replace(/{content}/g, responseHTML); $pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject; myClone = $($pp_pic_holder.find('#pp_full_res')[0]).clone().append('
').css({ 'width': settings.default_width }).wrapInner('
').appendTo($('body')).show(); doresize = false; // Make sure the dimensions are not resized. pp_dimensions = _fitToViewport($(myClone).width(), $(myClone).height()); doresize = true; // Reset the dimensions $(myClone).remove(); _showContent(); }); break; case 'custom': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport toInject = settings.custom_markup; break; case 'inline': // to get the item height clone it, apply default width, wrap it in the prettyPhoto containers , then delete myClone = $(pp_images[set_position]).clone().append('
').css({'width':settings.default_width}).wrapInner('
').appendTo($('body')).show(); doresize = false; // Make sure the dimensions are not resized. pp_dimensions = _fitToViewport($(myClone).width(),$(myClone).height()); doresize = true; // Reset the dimensions $(myClone).remove(); toInject = settings.inline_markup.replace(/{content}/g,$(pp_images[set_position]).html()); break; case 'permalink': pp_dimensions = _fitToViewport(movie_width,movie_height); var link = pp_images[set_position].split('#',2)[0]; toInject = settings.permalink_markup.replace(/{link}/g,link); break; case 'textarea': pp_dimensions = _fitToViewport(movie_width,movie_height); var link = getPermalinkURL(); toInject = settings.textarea_markup.replace(/{link}/g,link); break; case 'login': pp_dimensions = _fitToViewport(movie_width,movie_height); // Fit item to viewport var destination = ''; var pattern = /destination=(.*)/ var href = pp_images[set_position]; if(href) { var dest = href.match(pattern) ? href.match(pattern)[1] : ''; if(dest != '') destination = dest; } toInject = settings.login_markup.replace(/{destination}/g,destination); break; }; if(!imgPreloader && !skipInjection){ $pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject; // Show content _showContent(); }; }); return false; }; /** * Change page in the prettyPhoto modal box * @param direction {String} Direction of the paging, previous or next. */ $.prettyPhoto.changePage = function(direction){ currentGalleryPage = 0; if(direction == 'previous') { set_position--; if (set_position < 0) set_position = $(pp_images).size()-1; }else if(direction == 'next'){ set_position++; if(set_position > $(pp_images).size()-1) set_position = 0; }else{ set_position=direction; }; rel_index = set_position; //if(!doresize) doresize = true; // Allow the resizing of the images if(settings.allow_expand) { if (doresize) { $('.pp_contract').removeClass('pp_expand').addClass('pp_contract'); } else { $('.pp_expand').removeClass('pp_contract').addClass('pp_expand'); } } _hideContent(function(){ $.prettyPhoto.open(); }); }; /** * Change gallery page in the prettyPhoto modal box * @param direction {String} Direction of the paging, previous or next. */ $.prettyPhoto.changeGalleryPage = function(direction){ if(direction=='next'){ currentGalleryPage ++; if(currentGalleryPage > totalPage) currentGalleryPage = 0; }else if(direction=='previous'){ currentGalleryPage --; if(currentGalleryPage < 0) currentGalleryPage = totalPage; }else{ currentGalleryPage = direction; }; slide_speed = (direction == 'next' || direction == 'previous') ? settings.animation_speed : 0; slide_to = currentGalleryPage * (itemsPerPage * itemWidth); $pp_gallery.find('ul').animate({left:-slide_to},slide_speed); }; /** * Start the slideshow... */ $.prettyPhoto.startSlideshow = function(){ if(typeof pp_slideshow == 'undefined'){ $pp_pic_holder.find('.pp_play').unbind('click').removeClass('pp_play').addClass('pp_pause').click(function(){ $.prettyPhoto.stopSlideshow(); return false; }); pp_slideshow = setInterval($.prettyPhoto.startSlideshow,settings.slideshow); }else{ $.prettyPhoto.changePage('next'); }; } /** * Stop the slideshow... */ $.prettyPhoto.stopSlideshow = function(){ $pp_pic_holder.find('.pp_pause').unbind('click').removeClass('pp_pause').addClass('pp_play').click(function(){ $.prettyPhoto.startSlideshow(); return false; }); clearInterval(pp_slideshow); pp_slideshow=undefined; } /** * Closes prettyPhoto. */ $.prettyPhoto.close = function(){ if($pp_overlay.is(":animated")) return; $.prettyPhoto.stopSlideshow(); $pp_pic_holder.stop().find('object,embed').css('visibility','hidden'); $('div.pp_pic_holder,div.ppt,.pp_fade').fadeOut(settings.animation_speed,function(){ $(this).remove(); }); $pp_overlay.fadeOut(settings.animation_speed, function(){ if($.browser.msie && $.browser.version == 6) $('select').css('visibility','visible'); // To fix the bug with IE select boxes if(settings.hideflash) $('object,embed,iframe[src*=youtube],iframe[src*=vimeo]').css('visibility','visible'); // Show the flash $(this).remove(); // No more need for the prettyPhoto markup $(window).unbind('scroll.prettyphoto'); clearHashtag(); settings.callback(); doresize = true; pp_open = false; delete settings; }); }; /** * Set the proper sizes on the containers and animate the content in. */ function _showContent(){ $('.pp_loaderIcon').hide(); // Calculate the opened top position of the pic holder projectedTop = scroll_pos['scrollTop'] + ((windowHeight/2) - (pp_dimensions['containerHeight']/2)); if(projectedTop < 0) projectedTop = 0; $ppt.fadeTo(settings.animation_speed,1); // Resize the content holder $pp_pic_holder.find('.pp_content') .animate({ height:pp_dimensions['contentHeight'], width:pp_dimensions['contentWidth'] },settings.animation_speed); // Resize picture the holder $pp_pic_holder.animate({ 'top': projectedTop, 'left': ((windowWidth/2) - (pp_dimensions['containerWidth']/2) < 0) ? 0 : (windowWidth/2) - (pp_dimensions['containerWidth']/2), width:pp_dimensions['containerWidth'] },settings.animation_speed,function(){ $pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(pp_dimensions['height']).width(pp_dimensions['width']); $pp_pic_holder.find('.pp_fade').fadeIn(settings.animation_speed); // Fade the new content // Show the nav if(isSet && _getFileType(pp_images[set_position])=="image") { $pp_pic_holder.find('.pp_hoverContainer').show(); }else{ $pp_pic_holder.find('.pp_hoverContainer').hide(); } if(settings.allow_expand) { if(pp_dimensions['resized']){ // Fade the resizing link if the image is resized $('a.pp_expand,a.pp_contract').show(); }else{ if (doresize) $('a.pp_expand,a.pp_expand').hide(); } } if(settings.autoplay_slideshow && !pp_slideshow && !pp_open) $.prettyPhoto.startSlideshow(); if(_getFileType(pp_images[set_position])=="permalink" || _getFileType(pp_images[set_position])=="textarea" || _getFileType(pp_images[set_position])=="login") { $pp_pic_holder.find('[rel="thickbox-focus"]').focus(); if(_getFileType(pp_images[set_position])=="permalink" || _getFileType(pp_images[set_position])=="textarea") { $pp_pic_holder.find('[rel="thickbox-focus"]').select(); } } settings.changepicturecallback(); // Callback! pp_open = true; }); _insert_gallery(); pp_settings.ajaxcallback(); }; /** * Hide the content...DUH! */ function _hideContent(callback){ // Fade out the current picture $pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden'); $pp_pic_holder.find('.pp_fade').fadeOut(settings.animation_speed,function(){ $('.pp_loaderIcon').show(); callback(); }); }; /** * Check the item position in the gallery array, hide or show the navigation links * @param setCount {integer} The total number of items in the set */ function _checkPosition(setCount){ (setCount > 1) ? $('.pp_nav').show() : $('.pp_nav').hide(); // Hide the bottom nav if it's not a set. }; /** * Resize the item dimensions if it's bigger than the viewport * @param width {integer} Width of the item to be opened * @param height {integer} Height of the item to be opened * @return An array containin the "fitted" dimensions */ function _fitToViewport(width,height){ resized = false; _getDimensions(width,height); // Define them in case there's no resize needed imageWidth = width, imageHeight = height; if( ((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allow_resize && !percentBased) { resized = true, fitting = false; while (!fitting){ if((pp_containerWidth > windowWidth)){ imageWidth = (windowWidth - 110); imageHeight = (height/width) * imageWidth; }else if((pp_containerHeight > windowHeight)){ imageHeight = (windowHeight - 110); imageWidth = (width/height) * imageHeight; }else{ fitting = true; }; pp_containerHeight = imageHeight, pp_containerWidth = imageWidth; }; _getDimensions(imageWidth,imageHeight); if((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)){ _fitToViewport(pp_containerWidth,pp_containerHeight) }; }; return { width:Math.floor(imageWidth), height:Math.floor(imageHeight), containerHeight:Math.floor(pp_containerHeight), containerWidth:Math.floor(pp_containerWidth) + (settings.horizontal_padding * 2), contentHeight:Math.floor(pp_contentHeight), contentWidth:Math.floor(pp_contentWidth), resized:resized }; }; /** * Get the containers dimensions according to the item size * @param width {integer} Width of the item to be opened * @param height {integer} Height of the item to be opened */ function _getDimensions(width,height){ width = parseFloat(width); height = parseFloat(height); // Get the details height, to do so, I need to clone it since it's invisible $pp_details = $pp_pic_holder.find('.pp_details'); $pp_details.width(width); detailsHeight = parseFloat($pp_details.css('marginTop')) + parseFloat($pp_details.css('marginBottom')); $pp_details = $pp_details.clone().addClass(settings.theme).width(width).appendTo($('body')).css({ 'position':'absolute', 'top':-10000 }); detailsHeight += $pp_details.height(); detailsHeight = (detailsHeight <= 34) ? 36 : detailsHeight; // Min-height for the details if($.browser.msie && $.browser.version==7) detailsHeight+=8; $pp_details.remove(); // Get the titles height, to do so, I need to clone it since it's invisible $pp_title = $pp_pic_holder.find('.ppt'); $pp_title.width(width); titleHeight = parseFloat($pp_title.css('marginTop')) + parseFloat($pp_title.css('marginBottom')); $pp_title = $pp_title.clone().appendTo($('body')).css({ 'position':'absolute', 'top':-10000 }); titleHeight += $pp_title.height(); $pp_title.remove(); // Get the container size, to resize the holder to the right dimensions pp_contentHeight = height + detailsHeight; pp_contentWidth = width; pp_containerHeight = pp_contentHeight + titleHeight + $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height(); pp_containerWidth = width; } function _getFileType(itemSrc){ if (itemSrc.match(/youtube\.com\/watch/i) || itemSrc.match(/youtu\.be/i)) { return 'youtube'; }else if (itemSrc.match(/vimeo\.com/i)) { return 'vimeo'; }else if(itemSrc.match(/\b.mov\b/i)){ return 'quicktime'; }else if(itemSrc.match(/\b.swf\b/i)){ return 'flash'; }else if(itemSrc.match(/\biframe=true\b/i)){ return 'iframe'; }else if(itemSrc.match(/\bajax=true\b/i)){ return 'ajax'; }else if(itemSrc.match(/\bcustom=true\b/i)){ return 'custom'; }else if(itemSrc.match(/\bpermalink=true\b/i)){ return 'permalink'; }else if(itemSrc.match(/\btextarea=true\b/i)){ return 'textarea'; }else if(itemSrc.match(/\/login/i)){ return 'login'; }else if(itemSrc.substr(0,1) == '#'){ return 'inline'; }else{ return 'image'; }; }; function _center_overlay(){ if(doresize && typeof $pp_pic_holder != 'undefined') { scroll_pos = _get_scroll(); contentHeight = $pp_pic_holder.height(), contentwidth = $pp_pic_holder.width(); projectedTop = (windowHeight/2) + scroll_pos['scrollTop'] - (contentHeight/2); if(projectedTop < 0) projectedTop = 0; if(contentHeight > windowHeight) return; $pp_pic_holder.css({ 'top': projectedTop, 'left': (windowWidth/2) + scroll_pos['scrollLeft'] - (contentwidth/2) }); }; }; function _get_scroll(){ if (self.pageYOffset) { return {scrollTop:self.pageYOffset,scrollLeft:self.pageXOffset}; } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict return {scrollTop:document.documentElement.scrollTop,scrollLeft:document.documentElement.scrollLeft}; } else if (document.body) {// all other Explorers return {scrollTop:document.body.scrollTop,scrollLeft:document.body.scrollLeft}; }; }; function _resize_overlay() { windowHeight = $(window).height(), windowWidth = $(window).width(); if(typeof $pp_overlay != "undefined") $pp_overlay.height($(document).height()).width(windowWidth); }; function _insert_gallery(){ if(isSet && settings.overlay_gallery && _getFileType(pp_images[set_position])=="image" && (settings.ie6_fallback && !($.browser.msie && parseInt($.browser.version) == 6))) { itemWidth = 52+5; // 52 beign the thumb width, 5 being the right margin. navWidth = (settings.theme == "facebook" || settings.theme == "pp_default") ? 50 : 30; // Define the arrow width depending on the theme itemsPerPage = Math.floor((pp_dimensions['containerWidth'] - 100 - navWidth) / itemWidth); itemsPerPage = (itemsPerPage < pp_images.length) ? itemsPerPage : pp_images.length; totalPage = Math.ceil(pp_images.length / itemsPerPage) - 1; // Hide the nav in the case there's no need for links if(totalPage == 0){ navWidth = 0; // No nav means no width! $pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').hide(); }else{ $pp_gallery.find('.pp_arrow_next,.pp_arrow_previous').show(); }; galleryWidth = itemsPerPage * itemWidth; fullGalleryWidth = pp_images.length * itemWidth; // Set the proper width to the gallery items $pp_gallery .css('margin-left',-((galleryWidth/2) + (navWidth/2))) .find('div:first').width(galleryWidth+5) .find('ul').width(fullGalleryWidth) .find('li.selected').removeClass('selected'); goToPage = (Math.floor(set_position/itemsPerPage) < totalPage) ? Math.floor(set_position/itemsPerPage) : totalPage; $.prettyPhoto.changeGalleryPage(goToPage); $pp_gallery_li.filter(':eq('+set_position+')').addClass('selected'); }else{ $pp_pic_holder.find('.pp_content').unbind('mouseenter mouseleave'); // $pp_gallery.hide(); } } function _build_overlay(caller){ // Inject Social Tool markup into General markup if(settings.social_tools) facebook_like_link = settings.social_tools.replace('{location_href}', encodeURIComponent(location.href)); settings.markup = settings.markup.replace('{pp_social}',''); $('body').append(settings.markup); // Inject the markup $pp_pic_holder = $('.pp_pic_holder'), $ppt = $('.ppt'), $pp_overlay = $('div.pp_overlay'); // Set my global selectors // Inject the inline gallery! if(isSet && settings.overlay_gallery) { currentGalleryPage = 0; toInject = ""; for (var i=0; i < pp_images.length; i++) { if(!pp_images[i].match(/\b(jpg|jpeg|png|gif|files\/images)\b/gi)){ classname = 'default'; img_src = ''; }else{ classname = ''; img_src = pp_images[i]; } toInject += "
  • "; }; toInject = settings.gallery_markup.replace(/{gallery}/g,toInject); $pp_pic_holder.find('#pp_full_res').after(toInject); $pp_gallery = $('.pp_pic_holder .pp_gallery'), $pp_gallery_li = $pp_gallery.find('li'); // Set the gallery selectors $pp_gallery.find('.pp_arrow_next').click(function(){ $.prettyPhoto.changeGalleryPage('next'); $.prettyPhoto.stopSlideshow(); return false; }); $pp_gallery.find('.pp_arrow_previous').click(function(){ $.prettyPhoto.changeGalleryPage('previous'); $.prettyPhoto.stopSlideshow(); return false; }); $pp_pic_holder.find('.pp_content').hover( function(){ $pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeIn(); }, function(){ $pp_pic_holder.find('.pp_gallery:not(.disabled)').fadeOut(); }); itemWidth = 52+5; // 52 beign the thumb width, 5 being the right margin. $pp_gallery_li.each(function(i){ $(this) .find('a') .click(function(){ $.prettyPhoto.changePage(i); $.prettyPhoto.stopSlideshow(); return false; }); }); }; // Inject the play/pause if it's a slideshow if(settings.slideshow){ $pp_pic_holder.find('.pp_nav').prepend('Play') $pp_pic_holder.find('.pp_nav .pp_play').click(function(){ $.prettyPhoto.startSlideshow(); return false; }); } $pp_pic_holder.attr('class','pp_pic_holder ' + settings.theme); // Set the proper theme $pp_overlay .css({ 'opacity':0, 'height':$(document).height(), 'width':$(window).width() }) .bind('click',function(){ if(!settings.modal) $.prettyPhoto.close(); }); $('a.pp_close').bind('click',function(){ $.prettyPhoto.close(); return false; }); if(settings.allow_expand) { $('a.pp_expand').bind('click',function(e){ // Expand the image if($(this).hasClass('pp_expand')){ $(this).removeClass('pp_expand').addClass('pp_contract'); doresize = false; }else{ $(this).removeClass('pp_contract').addClass('pp_expand'); doresize = true; }; _hideContent(function(){ $.prettyPhoto.open(); }); return false; }); } $pp_pic_holder.find('.pp_previous, .pp_nav .pp_arrow_previous').bind('click',function(){ $.prettyPhoto.changePage('previous'); $.prettyPhoto.stopSlideshow(); return false; }); $pp_pic_holder.find('.pp_next, .pp_nav .pp_arrow_next').bind('click',function(){ $.prettyPhoto.changePage('next'); $.prettyPhoto.stopSlideshow(); return false; }); _center_overlay(); // Center it }; if(!pp_alreadyInitialized && getHashtag()){ pp_alreadyInitialized = true; // Grab the rel index to trigger the click on the correct element hashIndex = getHashtag(); hashRel = hashIndex; hashIndex = hashIndex.substring(hashIndex.indexOf('/')+1,hashIndex.length-1); hashRel = hashRel.substring(0,hashRel.indexOf('/')); // Little timeout to make sure all the prettyPhoto initialize scripts has been run. // Useful in the event the page contain several init scripts. setTimeout(function(){ $("a["+pp_settings.hook+"^='"+hashRel+"']:eq("+hashIndex+")").trigger('click'); },50); } return this.unbind('click.prettyphoto').bind('click.prettyphoto',$.prettyPhoto.initialize); // Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once }; function getHashtag(){ url = location.href; hashtag = (url.indexOf('#prettyPhoto') !== -1) ? decodeURI(url.substring(url.indexOf('#prettyPhoto')+1,url.length)) : false; return hashtag; }; function setHashtag(){ if(typeof theRel == 'undefined') return; // theRel is set on normal calls, it's impossible to deeplink using the API location.hash = theRel + '/'+rel_index+'/'; }; function clearHashtag(){ if ( location.href.indexOf('#prettyPhoto') !== -1 ) location.hash = "prettyPhoto"; } function getParam(name,url){ name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( url ); return ( results == null ) ? "" : results[1]; } })(jQuery); var pp_alreadyInitialized = false; // Used for the deep linking to make sure not to call the same function several times. /* Highcharts JS v6.1.3 (2018-09-12) (c) 2009-2016 Torstein Honsi License: www.highcharts.com/license */ (function(T,K){"object"===typeof module&&module.exports?module.exports=T.document?K(T):K:"function"===typeof define&&define.amd?define(function(){return K(T)}):T.Highcharts=K(T)})("undefined"!==typeof window?window:this,function(T){var K=function(){var a="undefined"===typeof T?window:T,C=a.document,D=a.navigator&&a.navigator.userAgent||"",E=C&&C.createElementNS&&!!C.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect,m=/(edge|msie|trident)/i.test(D)&&!a.opera,h=-1!==D.indexOf("Firefox"), f=-1!==D.indexOf("Chrome"),r=h&&4>parseInt(D.split("Firefox/")[1],10);return a.Highcharts?a.Highcharts.error(16,!0):{product:"Highcharts",version:"6.1.3",deg2rad:2*Math.PI/360,doc:C,hasBidiBug:r,hasTouch:C&&void 0!==C.documentElement.ontouchstart,isMS:m,isWebKit:-1!==D.indexOf("AppleWebKit"),isFirefox:h,isChrome:f,isSafari:!f&&-1!==D.indexOf("Safari"),isTouchDevice:/(Mobile|Android|Windows Phone)/.test(D),SVG_NS:"http://www.w3.org/2000/svg",chartCount:0,seriesTypes:{},symbolSizes:{},svg:E,win:a,marginNames:["plotTop", "marginRight","marginBottom","plotLeft"],noop:function(){},charts:[]}}();(function(a){a.timers=[];var C=a.charts,D=a.doc,E=a.win;a.error=function(m,h){m=a.isNumber(m)?"Highcharts error #"+m+": www.highcharts.com/errors/"+m:m;if(h)throw Error(m);E.console&&console.log(m)};a.Fx=function(a,h,f){this.options=h;this.elem=a;this.prop=f};a.Fx.prototype={dSetter:function(){var a=this.paths[0],h=this.paths[1],f=[],r=this.now,y=a.length,q;if(1===r)f=this.toD;else if(y===h.length&&1>r)for(;y--;)q=parseFloat(a[y]), f[y]=isNaN(q)?h[y]:r*parseFloat(h[y]-q)+q;else f=h;this.elem.attr("d",f,null,!0)},update:function(){var a=this.elem,h=this.prop,f=this.now,r=this.options.step;if(this[h+"Setter"])this[h+"Setter"]();else a.attr?a.element&&a.attr(h,f,null,!0):a.style[h]=f+this.unit;r&&r.call(a,f,this)},run:function(m,h,f){var r=this,y=r.options,q=function(a){return q.stopped?!1:r.step(a)},w=E.requestAnimationFrame||function(a){setTimeout(a,13)},e=function(){for(var c=0;c=w+this.startTime?(this.now=this.end,this.pos= 1,this.update(),f=e[this.prop]=!0,a.objectEach(e,function(a){!0!==a&&(f=!1)}),f&&q&&q.call(y),m=!1):(this.pos=r.easing((h-this.startTime)/w),this.now=this.start+(this.end-this.start)*this.pos,this.update(),m=!0);return m},initPath:function(m,h,f){function r(a){var d,k;for(b=a.length;b--;)d="M"===a[b]||"L"===a[b],k=/[a-zA-Z]/.test(a[b+3]),d&&k&&a.splice(b+1,0,a[b+1],a[b+2],a[b+1],a[b+2])}function y(a,d){for(;a.lengtha&&-Infinity=f&&(h=[1/f])));for(r=0;r=m||!y&&q<=(h[r]+(h[r+1]||h[r]))/2);r++);return w=a.correctFloat(w*f,-Math.round(Math.log(.001)/Math.LN10))};a.stableSort=function(a,h){var f=a.length,m,y;for(y=0;yf&&(f=a[h]);return f};a.destroyObjectProperties=function(m,h){a.objectEach(m,function(a,r){a&&a!==h&&a.destroy&&a.destroy();delete m[r]})};a.discardElement=function(m){var h=a.garbageBin;h||(h=a.createElement("div"));m&&h.appendChild(m);h.innerHTML=""};a.correctFloat=function(a,h){return parseFloat(a.toPrecision(h||14))};a.setAnimation=function(m,h){h.renderer.globalAnimation=a.pick(m,h.options.chart.animation,!0)};a.animObject=function(m){return a.isObject(m)?a.merge(m): {duration:m?500:0}};a.timeUnits={millisecond:1,second:1E3,minute:6E4,hour:36E5,day:864E5,week:6048E5,month:24192E5,year:314496E5};a.numberFormat=function(m,h,f,r){m=+m||0;h=+h;var y=a.defaultOptions.lang,q=(m.toString().split(".")[1]||"").split("e")[0].length,w,e,c=m.toString().split("e");-1===h?h=Math.min(q,20):a.isNumber(h)?h&&c[1]&&0>c[1]&&(w=h+ +c[1],0<=w?(c[0]=(+c[0]).toExponential(w).split("e")[0],h=w):(c[0]=c[0].split(".")[0]||0,m=20>h?(c[0]*Math.pow(10,c[1])).toFixed(h):0,c[1]=0)):h=2;e=(Math.abs(c[1]? c[0]:m)+Math.pow(10,-Math.max(h,q)-1)).toFixed(h);q=String(a.pInt(e));w=3m?"-":"")+(w?q.substr(0,w)+r:"");m+=q.substr(w).replace(/(\d{3})(?=\d)/g,"$1"+r);h&&(m+=f+e.slice(-h));c[1]&&0!==+m&&(m+="e"+c[1]);return m};Math.easeInOutSine=function(a){return-.5*(Math.cos(Math.PI*a)-1)};a.getStyle=function(m,h,f){if("width"===h)return Math.max(0,Math.min(m.offsetWidth,m.scrollWidth)-a.getStyle(m,"padding-left")-a.getStyle(m, "padding-right"));if("height"===h)return Math.max(0,Math.min(m.offsetHeight,m.scrollHeight)-a.getStyle(m,"padding-top")-a.getStyle(m,"padding-bottom"));E.getComputedStyle||a.error(27,!0);if(m=E.getComputedStyle(m,void 0))m=m.getPropertyValue(h),a.pick(f,"opacity"!==h)&&(m=a.pInt(m));return m};a.inArray=function(m,h,f){return(a.indexOfPolyfill||Array.prototype.indexOf).call(h,m,f)};a.grep=function(m,h){return(a.filterPolyfill||Array.prototype.filter).call(m,h)};a.find=Array.prototype.find?function(a, h){return a.find(h)}:function(a,h){var f,r=a.length;for(f=0;f>16,(f&65280)>>8,f&255,1]:4===h&&(y=[(f&3840)>>4|(f&3840)>>8,(f&240)>>4|f&240,(f&15)<<4|f&15,1])),!y)for(q=this.parsers.length;q--&&!y;)w=this.parsers[q],(h=w.regex.exec(f))&&(y=w.parse(h));this.rgba=y||[]},get:function(a){var f=this.input,h=this.rgba,q;this.stops? (q=m(f),q.stops=[].concat(q.stops),C(this.stops,function(f,e){q.stops[e]=[q.stops[e][0],f.get(a)]})):q=h&&D(h[0])?"rgb"===a||!a&&1===h[3]?"rgb("+h[0]+","+h[1]+","+h[2]+")":"a"===a?h[3]:"rgba("+h.join(",")+")":f;return q},brighten:function(a){var f,y=this.rgba;if(this.stops)C(this.stops,function(f){f.brighten(a)});else if(D(a)&&0!==a)for(f=0;3>f;f++)y[f]+=h(255*a),0>y[f]&&(y[f]=0),255A.width)A={width:0,height:0}}else A=this.htmlGetBBox();b.isSVG&&(a=A.width,b=A.height,c&&"11px"===c.fontSize&&17===Math.round(b)&&(A.height=b=14),g&&(A.width=Math.abs(b*Math.sin(d))+Math.abs(a*Math.cos(d)),A.height=Math.abs(b*Math.cos(d))+Math.abs(a* Math.sin(d))));if(p&&0]*>/g,"").replace(/</g,"\x3c").replace(/>/g,"\x3e")))},textSetter:function(a){a!==this.textStr&& (delete this.bBox,this.textStr=a,this.added&&this.renderer.buildText(this))},fillSetter:function(a,g,b){"string"===typeof a?b.setAttribute(g,a):a&&this.complexColor(a,g,b)},visibilitySetter:function(a,g,b){"inherit"===a?b.removeAttribute(g):this[g]!==a&&b.setAttribute(g,a);this[g]=a},zIndexSetter:function(a,b){var d=this.renderer,v=this.parentGroup,A=(v||d).element||d.box,c,k=this.element,n,J,d=A===d.box;c=this.added;var e;w(a)?(k.setAttribute("data-z-index",a),a=+a,this[b]===a&&(c=!1)):w(this[b])&& k.removeAttribute("data-z-index");this[b]=a;if(c){(a=this.zIndex)&&v&&(v.handleZ=!0);b=A.childNodes;for(e=b.length-1;0<=e&&!n;e--)if(v=b[e],c=v.getAttribute("data-z-index"),J=!w(c),v!==k)if(0>a&&J&&!d&&!e)A.insertBefore(k,b[e]),n=!0;else if(g(c)<=a||J&&(!w(a)||0<=a))A.insertBefore(k,b[e+1]||null),n=!0;n||(A.insertBefore(k,b[d?3:0]||null),n=!0)}return n},_defaultSetter:function(a,g,b){b.setAttribute(g,a)}});C.prototype.yGetter=C.prototype.xGetter;C.prototype.translateXSetter=C.prototype.translateYSetter= C.prototype.rotationSetter=C.prototype.verticalAlignSetter=C.prototype.rotationOriginXSetter=C.prototype.rotationOriginYSetter=C.prototype.scaleXSetter=C.prototype.scaleYSetter=C.prototype.matrixSetter=function(a,g){this[g]=a;this.doTransform=!0};C.prototype["stroke-widthSetter"]=C.prototype.strokeSetter=function(a,g,b){this[g]=a;this.stroke&&this["stroke-width"]?(C.prototype.fillSetter.call(this,this.stroke,"stroke",b),b.setAttribute("stroke-width",this["stroke-width"]),this.hasStroke=!0):"stroke-width"=== g&&0===a&&this.hasStroke&&(b.removeAttribute("stroke"),this.hasStroke=!1)};D=a.SVGRenderer=function(){this.init.apply(this,arguments)};k(D.prototype,{Element:C,SVG_NS:J,init:function(a,g,b,d,v,c){var A;d=this.createElement("svg").attr({version:"1.1","class":"highcharts-root"}).css(this.getStyle(d));A=d.element;a.appendChild(A);h(a,"dir","ltr");-1===a.innerHTML.indexOf("xmlns")&&h(A,"xmlns",this.SVG_NS);this.isSVG=!0;this.box=A;this.boxWrapper=d;this.alignedObjects=[];this.url=(t||n)&&l.getElementsByTagName("base").length? N.location.href.split("#")[0].replace(/<[^>]*>/g,"").replace(/([\('\)])/g,"\\$1").replace(/ /g,"%20"):"";this.createElement("desc").add().element.appendChild(l.createTextNode("Created with Highcharts 6.1.3"));this.defs=this.createElement("defs").add();this.allowHTML=c;this.forExport=v;this.gradients={};this.cache={};this.cacheKeys=[];this.imgCount=0;this.setSize(g,b,!1);var k;t&&a.getBoundingClientRect&&(g=function(){y(a,{left:0,top:0});k=a.getBoundingClientRect();y(a,{left:Math.ceil(k.left)-k.left+ "px",top:Math.ceil(k.top)-k.top+"px"})},g(),this.unSubPixelFix=E(N,"resize",g))},getStyle:function(a){return this.style=k({fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif',fontSize:"12px"},a)},setStyle:function(a){this.boxWrapper.css(this.getStyle(a))},isHidden:function(){return!this.boxWrapper.getBBox().width},destroy:function(){var a=this.defs;this.box=null;this.boxWrapper=this.boxWrapper.destroy();c(this.gradients||{});this.gradients=null;a&&(this.defs=a.destroy()); this.unSubPixelFix&&this.unSubPixelFix();return this.alignedObjects=null},createElement:function(a){var g=new this.Element;g.init(this,a);return g},draw:B,getRadialAttr:function(a,g){return{cx:a[0]-a[2]/2+g.cx*a[2],cy:a[1]-a[2]/2+g.cy*a[2],r:g.r*a[2]}},getSpanWidth:function(a){return a.getBBox(!0).width},applyEllipsis:function(a,g,b,d){var v=a.rotation,c=b,k,A=0,n=b.length,J=function(a){g.removeChild(g.firstChild);a&&g.appendChild(l.createTextNode(a))},e;a.rotation=0;c=this.getSpanWidth(a,g);if(e= c>d){for(;A<=n;)k=Math.ceil((A+n)/2),c=b.substring(0,k)+"\u2026",J(c),c=this.getSpanWidth(a,g),A===n?A=n+1:c>d?n=k-1:A=k;0===n&&J("")}a.rotation=v;return e},escapes:{"\x26":"\x26amp;","\x3c":"\x26lt;","\x3e":"\x26gt;","'":"\x26#39;",'"':"\x26quot;"},buildText:function(a){var d=a.element,v=this,c=v.forExport,k=F(a.textStr,"").toString(),A=-1!==k.indexOf("\x3c"),n=d.childNodes,e,B=h(d,"x"),u=a.styles,t=a.textWidth,G=u&&u.lineHeight,x=u&&u.textOutline,f=u&&"ellipsis"===u.textOverflow,P=u&&"nowrap"=== u.whiteSpace,O=u&&u.fontSize,w,q,H=n.length,u=t&&!a.added&&this.box,I=function(a){var b;b=/(px|em)$/.test(a&&a.style.fontSize)?a.style.fontSize:O||v.style.fontSize||12;return G?g(G):v.fontMetrics(b,a.getAttribute("style")?a:d).h},N=function(a,g){M(v.escapes,function(b,d){g&&-1!==p(b,g)||(a=a.toString().replace(new RegExp(b,"g"),d))});return a},m=function(a,g){var b;b=a.indexOf("\x3c");a=a.substring(b,a.indexOf("\x3e")-b);b=a.indexOf(g+"\x3d");if(-1!==b&&(b=b+g.length+1,g=a.charAt(b),'"'===g||"'"=== g))return a=a.substring(b+1),a.substring(0,a.indexOf(g))};w=[k,f,P,G,x,O,t].join();if(w!==a.textCache){for(a.textCache=w;H--;)d.removeChild(n[H]);A||x||f||t||-1!==k.indexOf(" ")?(u&&u.appendChild(d),k=A?k.replace(/<(b|strong)>/g,'\x3cspan style\x3d"font-weight:bold"\x3e').replace(/<(i|em)>/g,'\x3cspan style\x3d"font-style:italic"\x3e').replace(//g,"\x3c/span\x3e").split(//g):[k],k=b(k,function(a){return""!==a}),z(k,function(g,b){var k,A=0;g=g.replace(/^\s+|\s+$/g, "").replace(//g,"\x3c/span\x3e|||");k=g.split("|||");z(k,function(g){if(""!==g||1===k.length){var n={},u=l.createElementNS(v.SVG_NS,"tspan"),p,G;(p=m(g,"class"))&&h(u,"class",p);if(p=m(g,"style"))p=p.replace(/(;| |^)color([ :])/,"$1fill$2"),h(u,"style",p);(G=m(g,"href"))&&!c&&(h(u,"onclick",'location.href\x3d"'+G+'"'),h(u,"class","highcharts-anchor"),y(u,{cursor:"pointer"}));g=N(g.replace(/<[a-zA-Z\/](.|\n)*?>/g,"")||" ");if(" "!==g){u.appendChild(l.createTextNode(g)); A?n.dx=0:b&&null!==B&&(n.x=B);h(u,n);d.appendChild(u);!A&&q&&(!Q&&c&&y(u,{display:"block"}),h(u,"dy",I(u)));if(t){n=g.replace(/([^\^])-/g,"$1- ").split(" ");G=1t,void 0===e&&(e=g),g&&1!==n.length?(u.removeChild(u.firstChild),x.unshift(n.pop())):(n=x,x=[],n.length&&!P&&(u=l.createElementNS(J,"tspan"),h(u,{dy:O,x:B}),p&&h(u,"style",p),d.appendChild(u)), z>t&&(t=z+1)),n.length&&u.appendChild(l.createTextNode(n.join(" ").replace(/- /g,"-")));a.rotation=w}A++}}});q=q||d.childNodes.length}),f&&e&&a.attr("title",N(a.textStr,["\x26lt;","\x26gt;"])),u&&u.removeChild(d),x&&a.applyTextOutline&&a.applyTextOutline(x)):d.appendChild(l.createTextNode(N(k)))}},getContrast:function(a){a=r(a).rgba;a[0]*=1;a[1]*=1.2;a[2]*=.5;return 459Math.abs(v.end-v.start-2*Math.PI));var J=Math.cos(c),u=Math.sin(c),A=Math.cos(e),e=Math.sin(e);v=.001>v.end-c-Math.PI?0:1;k=["M",a+k*J,g+n*u,"A",k,n,0,v,1,a+k*A,g+n*e];w(b)&&k.push(d?"M":"L",a+b*A,g+b*e,"A",b,b,0,v,0,a+b*J,g+b*u);k.push(d?"":"Z");return k},callout:function(a,g,b,d,v){var c=Math.min(v&&v.r||0,b,d),k=c+6,n=v&&v.anchorX;v= v&&v.anchorY;var e;e=["M",a+c,g,"L",a+b-c,g,"C",a+b,g,a+b,g,a+b,g+c,"L",a+b,g+d-c,"C",a+b,g+d,a+b,g+d,a+b-c,g+d,"L",a+c,g+d,"C",a,g+d,a,g+d,a,g+d-c,"L",a,g+c,"C",a,g,a,g,a+c,g];n&&n>b?v>g+k&&vn?v>g+k&&vd&&n>a+k&&nv&&n>a+k&&na?a+3:Math.round(1.2*a);return{h:b,b:Math.round(.8*b),f:a}},rotCorr:function(a,g,b){var d=a;g&&b&&(d=Math.max(d*Math.cos(g*e),4));return{x:-a/3*Math.sin(g*e),y:d}},label:function(g, b,d,c,n,e,J,u,l){var B=this,p=B.g("button"!==l&&"label"),t=p.text=B.text("",0,0,J).attr({zIndex:1}),A,x,Q=0,f=3,P=0,h,O,q,F,H,I={},N,y,M=/^url\((.*?)\)$/.test(c),m=M,L,r,R,U;l&&p.addClass("highcharts-"+l);m=M;L=function(){return(N||0)%2/2};r=function(){var a=t.element.style,g={};x=(void 0===h||void 0===O||H)&&w(t.textStr)&&t.getBBox();p.width=(h||x.width||0)+2*f+P;p.height=(O||x.height||0)+2*f;y=f+B.fontMetrics(a&&a.fontSize,t).b;m&&(A||(p.box=A=B.symbols[c]||M?B.symbol(c):B.rect(),A.addClass(("button"=== l?"":"highcharts-label-box")+(l?" highcharts-"+l+"-box":"")),A.add(p),a=L(),g.x=a,g.y=(u?-y:0)+a),g.width=Math.round(p.width),g.height=Math.round(p.height),A.attr(k(g,I)),I={})};R=function(){var a=P+f,g;g=u?0:y;w(h)&&x&&("center"===H||"right"===H)&&(a+={center:.5,right:1}[H]*(h-x.width));if(a!==t.x||g!==t.y)t.attr("x",a),t.hasBoxWidthChanged&&(x=t.getBBox(!0),r()),void 0!==g&&t.attr("y",g);t.x=a;t.y=g};U=function(a,g){A?A.attr(a,g):I[a]=g};p.onAdd=function(){t.add(p);p.attr({text:g||0===g?g:"",x:b, y:d});A&&w(n)&&p.attr({anchorX:n,anchorY:e})};p.widthSetter=function(g){h=a.isNumber(g)?g:null};p.heightSetter=function(a){O=a};p["text-alignSetter"]=function(a){H=a};p.paddingSetter=function(a){w(a)&&a!==f&&(f=p.padding=a,R())};p.paddingLeftSetter=function(a){w(a)&&a!==P&&(P=a,R())};p.alignSetter=function(a){a={left:0,center:.5,right:1}[a];a!==Q&&(Q=a,x&&p.attr({x:q}))};p.textSetter=function(a){void 0!==a&&t.textSetter(a);r();R()};p["stroke-widthSetter"]=function(a,g){a&&(m=!0);N=this["stroke-width"]= a;U(g,a)};p.strokeSetter=p.fillSetter=p.rSetter=function(a,g){"r"!==g&&("fill"===g&&a&&(m=!0),p[g]=a);U(g,a)};p.anchorXSetter=function(a,g){n=p.anchorX=a;U(g,Math.round(a)-L()-q)};p.anchorYSetter=function(a,g){e=p.anchorY=a;U(g,a-F)};p.xSetter=function(a){p.x=a;Q&&(a-=Q*((h||x.width)+2*f),p["forceAnimate:x"]=!0);q=Math.round(a);p.attr("translateX",q)};p.ySetter=function(a){F=p.y=Math.round(a);p.attr("translateY",F)};var S=p.css;return k(p,{css:function(a){if(a){var g={};a=G(a);z(p.textProps,function(b){void 0!== a[b]&&(g[b]=a[b],delete a[b])});t.css(g);"width"in g&&r()}return S.call(p,a)},getBBox:function(){return{width:x.width+2*f,height:x.height+2*f,x:x.x-f,y:x.y-f}},shadow:function(a){a&&(r(),A&&A.shadow(a));return p},destroy:function(){v(p.element,"mouseenter");v(p.element,"mouseleave");t&&(t=t.destroy());A&&(A=A.destroy());C.prototype.destroy.call(p);p=B=r=R=U=null}})}});a.Renderer=D})(K);(function(a){var C=a.attr,D=a.createElement,E=a.css,m=a.defined,h=a.each,f=a.extend,r=a.isFirefox,y=a.isMS,q=a.isWebKit, w=a.pick,e=a.pInt,c=a.SVGRenderer,l=a.win,z=a.wrap;f(a.SVGElement.prototype,{htmlCss:function(a){var d=this.element;if((d=a&&"SPAN"===d.tagName&&a.width)||this.textWidth&&!d)delete a.width,this.textWidth=d,this.htmlUpdateTransform();a&&"ellipsis"===a.textOverflow&&(a.whiteSpace="nowrap",a.overflow="hidden");this.styles=f(this.styles,a);E(this.element,a);return this},htmlGetBBox:function(){var a=this.element;return{x:a.offsetLeft,y:a.offsetTop,width:a.offsetWidth,height:a.offsetHeight}},htmlUpdateTransform:function(){if(this.added){var a= this.renderer,d=this.element,b=this.translateX||0,c=this.translateY||0,p=this.x||0,l=this.y||0,t=this.textAlign||"left",f={left:0,center:.5,right:1}[t],x=this.styles,z=x&&x.whiteSpace;E(d,{marginLeft:b,marginTop:c});this.shadows&&h(this.shadows,function(a){E(a,{marginLeft:b+1,marginTop:c+1})});this.inverted&&h(d.childNodes,function(b){a.invertChild(b,d)});if("SPAN"===d.tagName){var x=this.rotation,n=this.textWidth&&e(this.textWidth),G=[x,t,d.innerHTML,this.textWidth,this.textAlign].join(),B;(B=n!== this.oldTextWidth)&&!(B=n>this.oldTextWidth)&&((B=this.textPxLength)||(E(d,{width:"",whiteSpace:z||"nowrap"}),B=d.offsetWidth),B=B>n);B&&/[ \-]/.test(d.textContent||d.innerText)?(E(d,{width:n+"px",display:"block",whiteSpace:z||"normal"}),this.oldTextWidth=n,this.hasBoxWidthChanged=!0):this.hasBoxWidthChanged=!1;G!==this.cTT&&(z=a.fontMetrics(d.style.fontSize).b,!m(x)||x===(this.oldRotation||0)&&t===this.oldAlign||this.setSpanRotation(x,f,z),this.getSpanCorrection(!m(x)&&this.textPxLength||d.offsetWidth, z,f,x,t));E(d,{left:p+(this.xCorr||0)+"px",top:l+(this.yCorr||0)+"px"});this.cTT=G;this.oldRotation=x;this.oldAlign=t}}else this.alignOnAdd=!0},setSpanRotation:function(a,d,b){var c={},k=this.renderer.getTransformKey();c[k]=c.transform="rotate("+a+"deg)";c[k+(r?"Origin":"-origin")]=c.transformOrigin=100*d+"% "+b+"px";E(this.element,c)},getSpanCorrection:function(a,d,b){this.xCorr=-a*b;this.yCorr=-d}});f(c.prototype,{getTransformKey:function(){return y&&!/Edge/.test(l.navigator.userAgent)?"-ms-transform": q?"-webkit-transform":r?"MozTransform":l.opera?"-o-transform":""},html:function(a,d,b){var c=this.createElement("span"),k=c.element,e=c.renderer,l=e.isSVG,q=function(a,b){h(["opacity","visibility"],function(d){z(a,d+"Setter",function(a,d,c,k){a.call(this,d,c,k);b[c]=d})});a.addedSetters=!0};c.textSetter=function(a){a!==k.innerHTML&&delete this.bBox;this.textStr=a;k.innerHTML=w(a,"");c.doTransform=!0};l&&q(c,c.element.style);c.xSetter=c.ySetter=c.alignSetter=c.rotationSetter=function(a,b){"align"=== b&&(b="textAlign");c[b]=a;c.doTransform=!0};c.afterSetters=function(){this.doTransform&&(this.htmlUpdateTransform(),this.doTransform=!1)};c.attr({text:a,x:Math.round(d),y:Math.round(b)}).css({fontFamily:this.style.fontFamily,fontSize:this.style.fontSize,position:"absolute"});k.style.whiteSpace="nowrap";c.css=c.htmlCss;l&&(c.add=function(a){var b,d=e.box.parentNode,p=[];if(this.parentGroup=a){if(b=a.div,!b){for(;a;)p.push(a),a=a.parentGroup;h(p.reverse(),function(a){function k(g,b){a[b]=g;"translateX"=== b?n.left=g+"px":n.top=g+"px";a.doTransform=!0}var n,g=C(a.element,"class");g&&(g={className:g});b=a.div=a.div||D("div",g,{position:"absolute",left:(a.translateX||0)+"px",top:(a.translateY||0)+"px",display:a.display,opacity:a.opacity,pointerEvents:a.styles&&a.styles.pointerEvents},b||d);n=b.style;f(a,{classSetter:function(a){return function(g){this.element.setAttribute("class",g);a.className=g}}(b),on:function(){p[0].div&&c.on.apply({element:p[0].div},arguments);return a},translateXSetter:k,translateYSetter:k}); a.addedSetters||q(a,n)})}}else b=d;b.appendChild(k);c.added=!0;c.alignOnAdd&&c.htmlUpdateTransform();return c});return c}})})(K);(function(a){var C=a.defined,D=a.each,E=a.extend,m=a.merge,h=a.pick,f=a.timeUnits,r=a.win;a.Time=function(a){this.update(a,!1)};a.Time.prototype={defaultOptions:{},update:function(a){var f=h(a&&a.useUTC,!0),w=this;this.options=a=m(!0,this.options||{},a);this.Date=a.Date||r.Date;this.timezoneOffset=(this.useUTC=f)&&a.timezoneOffset;this.getTimezoneOffset=this.timezoneOffsetFunction(); (this.variableTimezone=!(f&&!a.getTimezoneOffset&&!a.timezone))||this.timezoneOffset?(this.get=function(a,c){var e=c.getTime(),f=e-w.getTimezoneOffset(c);c.setTime(f);a=c["getUTC"+a]();c.setTime(e);return a},this.set=function(a,c,l){var e;if("Milliseconds"===a||"Seconds"===a||"Minutes"===a&&0===c.getTimezoneOffset()%60)c["set"+a](l);else e=w.getTimezoneOffset(c),e=c.getTime()-e,c.setTime(e),c["setUTC"+a](l),a=w.getTimezoneOffset(c),e=c.getTime()+a,c.setTime(e)}):f?(this.get=function(a,c){return c["getUTC"+ a]()},this.set=function(a,c,l){return c["setUTC"+a](l)}):(this.get=function(a,c){return c["get"+a]()},this.set=function(a,c,l){return c["set"+a](l)})},makeTime:function(f,q,w,e,c,l){var z,k,d;this.useUTC?(z=this.Date.UTC.apply(0,arguments),k=this.getTimezoneOffset(z),z+=k,d=this.getTimezoneOffset(z),k!==d?z+=d-k:k-36E5!==this.getTimezoneOffset(z-36E5)||a.isSafari||(z-=36E5)):z=(new this.Date(f,q,h(w,1),h(e,0),h(c,0),h(l,0))).getTime();return z},timezoneOffsetFunction:function(){var f=this,h=this.options, w=r.moment;if(!this.useUTC)return function(a){return 6E4*(new Date(a)).getTimezoneOffset()};if(h.timezone){if(w)return function(a){return 6E4*-w.tz(a,h.timezone).utcOffset()};a.error(25)}return this.useUTC&&h.getTimezoneOffset?function(a){return 6E4*h.getTimezoneOffset(a)}:function(){return 6E4*(f.timezoneOffset||0)}},dateFormat:function(f,h,w){if(!a.defined(h)||isNaN(h))return a.defaultOptions.lang.invalidDate||"";f=a.pick(f,"%Y-%m-%d %H:%M:%S");var e=this,c=new this.Date(h),l=this.get("Hours",c), z=this.get("Day",c),k=this.get("Date",c),d=this.get("Month",c),b=this.get("FullYear",c),u=a.defaultOptions.lang,p=u.weekdays,H=u.shortWeekdays,t=a.pad,c=a.extend({a:H?H[z]:p[z].substr(0,3),A:p[z],d:t(k),e:t(k,2," "),w:z,b:u.shortMonths[d],B:u.months[d],m:t(d+1),o:d+1,y:b.toString().substr(2,2),Y:b,H:t(l),k:l,I:t(l%12||12),l:l%12||12,M:t(e.get("Minutes",c)),p:12>l?"AM":"PM",P:12>l?"am":"pm",S:t(c.getSeconds()),L:t(Math.round(h%1E3),3)},a.dateFormats);a.objectEach(c,function(a,b){for(;-1!==f.indexOf("%"+ b);)f=f.replace("%"+b,"function"===typeof a?a.call(e,h):a)});return w?f.substr(0,1).toUpperCase()+f.substr(1):f},getTimeTicks:function(a,q,w,e){var c=this,l=[],z={},k,d=new c.Date(q),b=a.unitRange,u=a.count||1,p;if(C(q)){c.set("Milliseconds",d,b>=f.second?0:u*Math.floor(c.get("Milliseconds",d)/u));b>=f.second&&c.set("Seconds",d,b>=f.minute?0:u*Math.floor(c.get("Seconds",d)/u));b>=f.minute&&c.set("Minutes",d,b>=f.hour?0:u*Math.floor(c.get("Minutes",d)/u));b>=f.hour&&c.set("Hours",d,b>=f.day?0:u*Math.floor(c.get("Hours", d)/u));b>=f.day&&c.set("Date",d,b>=f.month?1:u*Math.floor(c.get("Date",d)/u));b>=f.month&&(c.set("Month",d,b>=f.year?0:u*Math.floor(c.get("Month",d)/u)),k=c.get("FullYear",d));b>=f.year&&c.set("FullYear",d,k-k%u);b===f.week&&c.set("Date",d,c.get("Date",d)-c.get("Day",d)+h(e,1));k=c.get("FullYear",d);e=c.get("Month",d);var H=c.get("Date",d),t=c.get("Hours",d);q=d.getTime();c.variableTimezone&&(p=w-q>4*f.month||c.getTimezoneOffset(q)!==c.getTimezoneOffset(w));d=d.getTime();for(q=1;dl.length&&D(l,function(a){0===a%18E5&&"000000000"===c.dateFormat("%H%M%S%L",a)&&(z[a]="day")})}l.info=E(a,{higherRanks:z,totalRange:b*u});return l}}})(K);(function(a){var C=a.color,D=a.merge;a.defaultOptions={colors:"#7cb5ec #434348 #90ed7d #f7a35c #8085e9 #f15c80 #e4d354 #2b908f #f45b5b #91e8e1".split(" "), symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:"January February March April May June July August September October November December".split(" "),shortMonths:"Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" "),weekdays:"Sunday Monday Tuesday Wednesday Thursday Friday Saturday".split(" "),decimalPoint:".",numericSymbols:"kMGTPE".split(""),resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:" "},global:{},time:a.Time.prototype.defaultOptions, chart:{borderRadius:0,defaultSeriesType:"line",ignoreHiddenSeries:!0,spacing:[10,10,15,10],resetZoomButton:{theme:{zIndex:6},position:{align:"right",x:-10,y:10}},width:null,height:null,borderColor:"#335cad",backgroundColor:"#ffffff",plotBorderColor:"#cccccc"},title:{text:"Chart title",align:"center",margin:15,widthAdjust:-44},subtitle:{text:"",align:"center",widthAdjust:-44},plotOptions:{},labels:{style:{position:"absolute",color:"#333333"}},legend:{enabled:!0,align:"center",alignColumns:!0,layout:"horizontal", labelFormatter:function(){return this.name},borderColor:"#999999",borderRadius:0,navigation:{activeColor:"#003399",inactiveColor:"#cccccc"},itemStyle:{color:"#333333",fontSize:"12px",fontWeight:"bold",textOverflow:"ellipsis"},itemHoverStyle:{color:"#000000"},itemHiddenStyle:{color:"#cccccc"},shadow:!1,itemCheckboxStyle:{position:"absolute",width:"13px",height:"13px"},squareSymbol:!0,symbolPadding:5,verticalAlign:"bottom",x:0,y:0,title:{style:{fontWeight:"bold"}}},loading:{labelStyle:{fontWeight:"bold", position:"relative",top:"45%"},style:{position:"absolute",backgroundColor:"#ffffff",opacity:.5,textAlign:"center"}},tooltip:{enabled:!0,animation:a.svg,borderRadius:3,dateTimeLabelFormats:{millisecond:"%A, %b %e, %H:%M:%S.%L",second:"%A, %b %e, %H:%M:%S",minute:"%A, %b %e, %H:%M",hour:"%A, %b %e, %H:%M",day:"%A, %b %e, %Y",week:"Week from %A, %b %e, %Y",month:"%B %Y",year:"%Y"},footerFormat:"",padding:8,snap:a.isTouchDevice?25:10,backgroundColor:C("#f7f7f7").setOpacity(.85).get(),borderWidth:1,headerFormat:'\x3cspan style\x3d"font-size: 10px"\x3e{point.key}\x3c/span\x3e\x3cbr/\x3e', pointFormat:'\x3cspan style\x3d"color:{point.color}"\x3e\u25cf\x3c/span\x3e {series.name}: \x3cb\x3e{point.y}\x3c/b\x3e\x3cbr/\x3e',shadow:!0,style:{color:"#333333",cursor:"default",fontSize:"12px",pointerEvents:"none",whiteSpace:"nowrap"}},credits:{enabled:!0,href:"https://www.highcharts.com",position:{align:"right",x:-10,verticalAlign:"bottom",y:-5},style:{cursor:"pointer",color:"#999999",fontSize:"9px"},text:"Highcharts.com"}};a.setOptions=function(C){a.defaultOptions=D(!0,a.defaultOptions,C); a.time.update(D(a.defaultOptions.global,a.defaultOptions.time),!1);return a.defaultOptions};a.getOptions=function(){return a.defaultOptions};a.defaultPlotOptions=a.defaultOptions.plotOptions;a.time=new a.Time(D(a.defaultOptions.global,a.defaultOptions.time));a.dateFormat=function(C,m,h){return a.time.dateFormat(C,m,h)}})(K);(function(a){var C=a.correctFloat,D=a.defined,E=a.destroyObjectProperties,m=a.fireEvent,h=a.isNumber,f=a.merge,r=a.pick,y=a.deg2rad;a.Tick=function(a,f,e,c){this.axis=a;this.pos= f;this.type=e||"";this.isNewLabel=this.isNew=!0;e||c||this.addLabel()};a.Tick.prototype={addLabel:function(){var a=this.axis,h=a.options,e=a.chart,c=a.categories,l=a.names,z=this.pos,k=h.labels,d=a.tickPositions,b=z===d[0],u=z===d[d.length-1],l=c?r(c[z],l[z],z):z,c=this.label,d=d.info,p;a.isDatetimeAxis&&d&&(p=h.dateTimeLabelFormats[d.higherRanks[z]||d.unitName]);this.isFirst=b;this.isLast=u;h={axis:a,chart:e,isFirst:b,isLast:u,dateTimeLabelFormat:p,value:a.isLog?C(a.lin2log(l)):l,pos:z};h=a.labelFormatter.call(h, h);if(D(c))c&&c.attr({text:h});else{if(this.label=c=D(h)&&k.enabled?e.renderer.text(h,0,0,k.useHTML).css(f(k.style)).add(a.labelGroup):null)c.textPxLength=c.getBBox().width;this.rotation=0}},getLabelSize:function(){return this.label?this.label.getBBox()[this.axis.horiz?"height":"width"]:0},handleOverflow:function(a){var f=this.axis,e=f.options.labels,c=a.x,l=f.chart.chartWidth,z=f.chart.spacing,k=r(f.labelLeft,Math.min(f.pos,z[3])),z=r(f.labelRight,Math.max(f.isRadial?0:f.pos+f.len,l-z[1])),d=this.label, b=this.rotation,u={left:0,center:.5,right:1}[f.labelAlign||d.attr("align")],p=d.getBBox().width,h=f.getSlotWidth(this),t=h,q=1,x,I={};if(b||!1===e.overflow)0>b&&c-u*pz&&(x=Math.round((l-c)/Math.cos(b*y)));else if(l=c+(1-u)*p,c-u*pz&&(t=z-a.x+t*u,q=-1),t=Math.min(h,t),tt||f.autoRotation&&(d.styles||{}).width)x=t;x&&(I.width=x,(e.style||{}).textOverflow||(I.textOverflow= "ellipsis"),d.css(I))},getPosition:function(f,h,e,c){var l=this.axis,z=l.chart,k=c&&z.oldChartHeight||z.chartHeight;f={x:f?a.correctFloat(l.translate(h+e,null,null,c)+l.transB):l.left+l.offset+(l.opposite?(c&&z.oldChartWidth||z.chartWidth)-l.right-l.left:0),y:f?k-l.bottom+l.offset-(l.opposite?l.height:0):a.correctFloat(k-l.translate(h+e,null,null,c)-l.transB)};m(this,"afterGetPosition",{pos:f});return f},getLabelPosition:function(a,f,e,c,l,h,k,d){var b=this.axis,u=b.transA,p=b.reversed,z=b.staggerLines, t=b.tickRotCorr||{x:0,y:0},w=l.y,x=c||b.reserveSpaceDefault?0:-b.labelOffset*("center"===b.labelAlign?.5:1),q={};D(w)||(w=0===b.side?e.rotation?-8:-e.getBBox().height:2===b.side?t.y+8:Math.cos(e.rotation*y)*(t.y-e.getBBox(!1,0).height/2));a=a+l.x+x+t.x-(h&&c?h*u*(p?-1:1):0);f=f+w-(h&&!c?h*u*(p?1:-1):0);z&&(e=k/(d||1)%z,b.opposite&&(e=z-e-1),f+=b.labelOffset/z*e);q.x=a;q.y=Math.round(f);m(this,"afterGetLabelPosition",{pos:q});return q},getMarkPath:function(a,f,e,c,l,h){return h.crispLine(["M",a,f, "L",a+(l?0:-e),f+(l?e:0)],c)},renderGridLine:function(a,f,e){var c=this.axis,l=c.options,h=this.gridLine,k={},d=this.pos,b=this.type,u=c.tickmarkOffset,p=c.chart.renderer,H=b?b+"Grid":"grid",t=l[H+"LineWidth"],w=l[H+"LineColor"],l=l[H+"LineDashStyle"];h||(k.stroke=w,k["stroke-width"]=t,l&&(k.dashstyle=l),b||(k.zIndex=1),a&&(k.opacity=0),this.gridLine=h=p.path().attr(k).addClass("highcharts-"+(b?b+"-":"")+"grid-line").add(c.gridGroup));if(!a&&h&&(a=c.getPlotLinePath(d+u,h.strokeWidth()*e,a,!0)))h[this.isNew? "attr":"animate"]({d:a,opacity:f})},renderMark:function(a,f,e){var c=this.axis,l=c.options,h=c.chart.renderer,k=this.type,d=k?k+"Tick":"tick",b=c.tickSize(d),u=this.mark,p=!u,H=a.x;a=a.y;var t=r(l[d+"Width"],!k&&c.isXAxis?1:0),l=l[d+"Color"];b&&(c.opposite&&(b[0]=-b[0]),p&&(this.mark=u=h.path().addClass("highcharts-"+(k?k+"-":"")+"tick").add(c.axisGroup),u.attr({stroke:l,"stroke-width":t})),u[p?"attr":"animate"]({d:this.getMarkPath(H,a,b[0],u.strokeWidth()*e,c.horiz,h),opacity:f}))},renderLabel:function(a, f,e,c){var l=this.axis,z=l.horiz,k=l.options,d=this.label,b=k.labels,u=b.step,l=l.tickmarkOffset,p=!0,H=a.x;a=a.y;d&&h(H)&&(d.xy=a=this.getLabelPosition(H,a,d,z,b,l,c,u),this.isFirst&&!this.isLast&&!r(k.showFirstLabel,1)||this.isLast&&!this.isFirst&&!r(k.showLastLabel,1)?p=!1:!z||b.step||b.rotation||f||0===e||this.handleOverflow(a),u&&c%u&&(p=!1),p&&h(a.y)?(a.opacity=e,d[this.isNewLabel?"attr":"animate"](a),this.isNewLabel=!1):(d.attr("y",-9999),this.isNewLabel=!0))},render:function(f,h,e){var c= this.axis,l=c.horiz,z=this.getPosition(l,this.pos,c.tickmarkOffset,h),k=z.x,d=z.y,c=l&&k===c.pos+c.len||!l&&d===c.pos?-1:1;e=r(e,1);this.isActive=!0;this.renderGridLine(h,e,c);this.renderMark(z,e,c);this.renderLabel(z,h,e,f);this.isNew=!1;a.fireEvent(this,"afterRender")},destroy:function(){E(this,this.axis)}}})(K);var V=function(a){var C=a.addEvent,D=a.animObject,E=a.arrayMax,m=a.arrayMin,h=a.color,f=a.correctFloat,r=a.defaultOptions,y=a.defined,q=a.deg2rad,w=a.destroyObjectProperties,e=a.each,c= a.extend,l=a.fireEvent,z=a.format,k=a.getMagnitude,d=a.grep,b=a.inArray,u=a.isArray,p=a.isNumber,H=a.isString,t=a.merge,L=a.normalizeTickInterval,x=a.objectEach,I=a.pick,n=a.removeEvent,G=a.splat,B=a.syncTimeout,M=a.Tick,F=function(){this.init.apply(this,arguments)};a.extend(F.prototype,{defaultOptions:{dateTimeLabelFormats:{millisecond:"%H:%M:%S.%L",second:"%H:%M:%S",minute:"%H:%M",hour:"%H:%M",day:"%e. %b",week:"%e. %b",month:"%b '%y",year:"%Y"},endOnTick:!1,labels:{enabled:!0,x:0,style:{color:"#666666", cursor:"default",fontSize:"11px"}},maxPadding:.01,minorTickLength:2,minorTickPosition:"outside",minPadding:.01,startOfWeek:1,startOnTick:!1,tickLength:10,tickPixelInterval:100,tickmarkPlacement:"between",tickPosition:"outside",title:{align:"middle",style:{color:"#666666"}},type:"linear",minorGridLineColor:"#f2f2f2",minorGridLineWidth:1,minorTickColor:"#999999",lineColor:"#ccd6eb",lineWidth:1,gridLineColor:"#e6e6e6",tickColor:"#ccd6eb"},defaultYAxisOptions:{endOnTick:!0,maxPadding:.05,minPadding:.05, tickPixelInterval:72,showLastLabel:!0,labels:{x:-8},startOnTick:!0,title:{rotation:270,text:"Values"},stackLabels:{allowOverlap:!1,enabled:!1,formatter:function(){return a.numberFormat(this.total,-1)},style:{fontSize:"11px",fontWeight:"bold",color:"#000000",textOutline:"1px contrast"}},gridLineWidth:1,lineWidth:0},defaultLeftAxisOptions:{labels:{x:-15},title:{rotation:270}},defaultRightAxisOptions:{labels:{x:15},title:{rotation:90}},defaultBottomAxisOptions:{labels:{autoRotation:[-45],x:0},title:{rotation:0}}, defaultTopAxisOptions:{labels:{autoRotation:[-45],x:0},title:{rotation:0}},init:function(a,d){var g=d.isX,v=this;v.chart=a;v.horiz=a.inverted&&!v.isZAxis?!g:g;v.isXAxis=g;v.coll=v.coll||(g?"xAxis":"yAxis");l(this,"init",{userOptions:d});v.opposite=d.opposite;v.side=d.side||(v.horiz?v.opposite?0:2:v.opposite?1:3);v.setOptions(d);var c=this.options,k=c.type;v.labelFormatter=c.labels.formatter||v.defaultLabelFormatter;v.userOptions=d;v.minPixelPadding=0;v.reversed=c.reversed;v.visible=!1!==c.visible; v.zoomEnabled=!1!==c.zoomEnabled;v.hasNames="category"===k||!0===c.categories;v.categories=c.categories||v.hasNames;v.names||(v.names=[],v.names.keys={});v.plotLinesAndBandsGroups={};v.isLog="logarithmic"===k;v.isDatetimeAxis="datetime"===k;v.positiveValuesOnly=v.isLog&&!v.allowNegativeLog;v.isLinked=y(c.linkedTo);v.ticks={};v.labelEdge=[];v.minorTicks={};v.plotLinesAndBands=[];v.alternateBands={};v.len=0;v.minRange=v.userMinRange=c.minRange||c.maxZoom;v.range=c.range;v.offset=c.offset||0;v.stacks= {};v.oldStacks={};v.stacksTouched=0;v.max=null;v.min=null;v.crosshair=I(c.crosshair,G(a.options.tooltip.crosshairs)[g?0:1],!1);d=v.options.events;-1===b(v,a.axes)&&(g?a.axes.splice(a.xAxis.length,0,v):a.axes.push(v),a[v.coll].push(v));v.series=v.series||[];a.inverted&&!v.isZAxis&&g&&void 0===v.reversed&&(v.reversed=!0);x(d,function(a,g){C(v,g,a)});v.lin2log=c.linearToLogConverter||v.lin2log;v.isLog&&(v.val2lin=v.log2lin,v.lin2val=v.lin2log);l(this,"afterInit")},setOptions:function(a){this.options= t(this.defaultOptions,"yAxis"===this.coll&&this.defaultYAxisOptions,[this.defaultTopAxisOptions,this.defaultRightAxisOptions,this.defaultBottomAxisOptions,this.defaultLeftAxisOptions][this.side],t(r[this.coll],a));l(this,"afterSetOptions",{userOptions:a})},defaultLabelFormatter:function(){var g=this.axis,b=this.value,d=g.chart.time,c=g.categories,k=this.dateTimeLabelFormat,n=r.lang,e=n.numericSymbols,n=n.numericSymbolMagnitude||1E3,p=e&&e.length,l,u=g.options.labels.format,g=g.isLog?Math.abs(b):g.tickInterval; if(u)l=z(u,this,d);else if(c)l=b;else if(k)l=d.dateFormat(k,b);else if(p&&1E3<=g)for(;p--&&void 0===l;)d=Math.pow(n,p+1),g>=d&&0===10*b%d&&null!==e[p]&&0!==b&&(l=a.numberFormat(b/d,-1)+e[p]);void 0===l&&(l=1E4<=Math.abs(b)?a.numberFormat(b,-1):a.numberFormat(b,-1,void 0,""));return l},getSeriesExtremes:function(){var a=this,b=a.chart;l(this,"getSeriesExtremes",null,function(){a.hasVisibleSeries=!1;a.dataMin=a.dataMax=a.threshold=null;a.softThreshold=!a.isXAxis;a.buildStacks&&a.buildStacks();e(a.series, function(g){if(g.visible||!b.options.chart.ignoreHiddenSeries){var v=g.options,c=v.threshold,k;a.hasVisibleSeries=!0;a.positiveValuesOnly&&0>=c&&(c=null);if(a.isXAxis)v=g.xData,v.length&&(g=m(v),k=E(v),p(g)||g instanceof Date||(v=d(v,p),g=m(v),k=E(v)),v.length&&(a.dataMin=Math.min(I(a.dataMin,v[0],g),g),a.dataMax=Math.max(I(a.dataMax,v[0],k),k)));else if(g.getExtremes(),k=g.dataMax,g=g.dataMin,y(g)&&y(k)&&(a.dataMin=Math.min(I(a.dataMin,g),g),a.dataMax=Math.max(I(a.dataMax,k),k)),y(c)&&(a.threshold= c),!v.softThreshold||a.positiveValuesOnly)a.softThreshold=!1}})});l(this,"afterGetSeriesExtremes")},translate:function(a,b,d,c,k,n){var g=this.linkedParent||this,v=1,e=0,J=c?g.oldTransA:g.transA;c=c?g.oldMin:g.min;var l=g.minPixelPadding;k=(g.isOrdinal||g.isBroken||g.isLog&&k)&&g.lin2val;J||(J=g.transA);d&&(v*=-1,e=g.len);g.reversed&&(v*=-1,e-=v*(g.sector||g.len));b?(a=(a*v+e-l)/J+c,k&&(a=g.lin2val(a))):(k&&(a=g.val2lin(a)),a=p(c)?v*(a-c)*J+e+v*l+(p(n)?J*n:0):void 0);return a},toPixels:function(a, b){return this.translate(a,!1,!this.horiz,null,!0)+(b?0:this.pos)},toValue:function(a,b){return this.translate(a-(b?0:this.pos),!0,!this.horiz,null,!0)},getPlotLinePath:function(a,b,d,c,k){var g=this.chart,v=this.left,n=this.top,e,J,l=d&&g.oldChartHeight||g.chartHeight,u=d&&g.oldChartWidth||g.chartWidth,B;e=this.transB;var f=function(a,g,b){if(ab)c?a=Math.min(Math.max(g,a),b):B=!0;return a};k=I(k,this.translate(a,null,null,d));k=Math.min(Math.max(-1E5,k),1E5);a=d=Math.round(k+e);e=J=Math.round(l- k-e);p(k)?this.horiz?(e=n,J=l-this.bottom,a=d=f(a,v,v+this.width)):(a=v,d=u-this.right,e=J=f(e,n,n+this.height)):(B=!0,c=!1);return B&&!c?null:g.renderer.crispLine(["M",a,e,"L",d,J],b||1)},getLinearTickPositions:function(a,b,d){var g,v=f(Math.floor(b/a)*a);d=f(Math.ceil(d/a)*a);var c=[],k;f(v+a)===v&&(k=20);if(this.single)return[b];for(b=v;b<=d;){c.push(b);b=f(b+a,k);if(b===g)break;g=b}return c},getMinorTickInterval:function(){var a=this.options;return!0===a.minorTicks?I(a.minorTickInterval,"auto"): !1===a.minorTicks?null:a.minorTickInterval},getMinorTickPositions:function(){var a=this,b=a.options,d=a.tickPositions,c=a.minorTickInterval,k=[],n=a.pointRangePadding||0,p=a.min-n,n=a.max+n,l=n-p;if(l&&l/c=this.minRange,f=this.minRange,c=(f-d+b)/2,c=[b-c,I(a.min, b-c)],k&&(c[2]=this.isLog?this.log2lin(this.dataMin):this.dataMin),b=E(c),d=[b+f,I(a.max,b+f)],k&&(d[2]=this.isLog?this.log2lin(this.dataMax):this.dataMax),d=m(d),d-b=H?(q=H,G=0):g.dataMax<=H&&(M=H,h=0)),g.min=I(m,q,g.dataMin),g.max=I(r,M,g.dataMax));n&&(g.positiveValuesOnly&& !b&&0>=Math.min(g.min,I(g.dataMin,g.min))&&a.error(10,1),g.min=f(g.log2lin(g.min),15),g.max=f(g.log2lin(g.max),15));g.range&&y(g.max)&&(g.userMin=g.min=m=Math.max(g.dataMin,g.minFromRange()),g.userMax=r=g.max,g.range=null);l(g,"foundExtremes");g.beforePadding&&g.beforePadding();g.adjustForMinRange();!(F||g.axisPointRange||g.usePercentage||t)&&y(g.min)&&y(g.max)&&(d=g.max-g.min)&&(!y(m)&&G&&(g.min-=d*G),!y(r)&&h&&(g.max+=d*h));p(c.softMin)&&!p(g.userMin)&&(g.min=Math.min(g.min,c.softMin));p(c.softMax)&& !p(g.userMax)&&(g.max=Math.max(g.max,c.softMax));p(c.floor)&&(g.min=Math.max(g.min,c.floor));p(c.ceiling)&&(g.max=Math.min(g.max,c.ceiling));w&&y(g.dataMin)&&(H=H||0,!y(m)&&g.min=H?g.min=H:!y(r)&&g.max>H&&g.dataMax<=H&&(g.max=H));g.tickInterval=g.min===g.max||void 0===g.min||void 0===g.max?1:t&&!x&&z===g.linkedParent.options.tickPixelInterval?x=g.linkedParent.tickInterval:I(x,this.tickAmount?(g.max-g.min)/Math.max(this.tickAmount-1,1):void 0,F?1:(g.max-g.min)*z/Math.max(g.len,z));B&& !b&&e(g.series,function(a){a.processData(g.min!==g.oldMin||g.max!==g.oldMax)});g.setAxisTranslation(!0);g.beforeSetTickPositions&&g.beforeSetTickPositions();g.postProcessTickInterval&&(g.tickInterval=g.postProcessTickInterval(g.tickInterval));g.pointRange&&!x&&(g.tickInterval=Math.max(g.pointRange,g.tickInterval));b=I(c.minTickInterval,g.isDatetimeAxis&&g.closestPointRange);!x&&g.tickIntervalg.tickInterval&&1E3g.max)),!!this.tickAmount));this.tickAmount||(g.tickInterval=g.unsquish());this.setTickPositions()},setTickPositions:function(){var a=this.options,b,d=a.tickPositions;b=this.getMinorTickInterval();var c=a.tickPositioner,k=a.startOnTick,n=a.endOnTick;this.tickmarkOffset=this.categories&&"between"===a.tickmarkPlacement&&1===this.tickInterval?.5:0;this.minorTickInterval="auto"===b&&this.tickInterval?this.tickInterval/5:b;this.single=this.min===this.max&& y(this.min)&&!this.tickAmount&&(parseInt(this.min,10)===this.min||!1!==a.allowDecimals);this.tickPositions=b=d&&d.slice();!b&&(b=this.isDatetimeAxis?this.getTimeTicks(this.normalizeTimeTickInterval(this.tickInterval,a.units),this.min,this.max,a.startOfWeek,this.ordinalPositions,this.closestPointRange,!0):this.isLog?this.getLogTickPositions(this.tickInterval,this.min,this.max):this.getLinearTickPositions(this.tickInterval,this.min,this.max),b.length>this.len&&(b=[b[0],b.pop()],b[0]===b[1]&&(b.length= 1)),this.tickPositions=b,c&&(c=c.apply(this,[this.min,this.max])))&&(this.tickPositions=b=c);this.paddedTicks=b.slice(0);this.trimTicks(b,k,n);this.isLinked||(this.single&&2>b.length&&(this.min-=.5,this.max+=.5),d||c||this.adjustTickAmount());l(this,"afterSetTickPositions")},trimTicks:function(a,b,d){var g=a[0],c=a[a.length-1],k=this.minPointOffset||0;if(!this.isLinked){if(b&&-Infinity!==g)this.min=g;else for(;this.min-k>a[0];)a.shift();if(d)this.max=c;else for(;this.max+kb&&(this.finalTickAmt=b,b=5);this.tickAmount=b},adjustTickAmount:function(){var a=this.tickInterval,b=this.tickPositions,d=this.tickAmount,c=this.finalTickAmt,k=b&&b.length,n=I(this.threshold,this.softThreshold?0:null);if(this.hasData()){if(k d&&(this.tickInterval*=2,this.setTickPositions());if(y(c)){for(a=d=b.length;a--;)(3===c&&1===a%2||2>=c&&0c&&(a=c)),y(d)&&(bc&&(b=c))),this.displayBtn=void 0!==a||void 0!==b,this.setExtremes(a,b,!1,void 0,{trigger:"zoom"});return!0},setAxisSize:function(){var b=this.chart,d=this.options,c=d.offsets||[0,0,0,0],k=this.horiz,n=this.width=Math.round(a.relativeLength(I(d.width,b.plotWidth-c[3]+ c[1]),b.plotWidth)),e=this.height=Math.round(a.relativeLength(I(d.height,b.plotHeight-c[0]+c[2]),b.plotHeight)),p=this.top=Math.round(a.relativeLength(I(d.top,b.plotTop+c[0]),b.plotHeight,b.plotTop)),d=this.left=Math.round(a.relativeLength(I(d.left,b.plotLeft+c[3]),b.plotWidth,b.plotLeft));this.bottom=b.chartHeight-e-p;this.right=b.chartWidth-n-d;this.len=Math.max(k?n:e,0);this.pos=k?d:p},getExtremes:function(){var a=this.isLog;return{min:a?f(this.lin2log(this.min)):this.min,max:a?f(this.lin2log(this.max)): this.max,dataMin:this.dataMin,dataMax:this.dataMax,userMin:this.userMin,userMax:this.userMax}},getThreshold:function(a){var b=this.isLog,g=b?this.lin2log(this.min):this.min,b=b?this.lin2log(this.max):this.max;null===a||-Infinity===a?a=g:Infinity===a?a=b:g>a?a=g:ba?"right":195a?"left":"center"},tickSize:function(a){var b=this.options,g=b[a+"Length"],d=I(b[a+"Width"],"tick"=== a&&this.isXAxis?1:0);if(d&&g)return"inside"===b[a+"Position"]&&(g=-g),[g,d]},labelMetrics:function(){var a=this.tickPositions&&this.tickPositions[0]||0;return this.chart.renderer.fontMetrics(this.options.labels.style&&this.options.labels.style.fontSize,this.ticks[a]&&this.ticks[a].label)},unsquish:function(){var a=this.options.labels,b=this.horiz,d=this.tickInterval,c=d,k=this.len/(((this.categories?1:0)+this.max-this.min)/d),n,p=a.rotation,l=this.labelMetrics(),u,B=Number.MAX_VALUE,t,h=function(a){a/= k||1;a=1=a)u=h(Math.abs(l.h/Math.sin(q*a))),b=u+Math.abs(a/360),b(d.step||0)&& !d.rotation&&(this.staggerLines||1)*this.len/c||!b&&(d.style&&parseInt(d.style.width,10)||k&&k-a.spacing[3]||.33*a.chartWidth)},renderUnsquish:function(){var a=this.chart,b=a.renderer,d=this.tickPositions,c=this.ticks,k=this.options.labels,n=k&&k.style||{},p=this.horiz,l=this.getSlotWidth(),u=Math.max(1,Math.round(l-2*(k.padding||5))),B={},f=this.labelMetrics(),t=k.style&&k.style.textOverflow,h,G,x=0,z;H(k.rotation)||(B.rotation=k.rotation||0);e(d,function(a){(a=c[a])&&a.label&&a.label.textPxLength> x&&(x=a.label.textPxLength)});this.maxLabelLength=x;if(this.autoRotation)x>u&&x>f.h?B.rotation=this.labelRotation:this.labelRotation=0;else if(l&&(h=u,!t))for(G="clip",u=d.length;!p&&u--;)if(z=d[u],z=c[z].label)z.styles&&"ellipsis"===z.styles.textOverflow?z.css({textOverflow:"clip"}):z.textPxLength>l&&z.css({width:l+"px"}),z.getBBox().height>this.len/d.length-(f.h-f.f)&&(z.specificTextOverflow="ellipsis");B.rotation&&(h=x>.5*a.chartHeight?.33*a.chartHeight:x,t||(G="ellipsis"));if(this.labelAlign= k.align||this.autoLabelAlign(this.labelRotation))B.align=this.labelAlign;e(d,function(a){var b=(a=c[a])&&a.label,g=n.width,d={};b&&(b.attr(B),h&&!g&&"nowrap"!==n.whiteSpace&&(h=this.min&&a<=this.max)g[a]||(g[a]=new M(this,a)),c&&g[a].isNew&&g[a].render(b,!0,.1),g[a].render(b)},render:function(){var b=this,d=b.chart,c=b.options,k=b.isLog,n=b.isLinked,u=b.tickPositions,f=b.axisTitle,t=b.ticks,h=b.minorTicks,G=b.alternateBands,z=c.stackLabels,H=c.alternateGridColor, F=b.tickmarkOffset,w=b.axisLine,I=b.showAxis,m=D(d.renderer.globalAnimation),q,r;b.labelEdge.length=0;b.overlap=!1;e([t,h,G],function(a){x(a,function(a){a.isActive=!1})});if(b.hasData()||n)b.minorTickInterval&&!b.categories&&e(b.getMinorTickPositions(),function(a){b.renderMinorTick(a)}),u.length&&(e(u,function(a,d){b.renderTick(a,d)}),F&&(0===b.min||b.single)&&(t[-1]||(t[-1]=new M(b,-1,null,!0)),t[-1].render(-1))),H&&e(u,function(c,g){r=void 0!==u[g+1]?u[g+1]+F:b.max-F;0===g%2&&cr&&(!q||d<=y)&&void 0!==d&&c.push(d),d>y&&(b=!0),d=k;else r=this.lin2log(r),y=this.lin2log(y),a=q?this.getMinorTickInterval():f.tickInterval,a=h("auto"===a?null:a,this._minorAutoInterval,f.tickPixelInterval/(q?5:1)*(y-r)/((q?e/this.tickPositions.length: e)||1)),a=m(a,null,D(a)),c=E(this.getLinearTickPositions(a,r,y),this.log2lin),q||(this._minorAutoInterval=a/5);q||(this.tickInterval=a);return c};C.prototype.log2lin=function(a){return Math.log(a)/Math.LN10};C.prototype.lin2log=function(a){return Math.pow(10,a)}})(K);(function(a,C){var D=a.arrayMax,E=a.arrayMin,m=a.defined,h=a.destroyObjectProperties,f=a.each,r=a.erase,y=a.merge,q=a.pick;a.PlotLineOrBand=function(a,e){this.axis=a;e&&(this.options=e,this.id=e.id)};a.PlotLineOrBand.prototype={render:function(){var f= this,e=f.axis,c=e.horiz,l=f.options,h=l.label,k=f.label,d=l.to,b=l.from,u=l.value,p=m(b)&&m(d),H=m(u),t=f.svgElem,r=!t,x=[],I=l.color,n=q(l.zIndex,0),G=l.events,x={"class":"highcharts-plot-"+(p?"band ":"line ")+(l.className||"")},B={},M=e.chart.renderer,F=p?"bands":"lines";e.isLog&&(b=e.log2lin(b),d=e.log2lin(d),u=e.log2lin(u));H?(x.stroke=I,x["stroke-width"]=l.width,l.dashStyle&&(x.dashstyle=l.dashStyle)):p&&(I&&(x.fill=I),l.borderWidth&&(x.stroke=l.borderColor,x["stroke-width"]=l.borderWidth)); B.zIndex=n;F+="-"+n;(I=e.plotLinesAndBandsGroups[F])||(e.plotLinesAndBandsGroups[F]=I=M.g("plot-"+F).attr(B).add());r&&(f.svgElem=t=M.path().attr(x).add(I));if(H)x=e.getPlotLinePath(u,t.strokeWidth());else if(p)x=e.getPlotBandPath(b,d,l);else return;r&&x&&x.length?(t.attr({d:x}),G&&a.objectEach(G,function(a,b){t.on(b,function(a){G[b].apply(f,[a])})})):t&&(x?(t.show(),t.animate({d:x})):(t.hide(),k&&(f.label=k=k.destroy())));h&&m(h.text)&&x&&x.length&&0this.max&&e>this.max;if(l&&c)for(a&&(b=l.toString()===c.toString(),d=0),a=0;aB-u?B:B-u);else if(f)b[a]=Math.max(n,k+u+g>c?k:k+u);else return!1},q=function(a,c,g,k){var n;kc-d?n=!1:b[a]=kc-g/2?c-g-2:k-g/ 2;return n},F=function(a){var b=z;z=n;n=b;p=a},g=function(){!1!==B.apply(0,z)?!1!==q.apply(0,n)||p||(F(!0),g()):p?b.x=b.y=0:(F(!0),g())};(c.inverted||1G&&(u=!1);a=(c.series&&c.series.yAxis&&c.series.yAxis.pos)+(c.plotY||0);a-=d.plotTop;k.push({target:c.isHeader?d.plotHeight+l:a,rank:c.isHeader?1:0,size:h.tt.getBBox().height+1,point:c,x:G,tt:n})}});this.cleanSplit();a.distribute(k,d.plotHeight+l);D(k,function(a){var b=a.point,c=b.series;a.tt.attr({visibility:void 0===a.pos?"hidden":"inherit",x:u||b.isHeader?a.x:b.plotX+d.plotLeft+y(p.distance, 16),y:a.pos+d.plotTop,anchorX:b.isHeader?b.plotX+d.plotLeft:b.plotX+c.xAxis.pos,anchorY:b.isHeader?a.pos+d.plotTop-15:b.plotY+c.yAxis.pos})})},updatePosition:function(a){var c=this.chart,e=this.getLabel(),k=(this.options.positioner||this.getPosition).call(this,e.width,e.height,a),d=a.plotX+c.plotLeft;a=a.plotY+c.plotTop;var b;this.outside&&(b=(this.options.borderWidth||0)+2*this.distance,this.renderer.setSize(e.width+b,e.height+b,!1),d+=c.pointer.chartPosition.left-k.x,a+=c.pointer.chartPosition.top- k.y);this.move(Math.round(k.x),Math.round(k.y||0),d,a)},getDateFormat:function(a,f,h,k){var d=this.chart.time,b=d.dateFormat("%m-%d %H:%M:%S.%L",f),c,p,l={millisecond:15,second:12,minute:9,hour:6,day:3},t="millisecond";for(p in e){if(a===e.week&&+d.dateFormat("%w",f)===h&&"00:00:00.000"===b.substr(6)){p="week";break}if(e[p]>a){p=t;break}if(l[p]&&b.substr(l[p])!=="01-01 00:00:00.000".substr(l[p]))break;"week"!==p&&(t=p)}p&&(c=k[p]);return c},getXDateFormat:function(a,e,f){e=e.dateTimeLabelFormats; var c=f&&f.closestPointRange;return(c?this.getDateFormat(c,a.x,f.options.startOfWeek,e):e.day)||e.year},tooltipFooterHeaderFormatter:function(a,e){e=e?"footer":"header";var c=a.series,k=c.tooltipOptions,d=k.xDateFormat,b=c.xAxis,f=b&&"datetime"===b.options.type&&h(a.key),p=k[e+"Format"];f&&!d&&(d=this.getXDateFormat(a,k,b));f&&d&&D(a.point&&a.point.tooltipDateKeys||["key"],function(a){p=p.replace("{point."+a+"}","{point."+a+":"+d+"}")});return m(p,{point:a,series:c},this.chart.time)},bodyFormatter:function(a){return f(a, function(a){var c=a.series.tooltipOptions;return(c[(a.point.formatPrefix||"point")+"Formatter"]||a.point.tooltipFormatter).call(a.point,c[(a.point.formatPrefix||"point")+"Format"])})}}})(K);(function(a){var C=a.addEvent,D=a.attr,E=a.charts,m=a.color,h=a.css,f=a.defined,r=a.each,y=a.extend,q=a.find,w=a.fireEvent,e=a.isNumber,c=a.isObject,l=a.offset,z=a.pick,k=a.splat,d=a.Tooltip;a.Pointer=function(a,d){this.init(a,d)};a.Pointer.prototype={init:function(a,c){this.options=c;this.chart=a;this.runChartClick= c.chart.events&&!!c.chart.events.click;this.pinchDown=[];this.lastValidTouch={};d&&(a.tooltip=new d(a,c.tooltip),this.followTouchMove=z(c.tooltip.followTouchMove,!0));this.setDOMEvents()},zoomOption:function(a){var b=this.chart,d=b.options.chart,c=d.zoomType||"",b=b.inverted;/touch/.test(a.type)&&(c=z(d.pinchType,c));this.zoomX=a=/x/.test(c);this.zoomY=c=/y/.test(c);this.zoomHor=a&&!b||c&&b;this.zoomVert=c&&!b||a&&b;this.hasZoom=a||c},normalize:function(a,d){var b;b=a.touches?a.touches.length?a.touches.item(0): a.changedTouches[0]:a;d||(this.chartPosition=d=l(this.chart.container));return y(a,{chartX:Math.round(b.pageX-d.left),chartY:Math.round(b.pageY-d.top)})},getCoordinates:function(a){var b={xAxis:[],yAxis:[]};r(this.chart.axes,function(d){b[d.isXAxis?"xAxis":"yAxis"].push({axis:d,value:d.toValue(a[d.horiz?"chartX":"chartY"])})});return b},findNearestKDPoint:function(a,d,k){var b;r(a,function(a){var e=!(a.noSharedTooltip&&d)&&0>a.options.findNearestPointBy.indexOf("y");a=a.searchPoint(k,e);if((e=c(a, !0))&&!(e=!c(b,!0)))var e=b.distX-a.distX,f=b.dist-a.dist,p=(a.series.group&&a.series.group.zIndex)-(b.series.group&&b.series.group.zIndex),e=0<(0!==e&&d?e:0!==f?f:0!==p?p:b.series.index>a.series.index?-1:1);e&&(b=a)});return b},getPointFromEvent:function(a){a=a.target;for(var b;a&&!b;)b=a.point,a=a.parentNode;return b},getChartCoordinatesFromPoint:function(a,d){var b=a.series,c=b.xAxis,b=b.yAxis,k=z(a.clientX,a.plotX),e=a.shapeArgs;if(c&&b)return d?{chartX:c.len+c.pos-k,chartY:b.len+b.pos-a.plotY}: {chartX:k+c.pos,chartY:a.plotY+b.pos};if(e&&e.x&&e.y)return{chartX:e.x,chartY:e.y}},getHoverData:function(b,d,k,e,f,h,l){var p,n=[],u=l&&l.isBoosting;e=!(!e||!b);l=d&&!d.stickyTracking?[d]:a.grep(k,function(a){return a.visible&&!(!f&&a.directTouch)&&z(a.options.enableMouseTracking,!0)&&a.stickyTracking});d=(p=e?b:this.findNearestKDPoint(l,f,h))&&p.series;p&&(f&&!d.noSharedTooltip?(l=a.grep(k,function(a){return a.visible&&!(!f&&a.directTouch)&&z(a.options.enableMouseTracking,!0)&&!a.noSharedTooltip}), r(l,function(a){var b=q(a.points,function(a){return a.x===p.x&&!a.isNull});c(b)&&(u&&(b=a.getPoint(b)),n.push(b))})):n.push(p));return{hoverPoint:p,hoverSeries:d,hoverPoints:n}},runPointActions:function(b,d){var c=this.chart,k=c.tooltip&&c.tooltip.options.enabled?c.tooltip:void 0,e=k?k.shared:!1,f=d||c.hoverPoint,l=f&&f.series||c.hoverSeries,l=this.getHoverData(f,l,c.series,!!d||l&&l.directTouch&&this.isDirectTouch,e,b,{isBoosting:c.isBoosting}),u,f=l.hoverPoint;u=l.hoverPoints;l=l.hoverSeries;d= b&&"touchmove"===b.type?!0===this.followTouchMove:l&&l.tooltipOptions.followPointer;e=e&&l&&!l.noSharedTooltip;if(f&&(f!==c.hoverPoint||k&&k.isHidden)){r(c.hoverPoints||[],function(b){-1===a.inArray(b,u)&&b.setState()});r(u||[],function(a){a.setState("hover")});if(c.hoverSeries!==l)l.onMouseOver();c.hoverPoint&&c.hoverPoint.firePointEvent("mouseOut");if(!f.series)return;f.firePointEvent("mouseOver");c.hoverPoints=u;c.hoverPoint=f;k&&k.refresh(e?u:f,b)}else d&&k&&!k.isHidden&&(f=k.getAnchor([{}],b), k.updatePosition({plotX:f[0],plotY:f[1]}));this.unDocMouseMove||(this.unDocMouseMove=C(c.container.ownerDocument,"mousemove",function(b){var d=E[a.hoverChartIndex];if(d)d.pointer.onDocumentMouseMove(b)}));r(c.axes,function(d){var c=z(d.crosshair.snap,!0),k=c?a.find(u,function(a){return a.series[d.coll]===d}):void 0;k||!c?d.drawCrosshair(b,k):d.hideCrosshair()})},reset:function(a,d){var b=this.chart,c=b.hoverSeries,e=b.hoverPoint,f=b.hoverPoints,l=b.tooltip,u=l&&l.shared?f:e;a&&u&&r(k(u),function(b){b.series.isCartesian&& void 0===b.plotX&&(a=!1)});if(a)l&&u&&(l.refresh(u),l.shared&&f?r(f,function(a){a.setState(a.state,!0);a.series.xAxis.crosshair&&a.series.xAxis.drawCrosshair(null,a);a.series.yAxis.crosshair&&a.series.yAxis.drawCrosshair(null,a)}):e&&(e.setState(e.state,!0),r(b.axes,function(a){a.crosshair&&a.drawCrosshair(null,e)})));else{if(e)e.onMouseOut();f&&r(f,function(a){a.setState()});if(c)c.onMouseOut();l&&l.hide(d);this.unDocMouseMove&&(this.unDocMouseMove=this.unDocMouseMove());r(b.axes,function(a){a.hideCrosshair()}); this.hoverX=b.hoverPoints=b.hoverPoint=null}},scaleGroups:function(a,d){var b=this.chart,c;r(b.series,function(k){c=a||k.getPlotBox();k.xAxis&&k.xAxis.zoomEnabled&&k.group&&(k.group.attr(c),k.markerGroup&&(k.markerGroup.attr(c),k.markerGroup.clip(d?b.clipRect:null)),k.dataLabelsGroup&&k.dataLabelsGroup.attr(c))});b.clipRect.attr(d||b.clipBox)},dragStart:function(a){var b=this.chart;b.mouseIsDown=a.type;b.cancelClick=!1;b.mouseDownX=this.mouseDownX=a.chartX;b.mouseDownY=this.mouseDownY=a.chartY},drag:function(a){var b= this.chart,d=b.options.chart,c=a.chartX,k=a.chartY,e=this.zoomHor,f=this.zoomVert,l=b.plotLeft,n=b.plotTop,h=b.plotWidth,B=b.plotHeight,z,F=this.selectionMarker,g=this.mouseDownX,v=this.mouseDownY,q=d.panKey&&a[d.panKey+"Key"];F&&F.touch||(cl+h&&(c=l+h),kn+B&&(k=n+B),this.hasDragged=Math.sqrt(Math.pow(g-c,2)+Math.pow(v-k,2)),10n.max&&(f=n.max-t,v=!0);v?(M-=.8*(M-l[d][0]),G||(g-=.8*(g-l[d][1])),h()):l[d]= [M,g];y||(c[d]=r-q,c[p]=t);c=y?1/x:x;e[p]=t;e[d]=f;m[y?a?"scaleY":"scaleX":"scale"+b]=x;m["translate"+b]=c*q+(M-c*B)},pinch:function(a){var r=this,q=r.chart,w=r.pinchDown,e=a.touches,c=e.length,l=r.lastValidTouch,z=r.hasZoom,k=r.selectionMarker,d={},b=1===c&&(r.inClass(a.target,"highcharts-tracker")&&q.runTrackerClick||r.runChartClick),u={};1c-6&&fz?this.maxItemWidth:a.itemWidth;e&&this.itemX-b+c>z&&(this.itemX=b,this.itemY+=l+this.lastLineHeight+f,this.lastLineHeight=0);this.lastItemY=l+this.itemY+f;this.lastLineHeight=Math.max(k,this.lastLineHeight);a._legendItemPos=[this.itemX,this.itemY];e?this.itemX+=c:(this.itemY+=l+k+f,this.lastLineHeight=k);this.offsetWidth=x||Math.max((e?this.itemX-b-(a.checkbox?0:h):c)+b,this.offsetWidth)},getAllItems:function(){var a=[];h(this.chart.series,function(c){var b= c&&c.options;c&&w(b.showInLegend,m(b.linkedTo)?!1:void 0,!0)&&(a=a.concat(c.legendItems||("point"===b.legendType?c.data:c)))});f(this,"afterGetAllItems",{allItems:a});return a},getAlignment:function(){var a=this.options;return this.proximate?a.align.charAt(0)+"tv":a.floating?"":a.align.charAt(0)+a.verticalAlign.charAt(0)+a.layout.charAt(0)},adjustMargins:function(a,c){var b=this.chart,d=this.options,e=this.getAlignment();e&&h([/(lth|ct|rth)/,/(rtv|rm|rbv)/,/(rbh|cb|lbh)/,/(lbv|lm|ltv)/],function(k, f){k.test(e)&&!m(a[f])&&(b[y[f]]=Math.max(b[y[f]],b.legend[(f+1)%2?"legendHeight":"legendWidth"]+[1,-1,-1,1][f]*d[f%2?"x":"y"]+w(d.margin,12)+c[f]+(0===f&&void 0!==b.options.title.margin?b.titleOffset+b.options.title.margin:0)))})},proximatePositions:function(){var c=this.chart,d=[],b="left"===this.options.align;h(this.allItems,function(e){var k,f;k=b;e.xAxis&&e.points&&(e.xAxis.options.reversed&&(k=!k),k=a.find(k?e.points:e.points.slice(0).reverse(),function(b){return a.isNumber(b.plotY)}),f=e.legendGroup.getBBox().height, d.push({target:e.visible?(k?k.plotY:e.xAxis.height)-.3*f:c.plotHeight,size:f,item:e}))},this);a.distribute(d,c.plotHeight);h(d,function(a){a.item._legendItemPos[1]=c.plotTop-c.spacing[0]+a.pos})},render:function(){var a=this.chart,d=a.renderer,b=this.group,e,f,l,t=this.box,z=this.options,x=this.padding;this.itemX=x;this.itemY=this.initialItemY;this.lastItemY=this.offsetWidth=0;b||(this.group=b=d.g("legend").attr({zIndex:7}).add(),this.contentGroup=d.g().attr({zIndex:1}).add(b),this.scrollGroup=d.g().add(this.contentGroup)); this.renderTitle();e=this.getAllItems();c(e,function(a,b){return(a.options&&a.options.legendIndex||0)-(b.options&&b.options.legendIndex||0)});z.reversed&&e.reverse();this.allItems=e;this.display=f=!!e.length;this.itemHeight=this.totalItemWidth=this.maxItemWidth=this.lastLineHeight=0;h(e,this.renderItem,this);h(e,this.layoutItem,this);e=(z.width||this.offsetWidth)+x;l=this.lastItemY+this.lastLineHeight+this.titleHeight;l=this.handleOverflow(l);l+=x;t||(this.box=t=d.rect().addClass("highcharts-legend-box").attr({r:z.borderRadius}).add(b), t.isNew=!0);t.attr({stroke:z.borderColor,"stroke-width":z.borderWidth||0,fill:z.backgroundColor||"none"}).shadow(z.shadow);0b&&!1!==m.enabled?(this.clipHeight=z=Math.max(b-20-this.titleHeight-l,0),this.currentPage=w(this.currentPage,1),this.fullHeight=a,h(g,function(a,b){var c=a._legendItemPos[1],d=Math.round(a.legendItem.getBBox().height),e=q.length;if(!e||c-q[e-1]>z&&(F||c)!==q[e-1])q.push(F||c),e++;a.pageIx=e-1;F&&(g[b-1].pageIx=e-1);b===g.length-1&&c+d-q[e-1]>z&&(q.push(c),a.pageIx=e);c!==F&&(F=c)}),x||(x=c.clipRect= e.clipRect(0,l,9999,0),c.contentGroup.clip(x)),v(z),B||(this.nav=B=e.g().attr({zIndex:1}).add(this.group),this.up=e.symbol("triangle",0,0,G,G).on("click",function(){c.scroll(-1,n)}).add(B),this.pager=e.text("",15,10).addClass("highcharts-legend-navigation").css(m.style).add(B),this.down=e.symbol("triangle-down",0,0,G,G).on("click",function(){c.scroll(1,n)}).add(B)),c.scroll(0),a=b):B&&(v(),this.nav=B.destroy(),this.scrollGroup.attr({translateY:1}),this.clipHeight=0);return a},scroll:function(a,c){var b= this.pages,d=b.length;a=this.currentPage+a;var k=this.clipHeight,f=this.options.navigation,l=this.pager,h=this.padding;a>d&&(a=d);0d&&(f=typeof e[0],"string"===f?c.name=e[0]:"number"===f&&(c.x=e[0]),b++);u=h.value;)h=c[++f];this.nonZonedColor||(this.nonZonedColor=this.color);this.color=h&&h.color&&!this.options.color?h.color:this.nonZonedColor;return h},destroy:function(){var a=this.series.chart,c=a.hoverPoints,f;a.pointCount--; c&&(this.setState(),m(c,this),c.length||(a.hoverPoints=null));if(this===a.hoverPoint)this.onMouseOut();if(this.graphic||this.dataLabel)w(this),this.destroyElements();this.legendItem&&a.legend.destroyItem(this);for(f in this)this[f]=null},destroyElements:function(){for(var a=["graphic","dataLabel","dataLabelUpper","connector","shadowGroup"],c,f=6;f--;)c=a[f],this[c]&&(this[c]=this[c].destroy())},getLabelConfig:function(){return{x:this.category,y:this.y,color:this.color,colorIndex:this.colorIndex,key:this.name|| this.category,series:this.series,point:this,percentage:this.percentage,total:this.total||this.stackTotal}},tooltipFormatter:function(a){var c=this.series,e=c.tooltipOptions,h=q(e.valueDecimals,""),k=e.valuePrefix||"",d=e.valueSuffix||"";D(c.pointArrayMap||["y"],function(b){b="{point."+b;if(k||d)a=a.replace(RegExp(b+"}","g"),k+b+"}"+d);a=a.replace(RegExp(b+"}","g"),b+":,."+h+"f}")});return f(a,{point:this,series:this.series},c.chart.time)},firePointEvent:function(a,c,f){var e=this,k=this.series.options; (k.point.events[a]||e.options&&e.options.events&&e.options.events[a])&&this.importEvents();"click"===a&&k.allowPointSelect&&(f=function(a){e.select&&e.select(null,a.ctrlKey||a.metaKey||a.shiftKey)});h(this,a,c,f)},visible:!0}})(K);(function(a){var C=a.addEvent,D=a.animObject,E=a.arrayMax,m=a.arrayMin,h=a.correctFloat,f=a.defaultOptions,r=a.defaultPlotOptions,y=a.defined,q=a.each,w=a.erase,e=a.extend,c=a.fireEvent,l=a.grep,z=a.isArray,k=a.isNumber,d=a.isString,b=a.merge,u=a.objectEach,p=a.pick,H=a.removeEvent, t=a.splat,L=a.SVGElement,x=a.syncTimeout,I=a.win;a.Series=a.seriesType("line",null,{lineWidth:2,allowPointSelect:!1,showCheckbox:!1,animation:{duration:1E3},events:{},marker:{lineWidth:0,lineColor:"#ffffff",enabledThreshold:2,radius:4,states:{normal:{animation:!0},hover:{animation:{duration:50},enabled:!0,radiusPlus:2,lineWidthPlus:1},select:{fillColor:"#cccccc",lineColor:"#000000",lineWidth:2}}},point:{events:{}},dataLabels:{align:"center",formatter:function(){return null===this.y?"":a.numberFormat(this.y, -1)},style:{fontSize:"11px",fontWeight:"bold",color:"contrast",textOutline:"1px contrast"},verticalAlign:"bottom",x:0,y:0,padding:5},cropThreshold:300,pointRange:0,softThreshold:!0,states:{normal:{animation:!0},hover:{animation:{duration:50},lineWidthPlus:1,marker:{},halo:{size:10,opacity:.25}},select:{}},stickyTracking:!0,turboThreshold:1E3,findNearestPointBy:"x"},{isCartesian:!0,pointClass:a.Point,sorted:!0,requireSorting:!0,directTouch:!1,axisTypes:["xAxis","yAxis"],colorCounter:0,parallelArrays:["x", "y"],coll:"series",init:function(a,b){var d=this,n,f=a.series,g;d.chart=a;d.options=b=d.setOptions(b);d.linkedSeries=[];d.bindAxes();e(d,{name:b.name,state:"",visible:!1!==b.visible,selected:!0===b.selected});n=b.events;u(n,function(a,b){C(d,b,a)});if(n&&n.click||b.point&&b.point.events&&b.point.events.click||b.allowPointSelect)a.runTrackerClick=!0;d.getColor();d.getSymbol();q(d.parallelArrays,function(a){d[a+"Data"]=[]});d.setData(b.data,!1);d.isCartesian&&(a.hasCartesianSeries=!0);f.length&&(g= f[f.length-1]);d._i=p(g&&g._i,-1)+1;a.orderSeries(this.insert(f));c(this,"afterInit")},insert:function(a){var b=this.options.index,c;if(k(b)){for(c=a.length;c--;)if(b>=p(a[c].options.index,a[c]._i)){a.splice(c+1,0,this);break}-1===c&&a.unshift(this);c+=1}else a.push(this);return p(c,a.length-1)},bindAxes:function(){var b=this,c=b.options,d=b.chart,e;q(b.axisTypes||[],function(f){q(d[f],function(a){e=a.options;if(c[f]===e.index||void 0!==c[f]&&c[f]===e.id||void 0===c[f]&&0===e.index)b.insert(a.series), b[f]=a,a.isDirty=!0});b[f]||b.optionalAxis===f||a.error(18,!0)})},updateParallelArrays:function(a,b){var c=a.series,d=arguments,e=k(b)?function(d){var g="y"===d&&c.toYData?c.toYData(a):a[d];c[d+"Data"][b]=g}:function(a){Array.prototype[b].apply(c[a+"Data"],Array.prototype.slice.call(d,2))};q(c.parallelArrays,e)},autoIncrement:function(){var a=this.options,b=this.xIncrement,c,d=a.pointIntervalUnit,e=this.chart.time,b=p(b,a.pointStart,0);this.pointInterval=c=p(this.pointInterval,a.pointInterval,1); d&&(a=new e.Date(b),"day"===d?e.set("Date",a,e.get("Date",a)+c):"month"===d?e.set("Month",a,e.get("Month",a)+c):"year"===d&&e.set("FullYear",a,e.get("FullYear",a)+c),c=a.getTime()-b);this.xIncrement=b+c;return b},setOptions:function(a){var d=this.chart,e=d.options,k=e.plotOptions,n=(d.userOptions||{}).plotOptions||{},g=k[this.type];this.userOptions=a;d=b(g,k.series,a);this.tooltipOptions=b(f.tooltip,f.plotOptions.series&&f.plotOptions.series.tooltip,f.plotOptions[this.type].tooltip,e.tooltip.userOptions, k.series&&k.series.tooltip,k[this.type].tooltip,a.tooltip);this.stickyTracking=p(a.stickyTracking,n[this.type]&&n[this.type].stickyTracking,n.series&&n.series.stickyTracking,this.tooltipOptions.shared&&!this.noSharedTooltip?!0:d.stickyTracking);null===g.marker&&delete d.marker;this.zoneAxis=d.zoneAxis;a=this.zones=(d.zones||[]).slice();!d.negativeColor&&!d.negativeFillColor||d.zones||a.push({value:d[this.zoneAxis+"Threshold"]||d.threshold||0,className:"highcharts-negative",color:d.negativeColor,fillColor:d.negativeFillColor}); a.length&&y(a[a.length-1].value)&&a.push({color:this.color,fillColor:this.fillColor});c(this,"afterSetOptions",{options:d});return d},getName:function(){return this.name||"Series "+(this.index+1)},getCyclic:function(a,b,c){var d,e=this.chart,g=this.userOptions,f=a+"Index",k=a+"Counter",n=c?c.length:p(e.options.chart[a+"Count"],e[a+"Count"]);b||(d=p(g[f],g["_"+f]),y(d)||(e.series.length||(e[k]=0),g["_"+f]=d=e[k]%n,e[k]+=1),c&&(b=c[d]));void 0!==d&&(this[f]=d);this[a]=b},getColor:function(){this.options.colorByPoint? this.options.color=null:this.getCyclic("color",this.options.color||r[this.type].color,this.chart.options.colors)},getSymbol:function(){this.getCyclic("symbol",this.options.marker.symbol,this.chart.options.symbols)},drawLegendSymbol:a.LegendSymbolMixin.drawLineMarker,updateData:function(b){var c=this.options,d=this.points,e=[],f,g,n,h=this.requireSorting;q(b,function(b){var g;g=a.defined(b)&&this.pointClass.prototype.optionsToObject.call({series:this},b).x;k(g)&&(g=a.inArray(g,this.xData,n),-1===g? e.push(b):b!==c.data[g]?(d[g].update(b,!1,null,!1),d[g].touched=!0,h&&(n=g)):d[g]&&(d[g].touched=!0),f=!0)},this);if(f)for(b=d.length;b--;)g=d[b],g.touched||g.remove(!1),g.touched=!1;else if(b.length===d.length)q(b,function(a,b){d[b].update&&a!==c.data[b]&&d[b].update(a,!1,null,!1)});else return!1;q(e,function(a){this.addPoint(a,!1)},this);return!0},setData:function(b,c,e,f){var n=this,g=n.points,h=g&&g.length||0,l,B=n.options,G=n.chart,t=null,x=n.xAxis,u=B.turboThreshold,m=this.xData,r=this.yData, w=(l=n.pointArrayMap)&&l.length,y;b=b||[];l=b.length;c=p(c,!0);!1!==f&&l&&h&&!n.cropped&&!n.hasGroupedData&&n.visible&&!n.isSeriesBoosting&&(y=this.updateData(b));if(!y){n.xIncrement=null;n.colorCounter=0;q(this.parallelArrays,function(a){n[a+"Data"].length=0});if(u&&l>u){for(e=0;null===t&&eh||this.forceCrop)&&(c[e-1]z?(c=[],d=[]):this.yData&&(c[0]z)&&(f=this.cropData(this.xData,this.yData,m,z),c=f.xData,d=f.yData,f=f.start,g=!0));for(h=c.length||1;--h;)e=x?l(c[h])-l(c[h-1]):c[h]-c[h-1],0e&&u&&(a.error(15),u=!1);this.cropped=g;this.cropStart=f;this.processedXData=c;this.processedYData=d;this.closestPointRange=k},cropData:function(a,b,c,d,e){var g=a.length,f=0,k=g,n;e=p(e,this.cropShoulder,1);for(n=0;n=c){f=Math.max(0,n-e);break}for(c=n;cd){k=c+e;break}return{xData:a.slice(f,k),yData:b.slice(f,k),start:f,end:k}},generatePoints:function(){var a=this.options,b=a.data,c=this.data,d,e=this.processedXData,g=this.processedYData,f=this.pointClass, k=e.length,h=this.cropStart||0,l,p=this.hasGroupedData,a=a.keys,x,u=[],m;c||p||(c=[],c.length=b.length,c=this.data=c);a&&p&&(this.options.keys=!1);for(m=0;m=f&&(c[x-p]||l)<=n,h&&l)if(h=t.length)for(;h--;)"number"===typeof t[h]&&(e[g++]=t[h]);else e[g++]=t;this.dataMin=m(e);this.dataMax=E(e)},translate:function(){this.processedXData|| this.processData();this.generatePoints();var a=this.options,b=a.stacking,d=this.xAxis,e=d.categories,f=this.yAxis,g=this.points,l=g.length,t=!!this.modifyValue,x=a.pointPlacement,m="between"===x||k(x),u=a.threshold,z=a.startFromThreshold?u:0,q,r,w,I,H=Number.MAX_VALUE;"between"===x&&(x=.5);k(x)&&(x*=p(a.pointRange||d.pointRange));for(a=0;a=D&&(L.isNull=!0); L.plotX=q=h(Math.min(Math.max(-1E5,d.translate(C,0,0,0,1,x,"flags"===this.type)),1E5));b&&this.visible&&!L.isNull&&E&&E[C]&&(I=this.getStackIndicator(I,C,this.index),K=E[C],D=K.points[I.key],r=D[0],D=D[1],r===z&&I.key===E[C].base&&(r=p(k(u)&&u,f.min)),f.positiveValuesOnly&&0>=r&&(r=null),L.total=L.stackTotal=K.total,L.percentage=K.total&&L.y/K.total*100,L.stackY=D,K.setOffset(this.pointXOffset||0,this.barW||0));L.yBottom=y(r)?Math.min(Math.max(-1E5,f.translate(r,0,1,0,1)),1E5):null;t&&(D=this.modifyValue(D, L));L.plotY=r="number"===typeof D&&Infinity!==D?Math.min(Math.max(-1E5,f.translate(D,0,1,0,1)),1E5):void 0;L.isInside=void 0!==r&&0<=r&&r<=f.len&&0<=q&&q<=d.len;L.clientX=m?h(d.translate(C,0,0,0,1,x)):q;L.negative=L.y<(u||0);L.category=e&&void 0!==e[L.x]?e[L.x]:L.x;L.isNull||(void 0!==w&&(H=Math.min(H,Math.abs(q-w))),w=q);L.zone=this.zones.length&&L.getZone()}this.closestPointRangePx=H;c(this,"afterTranslate")},getValidPoints:function(a,b){var c=this.chart;return l(a||this.points||[],function(a){return b&& !c.isInsidePlot(a.plotX,a.plotY,c.inverted)?!1:!a.isNull})},setClip:function(a){var b=this.chart,c=this.options,d=b.renderer,e=b.inverted,g=this.clipBox,f=g||b.clipBox,k=this.sharedClipKey||["_sharedClip",a&&a.duration,a&&a.easing,f.height,c.xAxis,c.yAxis].join(),n=b[k],h=b[k+"m"];n||(a&&(f.width=0,e&&(f.x=b.plotSizeX),b[k+"m"]=h=d.clipRect(e?b.plotSizeX+99:-99,e?-b.plotLeft:-b.plotTop,99,e?b.chartWidth:b.chartHeight)),b[k]=n=d.clipRect(f),n.count={length:0});a&&!n.count[this.index]&&(n.count[this.index]= !0,n.count.length+=1);!1!==c.clip&&(this.group.clip(a||g?n:b.clipRect),this.markerGroup.clip(h),this.sharedClipKey=k);a||(n.count[this.index]&&(delete n.count[this.index],--n.count.length),0===n.count.length&&k&&b[k]&&(g||(b[k]=b[k].destroy()),b[k+"m"]&&(b[k+"m"]=b[k+"m"].destroy())))},animate:function(a){var b=this.chart,c=D(this.options.animation),d;a?this.setClip(c):(d=this.sharedClipKey,(a=b[d])&&a.animate({width:b.plotSizeX,x:0},c),b[d+"m"]&&b[d+"m"].animate({width:b.plotSizeX+99,x:0},c),this.animate= null)},afterAnimate:function(){this.setClip();c(this,"afterAnimate");this.finishedAnimating=!0},drawPoints:function(){var a=this.points,b=this.chart,c,d,e,g,f=this.options.marker,k,h,l,t=this[this.specialGroup]||this.markerGroup,x,m=p(f.enabled,this.xAxis.isRadial?!0:null,this.closestPointRangePx>=f.enabledThreshold*f.radius);if(!1!==f.enabled||this._hasPointMarkers)for(c=0;ce&&b.shadow));f&&(f.startX=c.xMap,f.isArea=c.isArea)})},getZonesGraphs:function(a){q(this.zones,function(b, c){a.push(["zone-graph-"+c,"highcharts-graph highcharts-zone-graph-"+c+" "+(b.className||""),b.color||this.color,b.dashStyle||this.options.dashStyle])},this);return a},applyZones:function(){var a=this,b=this.chart,c=b.renderer,d=this.zones,e,g,f=this.clips||[],k,h=this.graph,l=this.area,t=Math.max(b.chartWidth,b.chartHeight),x=this[(this.zoneAxis||"y")+"Axis"],m,u,z=b.inverted,r,w,y,I,H=!1;d.length&&(h||l)&&x&&void 0!==x.min&&(u=x.reversed,r=x.horiz,h&&!this.showLine&&h.hide(),l&&l.hide(),m=x.getExtremes(), q(d,function(d,n){e=u?r?b.plotWidth:0:r?0:x.toPixels(m.min);e=Math.min(Math.max(p(g,e),0),t);g=Math.min(Math.max(Math.round(x.toPixels(p(d.value,m.max),!0)),0),t);H&&(e=g=x.toPixels(m.max));w=Math.abs(e-g);y=Math.min(e,g);I=Math.max(e,g);x.isXAxis?(k={x:z?I:y,y:0,width:w,height:t},r||(k.x=b.plotHeight-k.x)):(k={x:0,y:z?I:y,width:t,height:w},r&&(k.y=b.plotWidth-k.y));z&&c.isVML&&(k=x.isXAxis?{x:0,y:u?y:I,height:k.width,width:b.chartWidth}:{x:k.y-b.plotLeft-b.spacingBox.x,y:0,width:k.height,height:b.chartHeight}); f[n]?f[n].animate(k):(f[n]=c.clipRect(k),h&&a["zone-graph-"+n].clip(f[n]),l&&a["zone-area-"+n].clip(f[n]));H=d.value>m.max;a.resetZones&&0===g&&(g=void 0)}),this.clips=f)},invertGroups:function(a){function b(){q(["group","markerGroup"],function(b){c[b]&&(d.renderer.isVML&&c[b].attr({width:c.yAxis.len,height:c.xAxis.len}),c[b].width=c.yAxis.len,c[b].height=c.xAxis.len,c[b].invert(a))})}var c=this,d=c.chart,e;c.xAxis&&(e=C(d,"resize",b),C(c,"destroy",e),b(a),c.invertGroups=b)},plotGroup:function(a, b,c,d,e){var g=this[a],f=!g;f&&(this[a]=g=this.chart.renderer.g().attr({zIndex:d||.1}).add(e));g.addClass("highcharts-"+b+" highcharts-series-"+this.index+" highcharts-"+this.type+"-series "+(y(this.colorIndex)?"highcharts-color-"+this.colorIndex+" ":"")+(this.options.className||"")+(g.hasClass("highcharts-tracker")?" highcharts-tracker":""),!0);g.attr({visibility:c})[f?"attr":"animate"](this.getPlotBox());return g},getPlotBox:function(){var a=this.chart,b=this.xAxis,c=this.yAxis;a.inverted&&(b=c, c=this.xAxis);return{translateX:b?b.left:a.plotLeft,translateY:c?c.top:a.plotTop,scaleX:1,scaleY:1}},render:function(){var a=this,b=a.chart,d,e=a.options,f=!!a.animate&&b.renderer.isSVG&&D(e.animation).duration,g=a.visible?"inherit":"hidden",k=e.zIndex,h=a.hasRendered,l=b.seriesGroup,p=b.inverted;d=a.plotGroup("group","series",g,k,l);a.markerGroup=a.plotGroup("markerGroup","markers",g,k,l);f&&a.animate(!0);d.inverted=a.isCartesian?p:!1;a.drawGraph&&(a.drawGraph(),a.applyZones());a.drawDataLabels&& a.drawDataLabels();a.visible&&a.drawPoints();a.drawTracker&&!1!==a.options.enableMouseTracking&&a.drawTracker();a.invertGroups(p);!1===e.clip||a.sharedClipKey||h||d.clip(b.clipRect);f&&a.animate();h||(a.animationTimeout=x(function(){a.afterAnimate()},f));a.isDirty=!1;a.hasRendered=!0;c(a,"afterRender")},redraw:function(){var a=this.chart,b=this.isDirty||this.isDirtyData,c=this.group,d=this.xAxis,e=this.yAxis;c&&(a.inverted&&c.attr({width:a.plotWidth,height:a.plotHeight}),c.animate({translateX:p(d&& d.left,a.plotLeft),translateY:p(e&&e.top,a.plotTop)}));this.translate();this.render();b&&delete this.kdTree},kdAxisArray:["clientX","plotY"],searchPoint:function(a,b){var c=this.xAxis,d=this.yAxis,e=this.chart.inverted;return this.searchKDTree({clientX:e?c.len-a.chartY+c.pos:a.chartX-c.pos,plotY:e?d.len-a.chartX+d.pos:a.chartY-d.pos},b)},buildKDTree:function(){function a(c,d,e){var g,f;if(f=c&&c.length)return g=b.kdAxisArray[d%e],c.sort(function(a,b){return a[g]-b[g]}),f=Math.floor(f/2),{point:c[f], left:a(c.slice(0,f),d+1,e),right:a(c.slice(f+1),d+1,e)}}this.buildingKdTree=!0;var b=this,c=-1n?"left":"right";t=0>n?"right":"left";b[p]&&(p=c(a,b[p],k+1,h),x=p[f]m;)x--;this.updateParallelArrays(l,"splice",x,0,0);this.updateParallelArrays(l,x);g&&l.name&&(g[m]=l.name);n.splice(x,0,a);p&&(this.data.splice(x,0,null),this.processData());"point"===f.legendType&&this.generatePoints(); d&&(k[0]&&k[0].remove?k[0].remove(!1):(k.shift(),this.updateParallelArrays(l,"shift"),n.shift()));this.isDirtyData=this.isDirty=!0;c&&h.redraw(e)},removePoint:function(a,c,d){var e=this,f=e.data,k=f[a],h=e.points,g=e.chart,n=function(){h&&h.length===f.length&&h.splice(a,1);f.splice(a,1);e.options.data.splice(a,1);e.updateParallelArrays(k||{series:e},"splice",a,1);k&&k.destroy();e.isDirty=!0;e.isDirtyData=!0;c&&g.redraw()};t(d,g);c=b(c,!0);k?k.firePointEvent("remove",null,n):n()},remove:function(a, c,d){function e(){f.destroy();k.isDirtyLegend=k.isDirtyBox=!0;k.linkSeries();b(a,!0)&&k.redraw(c)}var f=this,k=f.chart;!1!==d?w(f,"remove",null,e):e()},update:function(c,d){var f=this,h=f.chart,l=f.userOptions,p=f.oldType||f.type,t=c.type||l.type||h.options.chart.type,g=H[p].prototype,x,m=["group","markerGroup","dataLabelsGroup"],u=["navigatorSeries","baseSeries"],z=f.finishedAnimating&&{animation:!1},y=["data","name","turboThreshold"],I=a.keys(c),A=0a&&q>f?(q=Math.max(a,f),e=2*f-q):qm&&e>f?(e=Math.max(m,f),q=2*f-e):e=Math.abs(c)&&.5a.closestPointRange*a.xAxis.transA,h=a.borderWidth=r(f.borderWidth,h?0:1),k=a.yAxis,d=f.threshold,b=a.translatedThreshold=k.getThreshold(d),m=r(f.minPointLength,5),p=a.getColumnMetrics(),q=p.width,t=a.barW=Math.max(q,1+2*h),w=a.pointXOffset=p.offset;c.inverted&&(b-=.5);f.pointPadding&& (t=Math.ceil(t));y.prototype.translate.apply(a);E(a.points,function(e){var f=r(e.yBottom,b),h=999+Math.abs(f),h=Math.min(Math.max(-h,e.plotY),k.len+h),l=e.plotX+w,p=t,u=Math.min(h,f),x,g=Math.max(h,f)-u;m&&Math.abs(g)m?f-m:b-(x?m:0));e.barX=l;e.pointWidth=q;e.tooltipPos=c.inverted?[k.len+k.pos-c.plotLeft-h,a.xAxis.len-l-p/2,g]:[l+p/2,h+k.pos-c.plotTop,g];e.shapeType="rect";e.shapeArgs= a.crispCol.apply(a,e.isNull?[l,b,p,0]:[l,u,p,g])})},getSymbol:a.noop,drawLegendSymbol:a.LegendSymbolMixin.drawRectangle,drawGraph:function(){this.group[this.dense?"addClass":"removeClass"]("highcharts-dense-data")},pointAttribs:function(a,c){var e=this.options,h,k=this.pointAttrToOptions||{};h=k.stroke||"borderColor";var d=k["stroke-width"]||"borderWidth",b=a&&a.color||this.color,m=a&&a[h]||e[h]||this.color||b,p=a&&a[d]||e[d]||this[d]||0,k=e.dashStyle;a&&this.zones.length&&(b=a.getZone(),b=a.options.color|| b&&b.color||this.color);c&&(a=f(e.states[c],a.options.states&&a.options.states[c]||{}),c=a.brightness,b=a.color||void 0!==c&&D(b).brighten(a.brightness).get()||b,m=a[h]||m,p=a[d]||p,k=a.dashStyle||k);h={fill:b,stroke:m,"stroke-width":p};k&&(h.dashstyle=k);return h},drawPoints:function(){var a=this,c=this.chart,l=a.options,m=c.renderer,k=l.animationLimit||250,d;E(a.points,function(b){var e=b.graphic,p=e&&c.pointCounte;++e)c=q[e],a=2>e||2===e&&/%$/.test(c),q[e]=m(c,[y,f,w,q[2]][e])+(a?r:0);q[3]>q[2]&&(q[3]=q[2]);return q},getStartAndEndRadians:function(a,f){a=D(a)?a:0;f=D(f)&&f>a&&360>f-a?f:a+360;return{start:C*(a+-90),end:C*(f+-90)}}}})(K);(function(a){var C=a.addEvent,D=a.CenteredSeriesMixin,E=a.defined,m=a.each,h=a.extend,f=D.getStartAndEndRadians,r=a.inArray,y=a.noop,q=a.pick,w=a.Point, e=a.Series,c=a.seriesType,l=a.setAnimation;c("pie","line",{center:[null,null],clip:!1,colorByPoint:!0,dataLabels:{allowOverlap:!0,distance:30,enabled:!0,formatter:function(){return this.point.isNull?void 0:this.point.name},x:0},ignoreHiddenPoint:!0,legendType:"point",marker:null,size:null,showInLegend:!1,slicedOffset:10,stickyTracking:!1,tooltip:{followPointer:!0},borderColor:"#ffffff",borderWidth:1,states:{hover:{brightness:.1}}},{isCartesian:!1,requireSorting:!1,directTouch:!0,noSharedTooltip:!0, trackerGroups:["group","dataLabelsGroup"],axisTypes:[],pointAttribs:a.seriesTypes.column.prototype.pointAttribs,animate:function(a){var c=this,d=c.points,b=c.startAngleRad;a||(m(d,function(a){var d=a.graphic,f=a.shapeArgs;d&&(d.attr({r:a.startR||c.center[3]/2,start:b,end:b}),d.animate({r:f.r,start:f.start,end:f.end},c.options.animation))}),c.animate=null)},updateTotals:function(){var a,c=0,d=this.points,b=d.length,f,e=this.options.ignoreHiddenPoint;for(a=0;a1.5*Math.PI? t-=2*Math.PI:t<-Math.PI/2&&(t+=2*Math.PI);F.slicedTranslation={translateX:Math.round(Math.cos(t)*b),translateY:Math.round(Math.sin(t)*b)};l=Math.cos(t)*a[2]/2;n=Math.sin(t)*a[2]/2;F.tooltipPos=[a[0]+.7*l,a[1]+.7*n];F.half=t<-Math.PI/2||t>Math.PI/2?1:0;F.angle=t;h=Math.min(e,F.labelDistance/5);F.labelPos=[a[0]+l+Math.cos(t)*F.labelDistance,a[1]+n+Math.sin(t)*F.labelDistance,a[0]+l+Math.cos(t)*h,a[1]+n+Math.sin(t)*h,a[0]+l,a[1]+n,0>F.labelDistance?"center":F.half?"right":"left",t]}},drawGraph:null, drawPoints:function(){var a=this,c=a.chart.renderer,d,b,f,e,l=a.options.shadow;l&&!a.shadowGroup&&(a.shadowGroup=c.g("shadow").add(a.group));m(a.points,function(k){b=k.graphic;if(k.isNull)b&&(k.graphic=b.destroy());else{e=k.shapeArgs;d=k.getTranslate();var t=k.shadowGroup;l&&!t&&(t=k.shadowGroup=c.g("shadow").add(a.shadowGroup));t&&t.attr(d);f=a.pointAttribs(k,k.selected&&"select");b?b.setRadialReference(a.center).attr(f).animate(h(e,d)):(k.graphic=b=c[k.shapeType](e).setRadialReference(a.center).attr(d).add(a.group), b.attr(f).attr({"stroke-linejoin":"round"}).shadow(l,t));b.attr({visibility:k.visible?"inherit":"hidden"});b.addClass(k.getClassName())}})},searchPoint:y,sortByAngle:function(a,c){a.sort(function(a,b){return void 0!==a.angle&&(b.angle-a.angle)*c})},drawLegendSymbol:a.LegendSymbolMixin.drawRectangle,getCenter:D.getCenter,getSymbol:y},{init:function(){w.prototype.init.apply(this,arguments);var a=this,c;a.name=q(a.name,"Slice");c=function(c){a.slice("select"===c.type)};C(a,"select",c);C(a,"unselect", c);return a},isValid:function(){return a.isNumber(this.y,!0)&&0<=this.y},setVisible:function(a,c){var d=this,b=d.series,f=b.chart,e=b.options.ignoreHiddenPoint;c=q(c,e);a!==d.visible&&(d.visible=d.options.visible=a=void 0===a?!d.visible:a,b.options.data[r(d,b.data)]=d.options,m(["graphic","dataLabel","connector","shadowGroup"],function(b){if(d[b])d[b][a?"show":"hide"](!0)}),d.legendItem&&f.legend.colorizeItem(d,a),a||"hover"!==d.state||d.setState(""),e&&(b.isDirty=!0),c&&f.redraw())},slice:function(a, c,d){var b=this.series;l(d,b.chart);q(c,!0);this.sliced=this.options.sliced=E(a)?a:!this.sliced;b.options.data[r(this,b.data)]=this.options;this.graphic.animate(this.getTranslate());this.shadowGroup&&this.shadowGroup.animate(this.getTranslate())},getTranslate:function(){return this.sliced?this.slicedTranslation:{translateX:0,translateY:0}},haloPath:function(a){var c=this.shapeArgs;return this.sliced||!this.visible?[]:this.series.chart.renderer.symbols.arc(c.x,c.y,c.r+a,c.r+a,{innerR:this.shapeArgs.r- 1,start:c.start,end:c.end})}})})(K);(function(a){var C=a.addEvent,D=a.arrayMax,E=a.defined,m=a.each,h=a.extend,f=a.format,r=a.map,y=a.merge,q=a.noop,w=a.pick,e=a.relativeLength,c=a.Series,l=a.seriesTypes,z=a.some,k=a.stableSort;a.distribute=function(c,b,f){function d(a,b){return a.target-b.target}var e,h=!0,l=c,x=[],q;q=0;var n=l.reducedLen||b;for(e=c.length;e--;)q+=c[e].size;if(q>n){k(c,function(a,b){return(b.rank||0)-(a.rank||0)});for(q=e=0;q<=n;)q+=c[e].size,e++;x=c.splice(e-1,c.length)}k(c,d); for(c=r(c,function(a){return{size:a.size,targets:[a.target],align:w(a.align,.5)}});h;){for(e=c.length;e--;)h=c[e],q=(Math.min.apply(0,h.targets)+Math.max.apply(0,h.targets))/2,h.pos=Math.min(Math.max(0,q-h.size*h.align),b-h.size);e=c.length;for(h=!1;e--;)0c[e].pos&&(c[e-1].size+=c[e].size,c[e-1].targets=c[e-1].targets.concat(c[e].targets),c[e-1].align=.5,c[e-1].pos+c[e-1].size>b&&(c[e-1].pos=b-c[e-1].size),c.splice(e,1),h=!0)}l.push.apply(l,x);e=0;z(c,function(c){var d= 0;if(z(c.targets,function(){l[e].pos=c.pos+d;if(Math.abs(l[e].pos-l[e].target)>f)return m(l.slice(0,e+1),function(a){delete a.pos}),l.reducedLen=(l.reducedLen||b)-.1*b,l.reducedLen>.1*b&&a.distribute(l,b,f),!0;d+=l[e].size;e++}))return!0});k(l,d)};c.prototype.drawDataLabels=function(){function c(a,b){var c=b.filter;return c?(b=c.operator,a=a[c.property],c=c.value,"\x3e"===b&&a>c||"\x3c"===b&&a=c||"\x3c\x3d"===b&&a<=c||"\x3d\x3d"===b&&a==c||"\x3d\x3d\x3d"===b&&a===c?!0:!1):!0} var b=this,e=b.chart,k=b.options,h=k.dataLabels,l=b.points,q,x,r=b.hasRendered||0,n,z,B=w(h.defer,!!k.animation),D=e.renderer;if(h.enabled||b._hasPointLabels)b.dlProcessOptions&&b.dlProcessOptions(h),z=b.plotGroup("dataLabelsGroup","data-labels",B&&!r?"hidden":"visible",h.zIndex||6),B&&(z.attr({opacity:+r}),r||C(b,"afterAnimate",function(){b.visible&&z.show(!0);z[k.animation?"animate":"attr"]({opacity:1},{duration:200})})),x=h,m(l,function(d){var g,l=d.dataLabel,t,p,m=d.connector,u=!l,r;q=d.dlOptions|| d.options&&d.options.dataLabels;(g=w(q&&q.enabled,x.enabled)&&!d.isNull)&&(g=!0===c(d,q||h));g&&(h=y(x,q),t=d.getLabelConfig(),r=h[d.formatPrefix+"Format"]||h.format,n=E(r)?f(r,t,e.time):(h[d.formatPrefix+"Formatter"]||h.formatter).call(t,h),r=h.style,t=h.rotation,r.color=w(h.color,r.color,b.color,"#000000"),"contrast"===r.color&&(d.contrastColor=D.getContrast(d.color||b.color),r.color=h.inside||0>w(d.labelDistance,h.distance)||k.stacking?d.contrastColor:"#000000"),k.cursor&&(r.cursor=k.cursor),p= {fill:h.backgroundColor,stroke:h.borderColor,"stroke-width":h.borderWidth,r:h.borderRadius||0,rotation:t,padding:h.padding,zIndex:1},a.objectEach(p,function(a,b){void 0===a&&delete p[b]}));!l||g&&E(n)?g&&E(n)&&(l?p.text=n:(l=d.dataLabel=t?D.text(n,0,-9999,h.useHTML).addClass("highcharts-data-label"):D.label(n,0,-9999,h.shape,null,null,h.useHTML,null,"data-label"),l.addClass(" highcharts-data-label-color-"+d.colorIndex+" "+(h.className||"")+(h.useHTML?" highcharts-tracker":""))),l.attr(p),l.css(r).shadow(h.shadow), l.added||l.add(z),b.alignDataLabel(d,l,h,null,u)):(d.dataLabel=l=l.destroy(),m&&(d.connector=m.destroy()))});a.fireEvent(this,"afterDrawDataLabels")};c.prototype.alignDataLabel=function(a,b,c,e,f){var d=this.chart,k=d.inverted,l=w(a.dlBox&&a.dlBox.centerX,a.plotX,-9999),m=w(a.plotY,-9999),n=b.getBBox(),p,q=c.rotation,r=c.align,u=this.visible&&(a.series.forceDL||d.isInsidePlot(l,Math.round(m),k)||e&&d.isInsidePlot(l,k?e.x+1:e.y+e.height-1,k)),g="justify"===w(c.overflow,"justify");if(u&&(p=c.style.fontSize, p=d.renderer.fontMetrics(p,b).b,e=h({x:k?this.yAxis.len-m:l,y:Math.round(k?this.xAxis.len-l:m),width:0,height:0},e),h(c,{width:n.width,height:n.height}),q?(g=!1,l=d.renderer.rotCorr(p,q),l={x:e.x+c.x+e.width/2+l.x,y:e.y+c.y+{top:0,middle:.5,bottom:1}[c.verticalAlign]*e.height},b[f?"attr":"animate"](l).attr({align:r}),m=(q+720)%360,m=180m,"left"===r?l.y-=m?n.height:0:"center"===r?(l.x-=n.width/2,l.y-=n.height/2):"right"===r&&(l.x-=n.width,l.y-=m?0:n.height),b.placed=!0,b.alignAttr=l):(b.align(c, null,e),l=b.alignAttr),g&&0<=e.height?a.isLabelJustified=this.justifyDataLabel(b,c,l,n,e,f):w(c.crop,!0)&&(u=d.isInsidePlot(l.x,l.y)&&d.isInsidePlot(l.x+n.width,l.y+n.height)),c.shape&&!q))b[f?"attr":"animate"]({anchorX:k?d.plotWidth-a.plotY:a.plotX,anchorY:k?d.plotHeight-a.plotX:a.plotY});u||(b.attr({y:-9999}),b.placed=!1)};c.prototype.justifyDataLabel=function(a,b,c,e,f,k){var d=this.chart,h=b.align,l=b.verticalAlign,n,m,t=a.box?0:a.padding||0;n=c.x+t;0>n&&("right"===h?b.align="left":b.x=-n,m=!0); n=c.x+e.width-t;n>d.plotWidth&&("left"===h?b.align="right":b.x=d.plotWidth-n,m=!0);n=c.y+t;0>n&&("bottom"===l?b.verticalAlign="top":b.y=-n,m=!0);n=c.y+e.height-t;n>d.plotHeight&&("top"===l?b.verticalAlign="bottom":b.y=d.plotHeight-n,m=!0);m&&(a.placed=!k,a.align(b,null,f));return m};l.pie&&(l.pie.prototype.drawDataLabels=function(){var d=this,b=d.data,e,f=d.chart,k=d.options.dataLabels,h=w(k.connectorPadding,10),l=w(k.connectorWidth,1),q=f.plotWidth,r=f.plotHeight,n=Math.round(f.chartWidth/3),y,z= d.center,C=z[2]/2,F=z[1],g,v,K,Q,J=[[],[]],O,N,A,R,S=[0,0,0,0];d.visible&&(k.enabled||d._hasPointLabels)&&(m(b,function(a){a.dataLabel&&a.visible&&a.dataLabel.shortened&&(a.dataLabel.attr({width:"auto"}).css({width:"auto",textOverflow:"clip"}),a.dataLabel.shortened=!1)}),c.prototype.drawDataLabels.apply(d),m(b,function(a){a.dataLabel&&(a.visible?(J[a.half].push(a),a.dataLabel._pos=null,!E(k.style.width)&&!E(a.options.dataLabels&&a.options.dataLabels.style&&a.options.dataLabels.style.width)&&a.dataLabel.getBBox().width> n&&(a.dataLabel.css({width:.7*n}),a.dataLabel.shortened=!0)):a.dataLabel=a.dataLabel.destroy())}),m(J,function(b,c){var l,n,t=b.length,p=[],x;if(t)for(d.sortByAngle(b,c-.5),0e.bottom-2?l:N,c,e),g._attr={visibility:A,align:K[6]},g._pos={x:O+k.x+({left:h,right:-h}[K[6]]||0),y:N+k.y-10},K.x=O,K.y=N,w(k.crop, !0)&&(v=g.getBBox().width,l=null,O-vq-h&&0===c&&(l=Math.round(O+v-q+h),S[1]=Math.max(l,S[1])),0>N-Q/2?S[0]=Math.max(Math.round(-N+Q/2),S[0]):N+Q/2>r&&(S[2]=Math.max(Math.round(N+Q/2-r),S[2])),g.sideOverflow=l)}),0===D(S)||this.verifyDataLabelOverflow(S))&&(this.placeDataLabels(),l&&m(this.points,function(a){var b;y=a.connector;if((g=a.dataLabel)&&g._pos&&a.visible&&0w(this.translatedThreshold,h.yAxis.len)),n=w(e.inside,!!this.options.stacking);l&&(f=y(l),0>f.y&&(f.height+=f.y,f.y=0),l=f.y+f.height-h.yAxis.len,0a+b||f+lc+e||h+mthis.pointCount))}, pan:function(a,b){var c=this,d=c.hoverPoints,e;d&&r(d,function(a){a.setState()});r("xy"===b?[1,0]:[1],function(b){b=c[b?"xAxis":"yAxis"][0];var d=b.horiz,f=a[d?"chartX":"chartY"],d=d?"mouseDownX":"mouseDownY",h=c[d],g=(b.pointRange||0)/2,k=b.reversed&&!c.inverted||!b.reversed&&c.inverted?-1:1,l=b.getExtremes(),n=b.toValue(h-f,!0)+g*k,k=b.toValue(h+b.len-f,!0)-g*k,m=k=f(m.minWidth,0)&&this.chartHeight>= f(m.minHeight,0)}).call(this)&&h.push(a._id)};C.prototype.currentOptions=function(f){function q(e,c,f,w){var k;a.objectEach(e,function(a,b){if(!w&&-1 0) $('.customselector').customSelect(); $("a[rel^='prettyPhoto']").prettyPhoto(); $("a[rel^='prettyText']").prettyPhoto({ default_width: 400, default_height: 60 }); $("a[rel^='prettyAreatext']").prettyPhoto({ default_width: 400, default_height: 120 }); //$("a[href$='/login'], a[href*='/login?destination']").prettyPhoto({ // default_width: 400, // default_height: 200 //}); $(".menu-top").hover( function () { $(this).addClass("menu-top-hover"); }, function () { $(this).removeClass("menu-top-hover"); } ); $("#longdo-menu-link, #longdo-link-other-menu dt").hover( function () { $(this).addClass("hover"); }, function () { $(this).removeClass("hover"); } ) $("#longdo-link-other-menu dt").click(function() { window.open( $(this).children("a").attr('href') ); return false; }) .mouseover(function(){ $(this).children("a").addClass("hover"); }) .mouseout(function(){ $(this).children("a").removeClass("hover"); }); $("#tomtom-map-button").click(function(){ initTomtomMap(); initRoutingForm(); //window.open('/tomtom'); }); $("#numap-map-button").click(function(){ initNuMap(); initRoutingForm(); }); }); var searchtomtom; // move to front-page-jquery ? function isShowMap() { return (Drupal.settings && Drupal.settings.showmap); } function initNuMap() { Drupal.settings.mapdata = 'numap'; clearSerchFormValue(); clearSuggestDiv(); map_init(false, 'icons'); var search_txtbox = document.getElementById("searchfor"); var search_button = document.getElementById("bluesearch-button"); var clear_search_button = document.getElementById("searchclear"); var searchform = search_txtbox.form; if (search_txtbox) { search_txtbox.onkeyup = function() {}; search_txtbox.onkeydown = function() {}; search_txtbox.onfocus = function(e) { document.onkeydown='return true'; document.onkeypress='return true'; setSuggestDivPosition(search_txtbox, '_suggest_disp'); onkeyup=_suggest_load; onkeydown=function(e){suggest_navigation_keys_check(e, search_txtbox, '_suggest_disp');}; setTimeout(function(){document.getElementById('searchfor').select();},10);}; search_txtbox.onblur = function() {setKeyFocusAtMaparea();setTimeout('clearSuggestDiv()',500);}; } if (search_button) { search_button.onclick = function() {setBookmark(0, 'all');longdomapSearch('');setKeyFocusAtMaparea();}; } if (clear_search_button) { clear_search_button.onclick = function() {clearSerchFormValue();adjust_searchresult('true');}; } if (searchform) { searchform.onsubmit = function() { setBookmark(0, 'all');_suggest_entersearch=true;longdomapSearch('');return false; }; } $('#numap-map-button').addClass('map-data-button-active'); $('#tomtom-map-button').removeClass('map-data-button-active'); showAddLocationMode(); hideTomtomLogo(); $('body').removeClass('map-data-tomtom'); } function htmlEscape(str) { return String(str) .replace(/&/g, '&') .replace(/"/g, '"') .replace(/'/g, ''') .replace(//g, '>'); } function longdomapSearch(keyword) { if(keyword == "" && document.getElementById("searchfor")) { keyword = document.getElementById("searchfor").value; } if (typeof keyword.trim == 'function') { keyword = keyword.trim(); } if (getSelectedMapdata() == 'tomtom') { searchtomtom.searchPlace(keyword); } else { doSearch(keyword); } } function initTomtomMap() { if (!isShowMap()) { window.open('/tomtom'); return false; } Drupal.settings.mapdata = 'tomtom'; clearSerchFormValue(); clearSuggestDiv(); map_init(false, 'tomicons'); var searchform = document.getElementById("searchfor").form; if (searchform) { searchform.onsubmit = function() { return false; }; onkeydown = false; onkeyup = false; } searchtomtom = new longdo.SearchPOI(mmmap2, { search_id: 'search-tools', search_txtbox_id: 'searchfor', search_button_id: 'bluesearch-button', clear_button_id: 'searchclear', search_result_id: 'search-result', routing_result_id: 'routing-result', search_ds: 'toma,tomp,tomr,tomw,tomb', suggest_ds: 'toma_s,tomp_s,tomr_s,tomw_s,tomb_s'}); searchtomtom.setBasePath('/mmmap/tomtom/'); searchtomtom.searchPlaceByAjax = function(keyword, bookmark) { var center_location = searchtomtom.map.location(); var params = "?action=searchpoi"; params += "&keyword="+encodeURIComponent(keyword); params += "&lat="+center_location.lat; params += "&lon="+center_location.lon; params += "&ds="+searchtomtom.search_ds; if (typeof bookmark != "undefined") { params += "&bookmark="+bookmark; } if(typeof bookmark == 'undefined' || bookmark == 0) { searchtomtom.clearSearchMarker(); searchtomtom.setSearchResults('
    '); } searchtomtom.hideSuggestion(); searchtomtom.clearSuggestionTimeout(); params += "&callback=searchtomtom.showSearchResult"; searchtomtom.Ajax.externalLoad('/mmmap/tomtom/search/rpc.php'+params); adjust_searchresult(false, 0); } $('#numap-map-button').removeClass('map-data-button-active'); $('#tomtom-map-button').addClass('map-data-button-active'); hideAddLocationMode(); showTomtomLogo(); $('body').addClass('map-data-tomtom'); } function showLoginForm() { if($("#loginbar-login-button").length > 0) { $("#loginbar-login-button").click(); } else if($("#loginbar-login-button", top.parent.document).length > 0) { $("#loginbar-login-button", top.parent.document).click(); } } function loadjscssfile(filename, filetype){ if (filetype=="js"){ //if filename is a external JavaScript file var fileref=document.createElement('script') fileref.setAttribute("type","text/javascript") fileref.setAttribute("src", filename) } else if (filetype=="css"){ //if filename is an external CSS file var fileref=document.createElement("link") fileref.setAttribute("rel", "stylesheet") fileref.setAttribute("type", "text/css") fileref.setAttribute("href", filename) } if (typeof fileref!="undefined") document.getElementsByTagName("head")[0].appendChild(fileref); } var filesadded="" //list of files already added function checkloadjscssfile(filename, filetype){ if (filesadded.indexOf("["+filename+"]")==-1){ loadjscssfile(filename, filetype) filesadded+="["+filename+"]" //List of files added in the form "[filename1],[filename2],etc" } } $.fn.customSelect = function() { // define defaults and override with options, if available // by extending the default settings, we don't modify the argument return this.each(function() { var selected_obj = false; obj = $(this); obj.after("
    "); obj.find('option').each(function(i) { $("#selectoptions").append("
    " + $(this).html() + "
    "); if($(this).attr("value")==$('.customselector').val()) { selected_obj = "
    " + $(this).html() + "
    "; } }); if(selected_obj) { obj.before("
    " + selected_obj + "
    ").remove(); } else { obj.before("
    " + this.title + "
    ").remove(); } $("#iconselect .select-text").css( {width: $('#iconselect').width()-($('#iconselect img').width()+28)+"px"} ); $("#iconselectholder").append( $("#selectoptions")[0] ); $("#iconselect").click(function(){ $("#iconselectholder").css( { width: ($('#pre-customselect').width()+$('#iconselect').width()-2)+"px", left: "-"+($('#pre-customselect').width()+$('#iconselect').width())+"px", top: $('#iconselect').height()+15+"px" } ); $("#iconselectholder").toggle("fast"); }); $(".selectitems").mouseover(function(){ $(this).addClass("hoverclass"); }); $(".selectitems").mouseout(function(){ $(this).removeClass("hoverclass"); }); $(".selectitems").click(function(){ $(".selectedclass").removeClass("selectedclass"); $(this).addClass("selectedclass"); var thisselection = $(this).html(); thisselection.replace("", ""); $(".customselect").val(this.id); $("#iconselect").html(thisselection); $("#iconselectholder").toggle("fast"); if(obj.hasClass('onchange-changeCategoryOOI')) { window.location = '//'+location.hostname+"/poilist/"+$(".customselect").val()+"/recently"; } }); }); } function checkLoadedAdsIFrameOnFrontPage(iframe) { var iframeDocument = iframe.contentDocument || iframe.contentWindow.document; if(iframeDocument && iframeDocument.body && iframeDocument.body.innerHTML != "") { iframe.className = 'ads-iframe-loaded'; } } function checkAreaForAdsIframe() { if(($(window).width() - $('#logo').width() - 20) < $('#longdo_advertisement').width()) { // 20: margin-left of logo if($('#longdo_advertisement_iframe').attr('src') != '') { $('#longdo_advertisement_iframe').removeAttr('src'); $('#longdo_advertisement_iframe').removeClass('ads-iframe-loaded'); } } else { if(! $('#longdo_advertisement_iframe').attr('src')) { $('#longdo_advertisement_iframe').attr('src', '/ads/rand_ads.php'); } } } function getPermalinkURL() { if(isShowMap()) { var selected_tab_index = getCurrentTabIndex(); var url = false; if (selected_tab_index > 0) { var tab_panel = $(".ui-tabs-panel").get(selected_tab_index); if (typeof(tab_panel) != 'undefiend' && tab_panel.id) { url = $("#"+tab_panel.id).attr('originalpath'); } if (url) { url = window.location.protocol+'//'+window.location.hostname+url; } } if (!url) { url = window.location.protocol+'//'+window.location.hostname+'/?'; var location = getCenterLocation(); var latitude = location.lat; var longitude = location.lon; var zoom = mapZoom(); var search, tag, ooi; /*, searchlat, searchlon*/ if (typeof(window._longdomap_permalink_act) != 'undefined') { search = _longdomap_permalink_act.search ? _longdomap_permalink_act.search : false; //searchlat = _longdomap_permalink_act.searchlat ? _longdomap_permalink_act.searchlat : false; //searchlon = _longdomap_permalink_act.searchlon ? _longdomap_permalink_act.searchlon : false; tag = _longdomap_permalink_act.tag ? _longdomap_permalink_act.tag : false; ooi = _longdomap_permalink_act.ooi ? _longdomap_permalink_act.ooi : false; // if (search && searchlat && searchlon) { // latitude = searchlat; // longitude = searchlon; // } } var advance_param = ''; if (search) { advance_param += '&search='+search; } if (tag) { advance_param += '&tag='+tag; } if (ooi) { advance_param += '&ooi='+ooi; } var ggmode = getGoogleMapModeV1(); if(ggmode == 'gmap') { url += "gmap=1&"; } else if(ggmode == 'hybrid') { url += "hybrid=1&"; } else { url += "mode=" + encodeURIComponent(getMapModeV1()) + "&"; } url = url + 'lat='+latitude+'&long='+longitude+'&zoom='+zoom+'&map='+getMapProjection()+advance_param; if (mylang) { url += '&locale='+mylang; } } } else { url = window.location.href; } return url; } /*** front-page-jquery ***/ var hash = false; // var add_ooi_latitude = false; // var add_ooi_longitude = false; var add_ooi_by_popup = false; //var add_ooi_param = false; var _add_new_tab = false; var $tabs; var hash_tab = window.location.hash.substring(1); if(hash_tab.match(/^!/)) { hash_tab = hash_tab.substring(1); if(hash_tab == '/longdomap') hash_tab = '/'; window.location = hash_tab; } // redirect to page info //if((typeof(user_uid)!='number' || user_uid <= 0) && (typeof(ooi_edit) != 'undefined' && ooi_edit)) { // ooi_view = ooi_edit; // ooi_edit = false; //} function getURLFromTabID(tab_id) { var path_arr = tab_id.split("-"); path_arr.pop(); var ajax_url = path_arr.join("/"); var original_path = ''; var add_parameter = ''; if(ajax_url.match(/addlocation/i)) { original_path = getOriginalPath('/'+ajax_url); add_parameter = typeof add_ooi_param != 'undefined' ? add_ooi_param : ''; if(add_ooi_by_popup && document.selectedOOI) { add_parameter = document.selectedOOI.getParameterToOpenAddTab(); } ajax_url += add_parameter; original_path += add_parameter; } else { ajax_url = '/p/'+ajax_url; original_path = getOriginalPath(ajax_url); } var result = new Array(2); result['original_path'] = original_path; result['ajax_url'] = ajax_url; return result; } // jQuery.noConflict(); $(document).ready(function() { // tabs init with a custom tab template and an "add" callback filling in the content $tabs = $('#longdomap-tabs > ul').tabs({ add: function(event, ui) { $(this).tabs('select', ui.index); if( !$("#"+ui.panel.id).hasClass('ui-tabs-panel-ooi') ) { $('#'+ui.panel.id).addClass('ui-tabs-panel-ooi'); } var url_obj = getURLFromTabID(ui.panel.id); var original_path = url_obj.original_path; var ajax_url = url_obj.ajax_url; setLocationHash(original_path); $("#"+ui.panel.id).attr('originalpath', original_path); if(ajax_url.match(/addlocation/i)) { add_ooi_param = false; add_ooi_by_popup = false; } //var iframe_id = ui.panel.id.match(/iframe/i) ? ui.panel.id : false; //resize_frontpage('resizetabonly', iframe_id); if(!(ajax_url.match(/^\/p\//i) && ajax_url.match(/\/tab$/i))) { // if not "/p/A********/tab" $(this).tabs('url', ui.index, ajax_url); $(this).tabs('load', ui.index); } }, tabTemplate: '
  • #{label}
  • ', cache: true, cookie: { expires: 1 }, ajaxOptions: { async: false, cache:true }, spinner: false, show: function(event, ui) { var not_view_mode = (typeof(ooi_view)=='undefined' || !ooi_view); var not_edit_mode = (typeof(ooi_edit)=='undefined' || !ooi_edit); var not_add_mode = (typeof(add_ooi)=='undefined' || !add_ooi); var anonymous_mode = (typeof(user_uid)!='number' || user_uid <= 0); $('#longdomap-tabs a[href=#'+ui.panel.id+']').parent('li').removeClass('ui-tabs-hilight-unselected'); if(ui.index == 0 && (( not_view_mode && (not_edit_mode || anonymous_mode) && (not_add_mode || anonymous_mode) ) ) ) { if(!mmmap2) { if (getSelectedMapdata() == 'tomtom') { initTomtomMap(); } else { map_init(); } } if($('#longdomap-tabs ul.ui-tabs-nav li').length > 1 || _add_new_tab) { setLocationHash('/longdomap'); } } else if($("#"+ui.panel.id).attr('originalpath')) { setLocationHash($("#"+ui.panel.id).attr('originalpath')); } if(ui.index > 0) { _add_new_tab = true; } if($('#'+ui.panel.id).find('.ooi-details').length > 0) resizeDetailDivInTab($('#'+ui.panel.id).find('.ooi-details')); if( !$('#'+ui.panel.id).hasClass('ui-tabs-panel-iframe') && ($('#'+ui.panel.id).children('iframe.iframe-ooitab').length>0 || ui.panel.id.match(/iframe-formedit/)) ) { $('#'+ui.panel.id).addClass('ui-tabs-panel-iframe'); if($('#'+ui.panel.id).children('iframe.iframe-ooitab-ajax').length>0 && !$('#'+ui.panel.id).children('iframe.iframe-ooitab-ajax').hasClass('iframe-loaded')) { $('#'+ui.panel.id).prepend("
    "); } $('#'+ui.panel.id+' iframe.iframe-ooitab').load(function() { $('.ajax-loading-img').remove(); $(this).addClass("iframe-loaded") }); } if($('#'+ui.panel.id).hasClass('ui-tabs-panel-iframe')) { resize_frontpage('resizetabonly', ui.panel.id); } else { resize_frontpage('resizetabonly'); } $('#longdomap-tabs span.ui-tab-close') .click(function() { var index = $('li',$tabs).index($(this).parent("li")); $tabs.tabs('remove', index); }) .mouseover(function(){ $(this).addClass('ui-tab-close-hover'); }) .mouseout(function(){ $(this).removeClass('ui-tab-close-hover'); }); $('#longdomap-tabs ul.ui-tabs-nav li a') .mouseover(function(){ $(this).parent("span").parent("li").addClass("ui-tabs-hover"); }) .mouseout(function(){ $(this).parent("span").parent("li").removeClass("ui-tabs-hover"); }) }, length: function() { return this.anchors.length; }, load: function(event, ui) { if($('#'+ui.panel.id).find('.page-is-loading').length > 0) { return; } $("#longdomap-tabs a:not([@rel^=prettyPhoto],[@rel^=prettyHTML],[@rel^=prettyText],a[href*='/login'],[@href^=#],[@href^=javascript])").attr({ target: "_blank" }); $('#'+ui.panel.id+' a[rel^=\"prettyPhoto\"]').prettyPhoto(); $('#'+ui.panel.id+' a[rel^=\"prettyText\"]').prettyPhoto({ default_width: 400, default_height: 60 }); if (typeof(longdo_account) != 'undefined' && longdo_account) { longdo_account.initLongdoLogin($('#'+ui.panel.id+' a[href*="/login"]')); } else { $('#'+ui.panel.id+' a[href*="/login"]').prettyPhoto({ default_width: 400, default_height: 200 }); } // $('#reportAbuse').click(function() { // if ($('#reportpopup').length) { // $('#reportpopup').fadeIn(); // } // else { // $('#center').append('
    ' // + '
    ' // + '' // + '
    ' // + '
    '); // $('#reportpopup').click(function() { // $('#reportpopup').fadeOut(); // }); // } // return false; // }); var edit_permission_denied = ($('#'+ui.panel.id+' .ooi-options-edit').length == 0); var remark_report_abuse = edit_permission_denied ? '' : '
    '+((window.mylang && window.mylang == 'th') ? 'หมายเหตุ' : 'Remark')+':
    หากท่านต้องการแก้รายละเอียดของสถานที่ เช่น ป้อนตำแหน่ง หรือ ใส่ชื่อ, รายละเอียดผิด ท่านสามารถแก้ไขได้เองในหน้า '+((window.mylang && window.mylang == 'th') ? 'แก้ไขสถานที่' : 'Edit the location')+' (ไม่ต้องกรอกแบบฟอร์มในหน้านี้)
    '; $('#'+ui.panel.id+' a[rel^=\"prettyReportAbuseOOI\"]').prettyPhoto({ default_width: 475, default_height: 300, show_description: false, custom_markup: '
    \

    '+((window.mylang && window.mylang == 'th') ? 'แจ้งลบสถานที่' : 'Report Abuse or Dup.')+'


    \

    ' + ((window.mylang && window.mylang == 'th') ? 'โปรดระบุเหตุผลในการลบสถานที่นี้ลงในช่องด้านล่าง แล้วกดปุ่ม Send Email เพื่อแจ้งให้ผู้ดูแลระบบทราบ และพิจารณาลบสถานที่' : 'Enter your reason for deleting this point of interest. An email will be sent to the webmaster for approval.') + '

    \
    \ \ \ '+remark_report_abuse+'\
    ', changepicturecallback: function() { var tabIDsplit = $('#'+ui.panel.id+':not(.ui-tabs-hide)').attr('id').split("-"); var ooiid = tabIDsplit[0]; if($("#report-abuse-edit-link").length > 0) { $("#report-abuse-edit-link").attr('href', $("#report-abuse-edit-link").attr('href').replace(/{ooiid}/g,ooiid)); } var location_name = $('#'+ui.panel.id).not('.ui-tabs-hide').find('.title-of-contents').text(); $("#report-abuse-locationname").html(location_name); $("#report-abuse-reason-textarea").focus(function(){ $("#report-abuse-message-error").fadeOut(); }); $("#report-abuse-edit-link").click(function() { var path = ($(this).attr('href')).replace(/^\/p\//, '').replace(/\//,'-'); $.prettyPhoto.close(); showOOITab('Loading ..', path); return false; }); $("#report-abuse-send-mail-button").click(function(){ var reason = $("#report-abuse-reason-textarea").val(); $.ajax({ type: 'POST', url: 'ajax/sendmailreportabuse', data: ({ 'ooiid' : ooiid, 'txtReason' : reason }), success: function(txt) { $("#report-abuse-reason-textarea, #report-abuse-send-mail-button").hide(); $("#report-abuse-message-error").html(txt); $("#report-abuse-message-error").fadeIn(); $("#report-abuse-reason-textarea").val(""); } }); return false; }); } }); $('#'+ui.panel.id+' a[href^="/p/"][href$="/edit"]').click(function() { var path = ($(this).attr('href')).replace(/^\/p\//, '').replace(/\//,'-'); showOOITab('Loading ..', path); return false; }); $('#'+ui.panel.id+' a[href^="/p/"][href$="/delete"]').click(function() { var nid = $(this).attr('nid'); var location_name = $('#'+ui.panel.id).not('.ui-tabs-hide').find('.title-of-contents').text(); if (confirm('Are you sure to delete "'+location_name+'" ?')) { $('#saving-loading-'+nid).width($('#delete-link-'+nid).width()); $('#saving-loading-'+nid).css('display', 'inline-block'); $('#delete-link-'+nid).hide(); $.ajax({ type: 'POST', url: 'ajax/deleteooi', data: ({ 'nid' : nid }), success: function(txt) { var pattern = /^Error/g; if(pattern.test(txt)) { ; $('#delete-link-'+nid).show(); $('#saving-loading-'+nid).hide(); alert(txt); } else { eval(txt); } } }); } return false; }); //$('#longdomap-tabs #'+ui.panel.id+' a[@rel=showobject]').click(function() { // selectMapTab(this.id.replace(/-link(.*)$/,'')); // return false; //}); // Version 2015 $('#longdomap-tabs #'+ui.panel.id+' a[@rel=showooitab]').click(function() { showOOITab($(this).text(), this.id.replace(/-link(.*)$/,'')); return false; }); //$('#longdomap-tabs #'+ui.panel.id+' a[@rel=showtag]').click(function() { // showTag($(this).text()); // return false; //}); // Version 2015 $('#longdomap-tabs #'+ui.panel.id+' a.small-map-image').hover( function () { $(this).addClass("small-map-image-hover"); }, function () { $(this).removeClass("small-map-image-hover"); } ); if(typeof(gapi) != "undefined" && (browser!='IE' || (browser=='IE' && version>7))) gapi.plusone.go(); if(typeof(FB) != "undefined" && (browser!='IE' /* || (browser=='IE' && version>6) */)) { FB.XFBML.parse(); } else { $("#fb-comment-header").hide(); $("#fb-comment").hide(); setTimeout( function(){ if(typeof(FB) != "undefined" && (browser!='IE' /* || (browser=='IE' && version>6) */)) { $("#fb-comment-header").show(); $("#fb-comment").show(); } }, 1000); } var title_div = $('#'+ui.panel.id).find('.title-of-contents'); if(title_div && title_div.length > 0) { var label = title_div.text(); if(label) { $('#longdomap-tabs a[href=#'+ui.panel.id+']').find('.location-tab-label').text(label.length > 12 ? label.substring(0,10) + "..." : label).attr('title', label); } } else if($('#'+ui.panel.id+' .iframe-ooitab').length > 0) { $('#'+ui.panel.id+' iframe.iframe-ooitab').load(function() { title_div = $(".title-of-contents", $("#"+ui.panel.id+" .iframe-ooitab").contents()); var label = title_div.text(); if(label) { $('#longdomap-tabs a[href=#'+ui.panel.id+']').find('.location-tab-label').text(label.length > 12 ? label.substring(0,10) + "..." : label).attr('title', label); } }); } } }); // console.log($tabs); //if($.cookie("longdotab_id_path_tab") && $.cookie("longdotab_title_tab")) { // open selected tab when login by ajax (set cookie @ longdo-jquery.js) // var title_tab = $.cookie("longdotab_title_tab"); // var title_id = $.cookie("longdotab_id_path_tab"); // $.cookie("longdotab_id_path_tab", null); // $.cookie("longdotab_title_tab", null); // setTimeout(function() {showOOITab(title_tab, title_id);}, 500); //} showRecentDiv(); $("#searchfor").focus(function(){ $(this).removeClass('searchfor-empty-onblur'); }).blur(function(){ if($(this).val() == '') { $(this).addClass('searchfor-empty-onblur'); } }); //resize_frontpage(); $("input#searchfor").focus(); $("input#searchfor").select(); if($('#longdomap-tabs').hasClass('ui-tabs-nav')) { $('#longdomap-tabs').removeClass('ui-tabs-nav') } $('#longdomap-tabs').addClass('ui-tabs'); $(".button").hover( function () { $(this).addClass("button-hover"); }, function () { $(this).removeClass("button-hover"); } ); $(".menu-top-right-tabbar").hover( function () { $(this).addClass("menu-top-right-tabbar-hover"); }, function () { $(this).removeClass("menu-top-right-tabbar-hover"); } ); $('#routing-export-to-line').bind('click', function() { exportRoutingToShape(); }); $('#routing-options').bind('click', function() { if(!$(this).hasClass('routing-options-contents-showing')) { showRoutingOptions(); } else { hideRoutingOptions(); } }); if(typeof(ooi_edit)!="undefined" && ooi_edit) { showOOITab("Loading ..", ooi_edit+"-edit"); ooi_edit = false; } else if(typeof(ooi_view)!="undefined" && ooi_view) { showOOITab("Loading ..", ooi_view); ooi_view = false; } else if(typeof(add_ooi)!="undefined" && add_ooi) { // showOOITab("Loading ..", 'A10000001'); // ooi_view = false; showOOITab("Loading ..", "addlocation-iframe-formedit"); add_ooi = false; } $(".menu-top").click(function () { $(".content-left-content-area").hide(); $("#"+$(this).attr('id')+"-area").show(); $(".menu-top").removeClass("menu-top-active"); $(this).addClass("menu-top-active"); if($(this).attr('id') != 'content-menu-tools') { hidePreviewSnippet(); } var this_id = $(this).attr('id'); if(this_id == 'content-menu-routing') { selectMapTab(); initRoutingForm(); resizeRoutingResult(); } else if(this_id == 'content-menu-main') { resize_frontpage('resizeleftpanelonly'); } }); $(".search-example-text .text-link").click(function () { var kw = $(this).text(); setSearchLocationValue(kw); doSearch(''); }); $('.icon-sample-tag').hover( function () { var bg_pos = $(this).css('background-position'); bg_pos = bg_pos.replace(/^0px/, '-16px'); $(this).css('background-position', bg_pos); }, function () { var bg_pos = $(this).css('background-position'); bg_pos = bg_pos.replace(/^-16px/, '0px'); $(this).css('background-position', bg_pos); $(this).css("icon-sample-tag-hover"); } ); $("#content-menu-tools").click(function(){ initSnippetForm(); selectMapTab(); createPermalink(); createDefaultSnippetCode(); }); //initLongdoTools(); resize_frontpage('resizeleftpanelonly'); if(typeof gensnippet != 'undefined' && gensnippet) { $("#content-menu-tools").click(); $("#tools-snippet-button").click(); setTimeout('$("#code-html-map-snippet").focus();$("#code-html-map-snippet").select(); showPreviewSnippet();', 100); } $(".text-link").hover( function () { $(this).addClass("text-link-hover"); }, function () { $(this).removeClass("text-link-hover"); } ); }); function initRoutingForm() { if(mmmap2.Route._longdomap_routing) return; mmmap2.Route._longdomap_routing = new Array(); setDragableOnRoutePin(); setAddDestinationButton(); setRoutingTxtBox(); setAddLastDestinationButton(); if (mmmap2.Route.size() == 0) { // do not display routing-about div, when init form by routing's pathComplete event showRoutingAbout(); clearRoutingFormValue(); } $( "#routing-destination-sortable" ).sortable({ placeholder: "ui-state-highlight", update: function( event, ui ) { regenerateRoutingTxtBox(); }, cancel: ".search-routing-icon,input,textarea,button,select,option" }); $( "#routing-destination-sortable" ).disableSelection(); } function setSearchLocationValue(val) { document.getElementById('searchfor').value = val; if(val != '') { $('#searchfor').removeClass('searchfor-empty-onblur'); } } var floodLayer, floodTagLayer, floodOverlay; function initMMMapOptions() { var label_default = mylang == 'th' ? 'เลือกชั้นข้อมูล' : 'Other layers'; var label_rain_forecast = mylang == 'th' ? 'คาดการณ์ฝนตก' : 'Rain Forecast'; var label_water_sensor = mylang == 'th' ? 'ระดับน้ำ' : 'Water sensor'; var label_future_masstransit = mylang == 'th' ? 'อนาคตประเทศไทย' : 'Future Masstransit'; var label_city_plan_thailand = mylang == 'th' ? 'ผังเมืองประเทศไทย' : 'Thailand plan'; var label_city_plan_province = mylang == 'th' ? 'ผังเมืองประเทศไทย (จังหวัด)' : 'Thailand plan (Provinces)'; var label_gistda_flood_update = mylang == 'th' ? 'น้ำท่วมล่าสุด (7 วัน)' : 'Latest Flood (7 days)'; var label_gistda_flood_2011 = mylang == 'th' ? 'น้ำท่วมปี 2554' : 'Flood 2011'; var label_gistda_flood_2010 = mylang == 'th' ? 'น้ำท่วมปี 2553' : 'Flood 2010'; var label_gistda_flood_2009 = mylang == 'th' ? 'น้ำท่วมปี 2552' : 'Flood 2009'; //var label_gistda_flood_2008 = mylang == 'th' ? 'น้ำท่วมปี 2551' : 'Flood 2008'; //var label_gistda_flood_2007 = mylang == 'th' ? 'น้ำท่วมปี 2550' : 'Flood 2007'; //var label_gistda_flood_2006 = mylang == 'th' ? 'น้ำท่วมปี 2549' : 'Flood 2006'; //var label_gistda_flood_2005 = mylang == 'th' ? 'น้ำท่วมปี 2548' : 'Flood 2005'; //var label_gistda_spot5 = mylang == 'th' ? 'ดาวเทียม SPOT5' : 'SPOT5 Satelite'; //var label_city_plan_city = mylang == 'th' ? 'ผังเมืองประเทศไทย (เมือง)' : 'Thailand plan (Cities)'; var label_none = mylang == 'th' ? 'ไม่แสดง' : 'Hide layer'; var flood_layer = [ {label: label_water_sensor, layer: "water_sensor"}, {label: label_future_masstransit, layer: "future_masstransit"}, {label: label_rain_forecast, layer: "rain_forecast_nextday"}, {label: label_city_plan_thailand, layer: "cityplan_thailand"}, {label: label_city_plan_province, layer: "cityplan_provinces"}, {label: label_gistda_flood_update, layer: "gistda_flood_update"}, {label: label_gistda_flood_2011, layer: "gistda_flood_2011"}, {label: label_gistda_flood_2010, layer: "gistda_flood_2010"}, {label: label_gistda_flood_2009, layer: "gistda_flood_2009"}, //{label: label_gistda_flood_2008, layer: "gistda_flood_2008"}, //{label: label_gistda_flood_2007, layer: "gistda_flood_2007"}, //{label: label_gistda_flood_2006, layer: "gistda_flood_2006"}, //{label: label_gistda_flood_2005, layer: "gistda_flood_2005"}, //{label: label_gistda_spot5, layer: "gistda_spot5"}, //{label: label_city_plan_city, layer: "cityplan_cities"}, {label: label_none, layer: "", type: longdo.ButtonType.Reset } ]; var floodMenu = new longdo.MenuBar({ dropdown: flood_layer, dropdownLabel: label_default, change: function(item){ if (floodLayer) { mmmap2.Layers.remove(floodLayer); floodLayer = ''; } if (floodTagLayer) { mmmap2.Tags.remove(floodTagLayer); if (floodTagLayer == 'future_masstransit') { mmmap2.Tags.remove('future_masstransit_station'); } floodTagLayer = ''; } if (floodOverlay) { if (floodOverlay == 'water_sensor') { clearWaterSensorLocations(); showMyFavoriteIcons(); floodOverlay = ''; } } if (item && item.layer && item.layer != '') { if (item.layer == 'future_masstransit') { floodTagLayer = item.layer; mmmap2.Tags.add('future_masstransit'); mmmap2.Tags.add('future_masstransit_station'); hideMapLegend(); } else if(item.layer == 'water_sensor') { floodOverlay = item.layer; showMapLegend('longdomap-area', '
    ข้อมูลจาก HAII
    ข้อมูลจาก GISTDA
    '); hideMyFavoriteIcons(); displayWaterSensorRange(); } else { if (item.layer == 'cityplan_thailand' || item.layer == 'cityplan_provinces' || item.layer == 'cityplan_cities') { floodLayer = new longdo.Layer('', { type: longdo.LayerType.TMS, url: '//ms.longdo.com/mapproxy/tms/1.0.0/'+item.layer+'/EPSG3857', zoomRange: {min: 1, max: 15}}); var layer_legend = item.layer == 'cityplan_thailand' ? 'cityplan_provinces' : item.layer; showMapLegend('longdomap-area', '', 'hide'); } else if(item.layer == 'rain_forecast_nextday') { floodLayer = new longdo.Layer('rain_forecast_nextday', { type: longdo.LayerType.WMTS, url: '//ms.longdo.com/mapproxy/service/', srs: 'GLOBAL_WEBMERCATOR', tileMatrix: function(zoom) { return zoom < 10 ? '0' + zoom : zoom }, zoomRange: { min: 1, max: 13 }, opacity: 1, refresh:3600}); var layer_legend = item.layer == 'cityplan_thailand' ? 'cityplan_provinces' : item.layer; showMapLegend('longdomap-area', '
    แสดงข้อมูลเฉพาะแผนที่ในระดับซูม 1 ถึง 13
    ข้อมูลคาดการณ์สภาวะฝน 24 ชม. จาก สถาบันสารสนเทศทรัพยากรน้ำและการเกษตร (องค์การมหาชน)
    ปรับปรุงทุกวัน เวลา 07:30, ข้อมูลแสดงถึงสภาวะฝนตั้งแต่ 19:00 ของวันก่อนหน้าถึง 19:00 ของวันนี้
    คำเตือน: ข้อมูลนี้เป็นผลงานในระยะวิจัยและพัฒนา โปรดใช้วิจารณญาณในการนำข้อมูลไปใช้
    '); if (mapZoom() < 6) { mapZoom(6); } else if (mapZoom() > 9) { mapZoom(9); } } else { floodLayer = new longdo.Layer(item.layer); hideMapLegend(); } mmmap2.Layers.add(floodLayer); } } else { hideMapLegend(); } } }); mmmap2.Ui.add(floodMenu); } function displayWaterSensorRange() { $.ajax({ dataType: "json", type: 'GET', url: '/webservice/json/getwatersensor', data: ({ 'op' : 'range' }), success: function(rs) { var result = rs.result; $('#watersensor-slider').attr('min', result.min_range); $('#watersensor-slider').attr('max', result.max_range); $('#watersensor-slider').attr('value', result.max_range); $('#watersensor-slider').attr('step', result.step); $('#watersensor-slider').show(); displayWaterSensorDatetime(); getWaterSensorLocations('latest'); } }); } function clearWaterSensorLocations() { var all_overlay = mmmap2.Overlays.list(); var num_overlay = all_overlay.length; var obj; for(var i=0; i'); var datas = result.data; var num = datas.length; var yAxisOption, dataSeries, unit, source, time; var waterLvl = []; var groundLvl = []; var leftBankLvl = []; var rightBankLvl = []; unit = datas[0][8]; source = datas[0][3]; if (source === 'GISTDA') { for (var i=0; i' + date_time_txt + ''); } function timeConverter(unixtimestamp){ var a = new Date(unixtimestamp * 1000); var month_en = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; var month_th = ['ม.ค.','ก.พ.','มี.ค.','เม.ย.','พ.ค.','มิ.ย.','ก.ค.','ส.ค.','ก.ย.','ต.ค.','พ.ย.','ธ.ค.']; var year = a.getFullYear(); if (mylang == 'th') { year += 543; } var month = mylang == 'th' ? month_th[a.getMonth()] : month_en[a.getMonth()]; var date = a.getDate(); var hour = a.getHours(); var min = a.getMinutes(); var sec = a.getSeconds(); var time = date + ' ' + month + ' ' + year + ' ' + (hour < 10 ? '0' : '') + hour + ':' + (min < 10 ? '0' : '') + min + ':' + (sec < 10 ? '0' : '') + sec ; return time; } var ROUTING_ABOUT_CONTENTS = "\
    \
    บริการแนะนำเส้นทาง
    \
    \
    วิธีใช้งาน
    \
    \
    เพิ่มจุดหมาย
    \
    คลิกขวาที่ตำแหน่งที่ต้องการบนแผนที่ แล้วเลือกคำสั่ง \"เดินทางจากจุดนี้\" หรือ \"เดินทางมาจุดนี้\"
    \
    หรือ ลากไอคอนหมุด ที่อยู่ด้านหลังกล่องข้อความไปวางบนแผนที่ในตำแหน่งที่ต้องการ
    \
    หรือ พิมพ์ชื่อสถานที่ในกล่องข้อความ แล้วเลือกจุดหมายโดยการคลิกที่ปุ่ม จากผลลัพธ์การค้นหา
    \
    แก้ไขจุดหมาย
    \
    ลากไอคอนหมุดบนแผนที่ไปยังตำแหน่งที่ต้องการ
    \
    หรือ ลากไอคอนหมุด ที่อยู่ด้านหลังกล่องข้อความของจุดหมายที่ต้องการแก้ไข ไปวางบนแผนที่ในตำแหน่งที่ต้องการ
    \
    หรือ พิมพ์ชื่อสถานที่ในกล่องข้อความของจุดหมายที่ต้องการเปลี่ยนแปลง แล้วเลือกจุดหมายโดยการคลิกที่ปุ่ม จากผลลัพธ์การค้นหา
    \
    สลับจุดหมาย
    \
    ลากปุ่ม เพื่อเลื่อนไปวางแทนที่ในตำแหน่งจุดหมายที่ต้องการ
    \
    หรือ คลิกปุ่ม เพื่อย้อนกลับเส้นทางของจุดหมายทั้งหมด
    \
    ลบจุดหมาย
    \
    คลิกที่ปุ่มกากบาท ในกล่องข้อความ
    \
    หรือ คลิกไอคอนหมุดบนแผนที่ แล้วเลือก \"ลบจุดหมาย\"
    \
    ตั้งค่าการเดินทาง
    \
    คลิกที่ปุ่ม เพื่อตั้งค่าการเดินทาง
    \
    บันทึกเส้นทางเข้าสู่ระบบ Longdo Map
    \
    คลิกที่ปุ่ม เพื่อบันทึกเส้นทาง
    \
    \
    \
    "; function showRoutingAbout() { $('#routing-result').html(ROUTING_ABOUT_CONTENTS); } function clearRoutingFormValue() { setBookmark(0, 'all', 'routing'); clearAllMarker(); clearAllPopup(); clearMyRouting(); hideRoutingOptions(); hideExportRoutingLink(); showRoutingAbout(); clearPlaceholderTxtbox(); if (mmmap_map && mmmap_map.longdomap_pano) { mmmap_map.longdomap_pano.showPath(); } } function clearPlaceholderTxtbox() { if($('.search-routing-textbox').length > 0) { $('.search-routing-textbox').each(function() { if ($(this).attr('original_placeholder')) { $(this).attr('placeholder', $(this).attr('original_placeholder')); } }); } } function clearSerchFormValue() { setSearchLocationValue(''); setBookmark(0, 'all'); clearAllMarker(); clearAllTag(); clearAllGeom(); clearAllPopup(); if(window.mmroute) mmroute.allClear(); showRecentDiv(); createCookie('cookie_search','',0); $("#searchfor").addClass('searchfor-empty-onblur'); showMyFavoriteIcons(); if(window.setPermalinkParam) setPermalinkParam('clearall'); updateQueryStringParam('all', ''); if (mmmap_map && mmmap_map.longdomap_pano) { mmmap_map.longdomap_pano.showPath(); } document.getElementById('searchfor').focus(); } function setRemoveDestinationButton(element_class) { if(typeof element_class == 'undefined') { element_class = '.remove-destination-div'; } $(element_class).bind('click', function() { var div_row_id = $(this).attr('rel'); var index = getIndexFromTxtboxID(div_row_id); var autosearchrouting = mmmap2.Route._longdomap_routing[index] !== false; mmmap2.Route._longdomap_routing.splice(index,1); $('#'+div_row_id + ', #add-destination-'+(index+1)).remove(); if(autosearchrouting) { searchMyRouting(); } else { regenerateRoutingTxtBox(); } }); $(element_class).hover( function () { $(this).addClass("remove-destination-div-hover"); }, function () { $(this).removeClass("remove-destination-div-hover"); } ); } function regenerateRoutingTxtBox() { var numTxtBox = $('.search-routing-destination-div').length; $(".remove-destination-div").remove(); $(".search-routing-destination-div").each(function(index) { var id = ''; if(index == 0) { // start id = 'start-search-routing-destination-div'; $(this).removeClass('mid-search-routing-destination-div'); } else if(index == (numTxtBox-1)) { // finish id = 'end-search-routing-destination-div'; $(this).removeClass('mid-search-routing-destination-div'); } else { // middle id = 'div-mid-destination'+index; $(this).addClass('mid-search-routing-destination-div'); } $(this).attr('id',id); }); $(".search-routing-textbox").each(function(index) { PLACEHOLDER_ROUTING_TXTBOX = 'กำหนด%p1 / ลากหมุด%p2วางบนแผนที่'; var placeholder = ''; if(index == 0) { // start plcaeholder = PLACEHOLDER_ROUTING_TXTBOX.replace('%p1', 'จุดเริ่มต้น').replace('%p2', 'สีเขียว'); } else if(index == (numTxtBox-1)) { // finish plcaeholder = PLACEHOLDER_ROUTING_TXTBOX.replace('%p1', 'จุดสิ้นสุด').replace('%p2', 'สีแดง'); } else { // middle plcaeholder = PLACEHOLDER_ROUTING_TXTBOX.replace('%p1', 'จุดหมาย '+index).replace('%p2', 'เลข '+index+' '); } $(this).attr('placeholder', plcaeholder); }); $(".search-routing-icon-div img").each(function(index) { var suffix_image = index; if (suffix_image > 50) { suffix_image = ''; } var img_src = '//mmmap15.longdo.com/mmroute/images/dest'+suffix_image+'.png'; var title = ''; var id = ''; if(index == 0) { // start title = PREFIX_TITLE_ROUTING_PIN + 'จุดเริ่มต้น'; id = 'icon-destination-start'; } else if(index == (numTxtBox-1)) { // finish img_src = '//mmmap15.longdo.com/mmroute/images/destLast.png'; title = PREFIX_TITLE_ROUTING_PIN + 'จุดสิ้นสุด'; id = 'icon-destination-finish'; } else { // middle title = PREFIX_TITLE_ROUTING_PIN + 'จุดหมายที่ ' + index; id = 'icon-mid-destination'+index; $(this).attr('orderdestination', index); } $(this).attr('src', img_src); $(this).attr('title', title); $(this).attr('id',id); }); var new_longdo_routing = new Array(); $(".search-routing-textbox").each(function(index) { var old_index = getIndexFromTxtboxID($(this).attr('id')); new_longdo_routing.push(mmmap2.Route._longdomap_routing[old_index]); var id = ''; var rel_txtbox = 'div-'+$(".search-routing-destination-div").get(index).id; if(index == 0) { // start id = 'destination-start'; $(this).removeClass('mid-search-routing-textbox'); } else if(index == (numTxtBox-1)) { // finish id = 'destination-finish'; $(this).removeClass('mid-search-routing-textbox'); } else { // middle id = 'mid-destination'+index; $(this).attr('orderdestination', index); $(this).addClass('mid-search-routing-textbox'); var remove_div = document.createElement('div'); remove_div.id = 'remove-destination-'+(index); remove_div.className = 'remove-destination-div'; remove_div.rel = rel_txtbox; $(this).after(remove_div); } $(this).attr('id',id); }); setRemoveDestinationButton(); mmmap2.Route._longdomap_routing = new_longdo_routing; searchMyRouting(); } function showRoutingOptions() { $('#routing-options-contents').show(); $('#routing-options').addClass('routing-options-contents-showing'); resizeRoutingResult(); } function hideRoutingOptions() { $('#routing-options-contents').hide(); $('#routing-options').removeClass('routing-options-contents-showing'); resizeRoutingResult(); } function setAddLastDestinationButton() { $('.add-last-destination').bind('click', function() { //var idx = parseInt($(this).attr('id').replace('add-destination-', '')); var idx = $('.search-routing-icon').length - 1; cloneRoutingTxtBox(idx); mmmap2.Route._longdomap_routing.splice(idx, 0, false); resizeRoutingResult(); adjest_result_content() }); $('#reverse-routing-path-button').bind('click', function() { mmmap2.Route.reverse(); }); } function setAddDestinationButton(element_class) { if(typeof element_class == 'undefined') { element_class = '.add-destination-div'; } setDragableOnRoutePin(element_class); } function setDragableOnRoutePin(element_class) { if(typeof element_class == 'undefined') { element_class = '.search-routing-icon, .add-destination-div'; } var PIN_WIDTH = 33; var PIN_HEIGHT = 45; $(element_class).draggable({ cursor: 'move', containment: '#longdomap-area', zIndex: 10000, appendTo: 'body', scroll: false, cursorAt: { left: PIN_WIDTH / 2, top: 10 }, stop: function (event, ui) { var posX = $("#longdomap-area").offset().left; var posY = $("#longdomap-area").offset().top; var x = parseInt(ui.absolutePosition.left, 10) + PIN_WIDTH / 2; var y = parseInt(ui.absolutePosition.top, 10) + PIN_HEIGHT - 3; x = x - posX; //y = y - posY - 4; y = y - posY; var currentLocation = mmmap2.location({x: x ,y: y}); var lon = currentLocation.lon; var lat = currentLocation.lat; var icon_id = $(this).attr('id'); var index = getIndexFromTxtboxID(icon_id); var add_new_destination = false; var txtbox_id = icon_id.replace(/^icon-/, ''); if(mmmap2.Route._longdomap_routing.length == 0) { var txtbox_id = "destination-start"; } if(icon_id.match(/^add-destination-/i)) { add_new_destination = true; mmmap2.Route._longdomap_routing.splice(index, 0, {'name': '', 'lat': lat, 'lon': lon}); } else { // update mmmap2.Route._longdomap_routing.splice(index, 1, {'name': '', 'lat': lat, 'lon': lon}); } $('#'+txtbox_id).val(lat.toFixed(5) + ', ' + lon.toFixed(5)); searchMyRouting(); adjest_result_content() //var update_destination = false; // ////if(!add_new_destination && typeof mmroute.xQueue[index] != 'undefined') { // update destination //var destinations = getAllRouteDestinations(); //if(!add_new_destination && destinations && typeof destinations[index] != 'undefined') { // update destination // update_destination = true; // mmmap2.Route.auto(false); // mmmap2.Route.removeAt(index); // //mmroute.removeDestination(index); //} // //if(update_destination) { // mmmap2.Route.auto(true); //} // //mmmap2.Route.insert(index, {lat: lat, lon: lon}); ////mmroute.insertDestination(index, lat, lon); }, helper: function (event) { var icon_dropped_pin = $(this).attr('src') ? $(this).attr('src') : $(this).attr('rel'); var pin_obj = document.createElement('img'); pin_obj.src = icon_dropped_pin; pin_obj.id = 'from_helper'; pin_obj.style.zIndex = 100000; return pin_obj; } }); $(element_class).hover( function () { $(this).addClass("search-routing-icon-hover"); }, function () { $(this).removeClass("search-routing-icon-hover"); } ); } //function initLongdoTools() { // $('#tools-permalink-textbox').click(function() { // $(this).focus().select(); // }); //} function cancelChoosingDestinationResult(jq_element) { if(jq_element[0].placeholder == 'เลือกจุดหมายจากรายการด้านล่าง') { jq_element.val(''); jq_element.removeClass('choosing-destination-txtbox'); } } var _do_search_routing_on_blur_timeout = false; function setRoutingTxtBox(element_class) { if(typeof element_class == 'undefined') { element_class = '.search-routing-textbox'; } $(element_class).unbind('focus').unbind('blur').unbind('click').unbind('keyup').unbind('keydown'); if (getSelectedMapdata() == 'tomtom') { if (element_class.match(/^#/)) { searchtomtom.initTextBox($(element_class)[0]); } else if (element_class.match(/^\./)) { var element_class_txt = element_class.replace(/^\./, ''); var each_class = document.getElementsByClassName(element_class_txt); for (var i = 0; i < each_class.length; i++) { searchtomtom.initTextBox(each_class[i]); } } } else { // numap $(element_class).bind('focus', function(e){ document.onkeydown='return true'; document.onkeypress='return true'; _set_form_suggestion('searchrouteform'); setSuggestDivPosition(this, '_suggest_routing'); //cancelChoosingDestinationResult($(this)); //if (this.value) this.select(); }).bind('blur', function(e) { if($(this).attr('prepareforsearch') == 1 && $(this).attr('changeforsearch') == 1 && $(this).val() != '') { setBookmark(0, 'all', 'routing'); _do_search_routing_on_blur_timeout = setTimeout(doSearchForRouting, 200); } setKeyFocusAtMaparea(); setTimeout('clearSuggestDiv()',500); }).bind('click', function(e) { document.onkeydown='return true'; document.onkeypress='return true'; //cancelChoosingDestinationResult($(this)); }).bind('keyup', function(e) { //$(this).attr('prepareforsearch', 1); //$(this).attr('changeforsearch', 1); checkForSearchLocation(e, $(this)); _suggest_load(); }).bind('keydown', function(e) { //$('.search-routing-textbox').removeClass('searching-routing-textbox'); //$(this).addClass('searching-routing-textbox'); suggest_navigation_keys_check(e, this, '_suggest_routing'); }); } $(element_class).bind('focus', function(e){ cancelChoosingDestinationResult($(this)); if (this.value) this.select(); }).bind('blur', function(e) { if($(this).attr('prepareforsearch') == 1 && $(this).attr('changeforsearch') == 1 && $(this).val() != '') { } }).bind('click', function(e) { cancelChoosingDestinationResult($(this)); }).bind('keyup', function(e) { $(this).attr('prepareforsearch', 1); $(this).attr('changeforsearch', 1); }).bind('keydown', function(e) { $('.search-routing-textbox').removeClass('searching-routing-textbox'); $(this).addClass('searching-routing-textbox'); }); } function clearMyRouting() { $('#destination-start, #destination-finish').val(''); $('.add-destination-div, .mid-search-routing-destination-div').remove(); $('.search-routing-textbox').removeClass('searching-routing-textbox'); $('.choosing-destination-txtbox').removeClass('choosing-destination-txtbox'); if(mmmap2.Route) mmmap2.Route.clear(); if(mmmap2.Route._longdomap_routing) mmmap2.Route._longdomap_routing = new Array(); //Remove Export Line On Map mmmap2.Overlays.list().forEach(function(ol){if(ol instanceof longdo.Polyline && ol.title=="New Shape"){mmmap2.Overlays.remove(ol)}}) } function hideExportRoutingLink() { $("#routing-export-to-line, #reverse-routing-path-button").css('visibility', 'hidden'); } function showExportRoutingLink() { $("#routing-export-to-line, #reverse-routing-path-button").css('visibility', 'visible'); } function searchMyRouting() { if(!mmmap2.Route._longdomap_routing) { hideExportRoutingLink(); return; } $('.choosing-destination-txtbox').removeClass('choosing-destination-txtbox').removeClass('choosing-destination-txtbox'); mmmap2.Route.clear(); var num_destination = 0; var longdomap_routing = mmmap2.Route._longdomap_routing; var destination, des; for (var i=0; i 1) { showExportRoutingLink(); clearAllSearchLocationPin(); $('#routing-result').html("
    "); mmmap2.Route.search(); } else { hideExportRoutingLink(); showRoutingAbout(); } adjest_result_content() } function checkForSearchLocation(e) { var keycode; if (window.event) { keycode = window.event.keyCode; // IE } else if (e) keycode = e.which; //Firefox switch(keycode) { case 13://enter setBookmark(0, 'all', 'routing'); doSearchForRouting(); return false; default : return true; } } function getIndexFromTxtboxID(ele_id) { // or Icon Element ID var index = 0; if(ele_id.match(/-start$/i)) { index = 0; } else if(ele_id.match(/-finish$/i)) { index = $('.search-routing-textbox').length - 1; } else if(ele_id.match(/^add-destination-/i)) { index = parseInt(ele_id.replace('add-destination-', '')); } else if($('#'+ele_id).attr('orderdestination')) { index = $('#'+ele_id).attr('orderdestination'); } return index; } function addDestinationToActiveTxtBox(lat, lon, name) { $('.searching-routing-textbox').val(name); if($('.searching-routing-textbox')[0] && $('.searching-routing-textbox')[0].original_placeholder) { $('.searching-routing-textbox')[0].placeholder = $('.searching-routing-textbox')[0].original_placeholder; } $('.searching-routing-textbox').removeClass('choosing-destination-txtbox'); var index = getIndexFromTxtboxID($('.searching-routing-textbox').attr('id')); var update_destination = false; lat = parseFloat(lat); lon = parseFloat(lon); if(typeof mmmap2.Route._longdomap_routing[index] == 'object') { // update mmmap2.Route._longdomap_routing.splice(index, 1, {'name': name, 'lat': lat, 'lon': lon}); } else { // insert if(mmmap2.Route._longdomap_routing.length == 0 && index > 0) { for(var i=0; i 0 && $('#longitude').length > 0) { var location_obj = getCenterLocation(); $('#latitude').val(location_obj.lat); $('#longitude').val(location_obj.lon); } var mapzoom_changed = (mapZoom() != $("#zoom").val()); var latlon_changed = ($("#snippet-location-by-latlon").is(":checked")); if ($("#zoom").length > 0 && mapzoom_changed) { $("#zoom").val(mapZoom()); } if (latlon_changed || mapzoom_changed) { generateSnippetCode(60); } } function setLocationHash(path) { var pathname = window.location.pathname + window.location.search; if(window.location.hash && window.location.hash.replace(/^#!/, '') == path) { return; } else if(pathname == path) { if(!window.location.hash) return; else window.location.hash = ''; } else if(path == '/longdomap') { if(pathname == '/') { if(!window.location.hash) return; else window.location.hash = ''; } else { window.location.hash = '!'+path; } } else window.location.hash = '!'+path; } function getOriginalPath(path) { if(path.match(/^\/addlocation/i) && path.match(/\/iframe\/formedit/i)) { return path.replace(/\/iframe\/formedit/i, ''); } else if(path.match(/iframe\/formedit$/i)) { return path.replace(/iframe\/formedit$/i, 'edit'); } else if(path.match(/\/tab$/i)) { return path.replace(/tab$/i, 'info'); } return path; } function setRecentLocationFrontPageHover() { $(".ads-location-frontpage, .recent-location-frontpage").hover( function () { $(this).addClass("hover-location-frontpage"); }, function () { $(this).removeClass("hover-location-frontpage"); } ); $(".more-recent-ooi").hover( function () { $(this).addClass("hover-more-recent-ooi"); }, function () { $(this).removeClass("hover-more-recent-ooi"); } ); $(".text-link").hover( function () { $(this).addClass("text-link-hover"); }, function () { $(this).removeClass("text-link-hover"); } ); $(".ads-location-frontpage-image img, .recent-location-frontpage-image img").hover( function () { $(this).addClass("hover"); }, function () { $(this).removeClass("hover"); } ); } function showAddLocationTab(lat, lon, source) { add_ooi_param = "?latitude="+lat+"&longitude="+lon if(source && typeof(source)=='string' && source=='popup') add_ooi_by_popup = true; showOOITab("Loading ..", "addlocation-iframe-formedit", false, "addlocation"); } function showOOITab(title, id, slide_to_div, replace_id_tab, notChangeToNewTab) { var ooiid = false; var mode = 'view'; if(id.match(/^(A|G|M)[0-9]{8}/i)) { var path_arr = id.split("-", 2); ooiid = path_arr[0]; } if(ooiid && !id.match(/-/i)) { id += "-tab"; } if(ooiid && id.match(/-edit$/i)) { id = id.replace(/-edit$/i, "-iframe-formedit"); mode = 'edit'; } else if(id.match(/^addlocation/i)) { mode = 'add'; } if(mode=='edit' || mode=='add') { if(typeof(user_uid)!='number' || user_uid <= 0) { var url_obj = getURLFromTabID(id+'-faketabid'); var original_path = url_obj.original_path; var ajax_url = url_obj.ajax_url; setLocationHash(original_path); if (window.longdo_account) { longdo_account.showLongdoLoginForm(); } else { setTimeout(function() {showLoginForm();}, 100); } return; } } var id_path = id.replace(/-/g, "/"); // id = id.replace(/\//g, "_"); if($("#longdomap-tabs a[href^=#"+(ooiid ? ooiid : id)+"-]").length == 0 && (!replace_id_tab || $("#longdomap-tabs a[href^=#"+replace_id_tab+"-]").length == 0) ) { var theme_path = (typeof Drupal == 'undefined' || typeof Drupal.settings == 'undefined' || typeof Drupal.settings.pathToTheme == 'undefined') ? '/themes/longdo' : Drupal.settings.pathToTheme; // FIXME Drupal.settings.pathToTheme is undefined on real server ?? checkloadjscssfile(theme_path+"/longdo-ooi.css?20130713", "css"); $tabs.tabs("option", "idPrefix", id+'-'); $tabs.bind("tabsload", function(event, ui) { $("#comment-controls").remove(); }); // label = title.length > 20 ? title.substring(0,18) + "..." : title; // $tabs.tabs('label', $tabs.tabs('option', 'selected'), label); if (!slide_to_div && window.location.hash && window.location.hash != '#') { slide_to_div = window.location.hash; } if(slide_to_div && typeof slide_to_div != 'undefined') { $tabs.bind("tabsshow", function(event, ui) { slideToHash(ui.panel.id, slide_to_div); slide_to_div = false; }); } else { $tabs.unbind("tabsshow"); } // var ajax_url = id_path.match(/iframe/i) && mode != 'add' ? '/p/'+id_path : "/tab/loading"; var ajax_url = mode != 'edit' && mode != 'add' ? '/p/'+id_path : "/tab/loading"; $tabs.tabs("add", ajax_url, title); } else { if( ((document.selectedOOI || (replace_id_tab == 'addlocation' && id && title)) && $("#longdomap-tabs a[href^=#"+replace_id_tab+"-]").length > 0) || (ooiid && $("#longdomap-tabs a[href^=#"+ooiid+"-]").length > 0) ) {// if($("#longdomap-tabs a[href^=#"+ooiid+"-]").length > 0) // $("#content ul li a:first").html("" + title + ""); // $("#content").tabs("url", 0, url).tabs("select", 0).tabs("load", 0); var old_tab_id = replace_id_tab ? replace_id_tab : ooiid; var tabindex = $('#longdomap-tabs ul li a').index($("a[href^='#"+old_tab_id+"-']")); if(notChangeToNewTab !== true) { selectTab(tabindex); } else { $('#longdomap-tabs a[href^="#'+old_tab_id+'-"]').parent('li').addClass('ui-tabs-hilight-unselected'); } var old_href = $("#longdomap-tabs a[href^=#"+old_tab_id+"-]").attr('href'); var old_href_arr = old_href.split('-'); var new_href = id+'-'+old_href_arr[old_href_arr.length-1]; if(old_href != '#'+new_href || new_href.match(/^addlocation/i)) { var ajax_url = ''; if(new_href.match(/^addlocation/i)) { ajax_url = '/'+id_path; add_parameter = add_ooi_param; if(add_ooi_by_popup && document.selectedOOI) { add_parameter = document.selectedOOI.getParameterToOpenAddTab(); } ajax_url += add_parameter; add_ooi_param = false; add_ooi_by_popup = false; } else { ajax_url = '/p/'+id_path; } // $tabs.tabs('url', tabindex, "/tab/loading"); // $tabs.tabs('load', tabindex); // $tabs.tabs('url', tabindex, ajax_url); $tabs.tabs('load', tabindex); var old_href = $("#longdomap-tabs a[href^=#"+old_tab_id+"-]").attr('href'); var old_href_arr = old_href.split('-'); var new_href = id+'-'+old_href_arr[old_href_arr.length-1]; $("#longdomap-tabs a[href^=#"+old_tab_id+"-]").attr('href', '#'+new_href); $(old_href).attr('id', new_href); var original_path = getOriginalPath(ajax_url); setLocationHash(original_path); $("#"+new_href).attr('originalpath', original_path) if(mode == 'edit' || mode == 'add') { $('#'+new_href).addClass('ui-tabs-panel-iframe'); } else { $('#'+new_href).removeClass('ui-tabs-panel-iframe'); } //var iframe_id = new_href.match(/iframe/i) ? new_href : false; resize_frontpage('resizetabonly'); } else if(old_href == '#'+new_href && new_href.match(/^addlocation/i)) { var original_path = getOriginalPath('/'+id_path); add_parameter = add_ooi_param; if(add_ooi_by_popup && document.selectedOOI) { add_parameter = document.selectedOOI.getParameterToOpenAddTab(); } ajax_url += add_parameter; original_path += add_parameter; setLocationHash(original_path); $("#"+ui.panel.id).attr('originalpath', original_path); add_ooi_param = false; add_ooi_by_popup = false; } } else { var tabindex = $('#longdomap-tabs ul li a').index($("a[href^='#"+id+"-']")); if(notChangeToNewTab !== true) { selectTab(tabindex); } else { $('#longdomap-tabs a[href^="#'+id+'-"]').parent('li').addClass('ui-tabs-hilight-unselected'); } } var panel_id = $("a[href^='#"+id+"-']").attr('href'); if(typeof slide_to_div != 'undefined') { slideToHash(panel_id, slide_to_div); slide_to_div = false; } } } document.showOOITab = showOOITab; function slideToHash(id, hash) { if(! /^#/.test(id)) id = "#"+id; if(! /^#/.test(hash)) hash = "#"+hash; if($(hash).length>0 && $(id).length>0 ) { var divOffset = $(id).scrollTop(); var hashOffset = $(hash).offset().top; var hashScroll = divOffset + hashOffset - 170; $(id).animate({ 'scrollTop': hashScroll }, 'slow'); if (hash.match(/#image-\d+/) && $(hash).parent('a').length > 0) { $(hash).parent('a').click(); } } } function selectTab(index) { if($tabs) $tabs.tabs('select', index); } function selectMapTab(ooiid) { selectTab(0); if(typeof(ooiid) != 'undefined' && (/^(A|G|M|H)/.test(ooiid)) ) { clearAllGeom(); showLongdoPOI(ooiid, true); //mmmap.showObject({"id":ooiid, "dozoom":1}); } } function getCurrentTabIndex() { return $('#longdomap-tabs ul li').index($(".ui-tabs-selected")); } function closeCurrentTab() { var selected_tab_index = getCurrentTabIndex(); if($tabs) $tabs.tabs('remove', selected_tab_index); } function refreshCurrentTab() { var selected_tab_index = getCurrentTabIndex(); if($tabs) $tabs.tabs('load', selected_tab_index); } /* function resizeTab() { var pageheaderH = $("#pageheader") ? $("#pageheader").height() : 0; var menuH = $("#menu_area") ? $("#menu_area").height() : 0; var tabheaderH = $("ul#tablist") ? $("ul#tablist").height() : 0; var tab_content_height = wh - pageheaderH - menuH - tabheaderH - (browser=='IE' ? 8 : 23); var rightpanelW = $("#right_panel") ? $("#right_panel").width() : 0; var tab_content_width = ww - rightpanelW - (browser=='IE' ? 4 : 6); if(tab_content_height > 0) $("#longdomap-tabs .ui-tabs-panel").css( {height:tab_content_height+"px"}); if(tab_content_width > 0) $("#longdomap-tabs").css( {width:tab_content_width+"px"}); } */ function resizeDetailDivInTab(ooi_details_div) { document.temp_ooi_details_div = ooi_details_div; setTimeout(function() { var ooi_details_div = document.temp_ooi_details_div; var detail_div = ooi_details_div.find('.detail-ooi'); if(!detail_div) return; var ooi_detail_w = $("#longdomap-tabs").width(); var image_w = ooi_details_div.find('.sample-image-ooi').width(); var snippet_w = ooi_details_div.find('.ooi-snippet').width(); var fit_w = ooi_detail_w - image_w - snippet_w - 75 - 30 - 4; // 75: all margin width, 30: padding, 4: border of images detail_div.width(fit_w); }, 100); }/** * Created by por on 7/17/2015 AD. */ /* (C) 2009 Ivan Boldyrev * * Fgh is a fast GeoHash implementation in JavaScript. * * Fgh is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Fgh is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this software; if not, see . */ (function(){var d="0123456789bcdefghjkmnpqrstuvwxyz";var e=[0,1,0,1,2,3,2,3,0,1,0,1,2,3,2,3,4,5,4,5,6,7,6,7,4,5,4,5,6,7,6,7];var f=[0,1,4,5,16,17,20,21,64,65,68,69,80,81,84,85,256,257,260,261,272,273,276,277,320,321,324,325,336,337,340,341];function _cmb(a,b){return(d.indexOf(a.charAt(b))<<5)|(d.indexOf(a.charAt(b+1)))};function _unp(v){return e[v&0x1F]|(e[(v>>6)&0xF]<<3)}function _sparse(a){var b=0,off=0;while(a>0){low=a&0xFF;b|=f[low]<>=8;off+=16}return b}window['Fgh']={decode:function(a){var L=a.length,i,w,ln=0.0,lt=0.0;if(L&1){w=(d.indexOf(a.charAt(L-1))<<5)}else{w=_cmb(a,L-2)}lt=(_unp(w))/32.0;ln=(_unp(w>>1))/32.0;for(i=(L-2)&~0x1;i>=0;i-=2){w=_cmb(a,i);lt=(_unp(w)+lt)/32.0;ln=(_unp(w>>1)+ln)/32.0}return{lat:180.0*(lt-0.5),lon:360.0*(ln-0.5)}},encode:function(a,b,c){a=a/180.0+0.5;b=b/360.0+0.5;var r='',l=Math.ceil(c/10),hlt,hln,b2,hi,lo,i;for(i=0;i>5;lo=b2&0x1F;r+=d.charAt(hi)+d.charAt(lo)}r=r.substr(0,Math.ceil(c/5));return r},checkValid:function(a){return!!a.match(/^[0-9b-hjkmnp-z]+$/)}}})(); /* Prototype JavaScript framework, version 1.5.0 * (c) 2005-2007 Sam Stephenson * * Prototype is freely distributable under the terms of an MIT-style license. * For details, see the Prototype web site: http://prototype.conio.net/ * /*--------------------------------------------------------------------------*/ var Prototype = { Version: '1.5.0', BrowserFeatures: { XPath: !!document.evaluate }, ScriptFragment: '(?:)((\n|\r|.)*?)(?:<\/script>)', emptyFunction: function() {}, K: function(x) { return x } } var Class = { create: function() { return function() { this.initialize.apply(this, arguments); } } } var Abstract = new Object(); Object.extend = function(destination, source) { for (var property in source) { destination[property] = source[property]; } return destination; } Object.extend(Object, { inspect: function(object) { try { if (object === undefined) return 'undefined'; if (object === null) return 'null'; return object.inspect ? object.inspect() : object.toString(); } catch (e) { if (e instanceof RangeError) return '...'; throw e; } }, keys: function(object) { var keys = []; for (var property in object) keys.push(property); return keys; }, values: function(object) { var values = []; for (var property in object) values.push(object[property]); return values; }, clone: function(object) { return Object.extend({}, object); } }); Function.prototype.bind = function() { var __method = this, args = $A(arguments), object = args.shift(); return function() { return __method.apply(object, args.concat($A(arguments))); } } Function.prototype.bindAsEventListener = function(object) { var __method = this, args = $A(arguments), object = args.shift(); return function(event) { return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments))); } } Object.extend(Number.prototype, { toColorPart: function() { var digits = this.toString(16); if (this < 16) return '0' + digits; return digits; }, succ: function() { return this + 1; }, times: function(iterator) { $R(0, this, true).each(iterator); return this; } }); var Try = { these: function() { var returnValue; for (var i = 0, length = arguments.length; i < length; i++) { var lambda = arguments[i]; try { returnValue = lambda(); break; } catch (e) {} } return returnValue; } } /*--------------------------------------------------------------------------*/ var PeriodicalExecuter = Class.create(); PeriodicalExecuter.prototype = { initialize: function(callback, frequency) { this.callback = callback; this.frequency = frequency; this.currentlyExecuting = false; this.registerCallback(); }, registerCallback: function() { this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); }, stop: function() { if (!this.timer) return; clearInterval(this.timer); this.timer = null; }, onTimerEvent: function() { if (!this.currentlyExecuting) { try { this.currentlyExecuting = true; this.callback(this); } finally { this.currentlyExecuting = false; } } } } String.interpret = function(value){ return value == null ? '' : String(value); } Object.extend(String.prototype, { gsub: function(pattern, replacement) { var result = '', source = this, match; replacement = arguments.callee.prepareReplacement(replacement); while (source.length > 0) { if (match = source.match(pattern)) { result += source.slice(0, match.index); result += String.interpret(replacement(match)); source = source.slice(match.index + match[0].length); } else { result += source, source = ''; } } return result; }, sub: function(pattern, replacement, count) { replacement = this.gsub.prepareReplacement(replacement); count = count === undefined ? 1 : count; return this.gsub(pattern, function(match) { if (--count < 0) return match[0]; return replacement(match); }); }, scan: function(pattern, iterator) { this.gsub(pattern, iterator); return this; }, truncate: function(length, truncation) { length = length || 30; truncation = truncation === undefined ? '...' : truncation; return this.length > length ? this.slice(0, length - truncation.length) + truncation : this; }, strip: function() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); }, stripTags: function() { return this.replace(/<\/?[^>]+>/gi, ''); }, stripScripts: function() { return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); }, extractScripts: function() { var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); return (this.match(matchAll) || [])._map(function(scriptTag) { return (scriptTag.match(matchOne) || ['', ''])[1]; }); }, evalScripts: function() { return this.extractScripts()._map(function(script) { return eval(script) }); }, escapeHTML: function() { var div = document.createElement('div'); var text = document.createTextNode(this); div.appendChild(text); return div.innerHTML; }, unescapeHTML: function() { var div = document.createElement('div'); div.innerHTML = this.stripTags(); return div.childNodes[0] ? (div.childNodes.length > 1 ? $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) : div.childNodes[0].nodeValue) : ''; }, toQueryParams: function(separator) { var match = this.strip().match(/([^?#]*)(#.*)?$/); if (!match) return {}; return match[1].split(separator || '&').inject({}, function(hash, pair) { if ((pair = pair.split('='))[0]) { var name = decodeURIComponent(pair[0]); var value = pair[1] ? decodeURIComponent(pair[1]) : undefined; if (hash[name] !== undefined) { if (hash[name].constructor != Array) hash[name] = [hash[name]]; if (value) hash[name].push(value); } else hash[name] = value; } return hash; }); }, toArray: function() { return this.split(''); }, succ: function() { return this.slice(0, this.length - 1) + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); }, camelize: function() { var parts = this.split('-'), len = parts.length; if (len == 1) return parts[0]; var camelized = this.charAt(0) == '-' ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) : parts[0]; for (var i = 1; i < len; i++) camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); return camelized; }, capitalize: function(){ return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); }, underscore: function() { return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase(); }, dasherize: function() { return this.gsub(/_/,'-'); }, inspect: function(useDoubleQuotes) { var escapedString = this.replace(/\\/g, '\\\\'); if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; else return "'" + escapedString.replace(/'/g, '\\\'') + "'"; } }); String.prototype.gsub.prepareReplacement = function(replacement) { if (typeof replacement == 'function') return replacement; var template = new Template(replacement); return function(match) { return template.evaluate(match) }; } String.prototype.parseQuery = String.prototype.toQueryParams; var Template = Class.create(); Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; Template.prototype = { initialize: function(template, pattern) { this.template = template.toString(); this.pattern = pattern || Template.Pattern; }, evaluate: function(object) { return this.template.gsub(this.pattern, function(match) { var before = match[1]; if (before == '\\') return match[2]; return before + String.interpret(object[match[3]]); }); } } var $break = new Object(); var $continue = new Object(); var Enumerable = { each: function(iterator) { var index = 0; try { this._each(function(value) { try { iterator(value, index++); } catch (e) { if (e != $continue) throw e; } }); } catch (e) { if (e != $break) throw e; } return this; }, eachSlice: function(number, iterator) { var index = -number, slices = [], array = this.toArray(); while ((index += number) < array.length) slices.push(array.slice(index, index+number)); return slices._map(iterator); }, all: function(iterator) { var result = true; this.each(function(value, index) { result = result && !!(iterator || Prototype.K)(value, index); if (!result) throw $break; }); return result; }, any: function(iterator) { var result = false; this.each(function(value, index) { if (result = !!(iterator || Prototype.K)(value, index)) throw $break; }); return result; }, collect: function(iterator) { var results = []; this.each(function(value, index) { results.push((iterator || Prototype.K)(value, index)); }); return results; }, detect: function(iterator) { var result; this.each(function(value, index) { if (iterator(value, index)) { result = value; throw $break; } }); return result; }, findAll: function(iterator) { var results = []; this.each(function(value, index) { if (iterator(value, index)) results.push(value); }); return results; }, grep: function(pattern, iterator) { var results = []; this.each(function(value, index) { var stringValue = value.toString(); if (stringValue.match(pattern)) results.push((iterator || Prototype.K)(value, index)); }) return results; }, include: function(object) { var found = false; this.each(function(value) { if (value == object) { found = true; throw $break; } }); return found; }, inGroupsOf: function(number, fillWith) { fillWith = fillWith === undefined ? null : fillWith; return this.eachSlice(number, function(slice) { while(slice.length < number) slice.push(fillWith); return slice; }); }, inject: function(memo, iterator) { this.each(function(value, index) { memo = iterator(memo, value, index); }); return memo; }, invoke: function(method) { var args = $A(arguments).slice(1); return this._map(function(value) { return value[method].apply(value, args); }); }, max: function(iterator) { var result; this.each(function(value, index) { value = (iterator || Prototype.K)(value, index); if (result == undefined || value >= result) result = value; }); return result; }, min: function(iterator) { var result; this.each(function(value, index) { value = (iterator || Prototype.K)(value, index); if (result == undefined || value < result) result = value; }); return result; }, partition: function(iterator) { var trues = [], falses = []; this.each(function(value, index) { ((iterator || Prototype.K)(value, index) ? trues : falses).push(value); }); return [trues, falses]; }, pluck: function(property) { var results = []; this.each(function(value, index) { results.push(value[property]); }); return results; }, reject: function(iterator) { var results = []; this.each(function(value, index) { if (!iterator(value, index)) results.push(value); }); return results; }, sortBy: function(iterator) { return this._map(function(value, index) { return {value: value, criteria: iterator(value, index)}; }).sort(function(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }).pluck('value'); }, toArray: function() { return this._map(); }, zip: function() { var iterator = Prototype.K, args = $A(arguments); if (typeof args.last() == 'function') iterator = args.pop(); var collections = [this].concat(args)._map($A); return this._map(function(value, index) { return iterator(collections.pluck(index)); }); }, size: function() { return this.toArray().length; }, inspect: function() { return '#'; } } Object.extend(Enumerable, { _map: Enumerable.collect, find: Enumerable.detect, select: Enumerable.findAll, member: Enumerable.include, entries: Enumerable.toArray }); var $A = Array.from = function(iterable) { if (!iterable) return []; if (iterable.toArray) { return iterable.toArray(); } else { var results = []; for (var i = 0, length = iterable.length; i < length; i++) results.push(iterable[i]); return results; } } Object.extend(Array.prototype, Enumerable); if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse; Object.extend(Array.prototype, { _each: function(iterator) { for (var i = 0, length = this.length; i < length; i++) iterator(this[i]); }, clear: function() { this.length = 0; return this; }, first: function() { return this[0]; }, last: function() { return this[this.length - 1]; }, compact: function() { return this.select(function(value) { return value != null; }); }, flatten: function() { return this.inject([], function(array, value) { return array.concat(value && value.constructor == Array ? value.flatten() : [value]); }); }, without: function() { var values = $A(arguments); return this.select(function(value) { return !values.include(value); }); }, indexOf: function(object) { for (var i = 0, length = this.length; i < length; i++) if (this[i] == object) return i; return -1; }, reverse: function(inline) { return (inline !== false ? this : this.toArray())._reverse(); }, reduce: function() { return this.length > 1 ? this : this[0]; }, uniq: function() { return this.inject([], function(array, value) { return array.include(value) ? array : array.concat([value]); }); }, clone: function() { return [].concat(this); }, size: function() { return this.length; }, inspect: function() { return '[' + this._map(Object.inspect).join(', ') + ']'; } }); Array.prototype.toArray = Array.prototype.clone; function $w(string){ string = string.strip(); return string ? string.split(/\s+/) : []; } if(window.opera){ Array.prototype.concat = function(){ var array = []; for(var i = 0, length = this.length; i < length; i++) array.push(this[i]); for(var i = 0, length = arguments.length; i < length; i++) { if(arguments[i].constructor == Array) { for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) array.push(arguments[i][j]); } else { array.push(arguments[i]); } } return array; } } var Hash = function(obj) { Object.extend(this, obj || {}); }; Object.extend(Hash, { toQueryString: function(obj) { var parts = []; this.prototype._each.call(obj, function(pair) { if (!pair.key) return; if (pair.value && pair.value.constructor == Array) { var values = pair.value.compact(); if (values.length < 2) pair.value = values.reduce(); else { key = encodeURIComponent(pair.key); values.each(function(value) { value = value != undefined ? encodeURIComponent(value) : ''; parts.push(key + '=' + encodeURIComponent(value)); }); return; } } if (pair.value == undefined) pair[1] = ''; parts.push(pair._map(encodeURIComponent).join('=')); }); return parts.join('&'); } }); Object.extend(Hash.prototype, Enumerable); Object.extend(Hash.prototype, { _each: function(iterator) { for (var key in this) { var value = this[key]; if (value && value == Hash.prototype[key]) continue; var pair = [key, value]; pair.key = key; pair.value = value; iterator(pair); } }, keys: function() { return this.pluck('key'); }, values: function() { return this.pluck('value'); }, merge: function(hash) { return $H(hash).inject(this, function(mergedHash, pair) { mergedHash[pair.key] = pair.value; return mergedHash; }); }, remove: function() { var result; for(var i = 0, length = arguments.length; i < length; i++) { var value = this[arguments[i]]; if (value !== undefined){ if (result === undefined) result = value; else { if (result.constructor != Array) result = [result]; result.push(value) } } delete this[arguments[i]]; } return result; }, toQueryString: function() { return Hash.toQueryString(this); }, inspect: function() { return '#'; } }); function $H(object) { if (object && object.constructor == Hash) return object; return new Hash(object); }; ObjectRange = Class.create(); Object.extend(ObjectRange.prototype, Enumerable); Object.extend(ObjectRange.prototype, { initialize: function(start, end, exclusive) { this.start = start; this.end = end; this.exclusive = exclusive; }, _each: function(iterator) { var value = this.start; while (this.include(value)) { iterator(value); value = value.succ(); } }, include: function(value) { if (value < this.start) return false; if (this.exclusive) return value < this.end; return value <= this.end; } }); var $R = function(start, end, exclusive) { return new ObjectRange(start, end, exclusive); } var Ajax = { getTransport: function() { return Try.these( function() {return new XMLHttpRequest()}, function() {return new ActiveXObject('Msxml2.XMLHTTP')}, function() {return new ActiveXObject('Microsoft.XMLHTTP')} ) || false; }, activeRequestCount: 0 } Ajax.Responders = { responders: [], _each: function(iterator) { this.responders._each(iterator); }, register: function(responder) { if (!this.include(responder)) this.responders.push(responder); }, unregister: function(responder) { this.responders = this.responders.without(responder); }, dispatch: function(callback, request, transport, json) { this.each(function(responder) { if (typeof responder[callback] == 'function') { try { responder[callback].apply(responder, [request, transport, json]); } catch (e) {} } }); } }; Object.extend(Ajax.Responders, Enumerable); Ajax.Responders.register({ onCreate: function() { Ajax.activeRequestCount++; }, onComplete: function() { Ajax.activeRequestCount--; } }); Ajax.Base = function() {}; Ajax.Base.prototype = { setOptions: function(options) { this.options = { method: 'post', asynchronous: true, contentType: 'application/x-www-form-urlencoded', encoding: 'UTF-8', parameters: '' } Object.extend(this.options, options || {}); this.options.method = this.options.method.toLowerCase(); if (typeof this.options.parameters == 'string') this.options.parameters = this.options.parameters.toQueryParams(); } } Ajax.Request = Class.create(); Ajax.Request.Events = ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; Ajax.Request.prototype = Object.extend(new Ajax.Base(), { _complete: false, initialize: function(url, options) { this.transport = Ajax.getTransport(); this.setOptions(options); this.request(url); }, request: function(url) { this.url = url; this.method = this.options.method; var params = this.options.parameters; if (!['get', 'post'].include(this.method)) { // simulate other verbs over post params['_method'] = this.method; this.method = 'post'; } params = Hash.toQueryString(params); if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_=' // when GET, append parameters to URL if (this.method == 'get' && params) this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params; try { Ajax.Responders.dispatch('onCreate', this, this.transport); this.transport.open(this.method.toUpperCase(), this.url, this.options.asynchronous); if (this.options.asynchronous) setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10); this.transport.onreadystatechange = this.onStateChange.bind(this); this.setRequestHeaders(); var body = this.method == 'post' ? (this.options.postBody || params) : null; this.transport.send(body); /* Force Firefox to handle ready state 4 for synchronous requests */ if (!this.options.asynchronous && this.transport.overrideMimeType) this.onStateChange(); } catch (e) { this.dispatchException(e); } }, onStateChange: function() { var readyState = this.transport.readyState; if (readyState > 1 && !((readyState == 4) && this._complete)) this.respondToReadyState(this.transport.readyState); }, setRequestHeaders: function() { var headers = { 'X-Requested-With': 'XMLHttpRequest', 'X-Prototype-Version': Prototype.Version, 'Accept': 'text/javascript, text/html, application/xml, text/xml, */*' }; if (this.method == 'post') { headers['Content-type'] = this.options.contentType + (this.options.encoding ? '; charset=' + this.options.encoding : ''); /* Force "Connection: close" for older Mozilla browsers to work * around a bug where XMLHttpRequest sends an incorrect * Content-length header. See Mozilla Bugzilla #246651. */ if (this.transport.overrideMimeType && (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005) headers['Connection'] = 'close'; } // user-defined headers if (typeof this.options.requestHeaders == 'object') { var extras = this.options.requestHeaders; if (typeof extras.push == 'function') for (var i = 0, length = extras.length; i < length; i += 2) headers[extras[i]] = extras[i+1]; else $H(extras).each(function(pair) { headers[pair.key] = pair.value }); } for (var name in headers) this.transport.setRequestHeader(name, headers[name]); }, success: function() { return !this.transport.status || (this.transport.status >= 200 && this.transport.status < 300); }, respondToReadyState: function(readyState) { var state = Ajax.Request.Events[readyState]; var transport = this.transport, json = this.evalJSON(); if (state == 'Complete') { try { this._complete = true; (this.options['on' + this.transport.status] || this.options['on' + (this.success() ? 'Success' : 'Failure')] || Prototype.emptyFunction)(transport, json); } catch (e) { this.dispatchException(e); } if ((this.getHeader('Content-type') || 'text/javascript').strip(). match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i)) this.evalResponse(); } try { (this.options['on' + state] || Prototype.emptyFunction)(transport, json); Ajax.Responders.dispatch('on' + state, this, transport, json); } catch (e) { this.dispatchException(e); } if (state == 'Complete') { // avoid memory leak in MSIE: clean up this.transport.onreadystatechange = Prototype.emptyFunction; } }, getHeader: function(name) { try { return this.transport.getResponseHeader(name); } catch (e) { return null } }, evalJSON: function() { try { var json = this.getHeader('X-JSON'); return json ? eval('(' + json + ')') : null; } catch (e) { return null } }, evalResponse: function() { try { return eval(this.transport.responseText); } catch (e) { this.dispatchException(e); } }, dispatchException: function(exception) { (this.options.onException || Prototype.emptyFunction)(this, exception); Ajax.Responders.dispatch('onException', this, exception); } }); Ajax.Updater = Class.create(); Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), { initialize: function(container, url, options) { this.container = { success: (container.success || container), failure: (container.failure || (container.success ? null : container)) } this.transport = Ajax.getTransport(); this.setOptions(options); var onComplete = this.options.onComplete || Prototype.emptyFunction; this.options.onComplete = (function(transport, param) { this.updateContent(); onComplete(transport, param); }).bind(this); this.request(url); }, updateContent: function() { var receiver = this.container[this.success() ? 'success' : 'failure']; var response = this.transport.responseText; if (!this.options.evalScripts) response = response.stripScripts(); if (receiver = $E(receiver)) { if (this.options.insertion) new this.options.insertion(receiver, response); else receiver.update(response); } if (this.success()) { if (this.onComplete) setTimeout(this.onComplete.bind(this), 10); } } }); Ajax.PeriodicalUpdater = Class.create(); Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), { initialize: function(container, url, options) { this.setOptions(options); this.onComplete = this.options.onComplete; this.frequency = (this.options.frequency || 2); this.decay = (this.options.decay || 1); this.updater = {}; this.container = container; this.url = url; this.start(); }, start: function() { this.options.onComplete = this.updateComplete.bind(this); this.onTimerEvent(); }, stop: function() { this.updater.options.onComplete = undefined; clearTimeout(this.timer); (this.onComplete || Prototype.emptyFunction).apply(this, arguments); }, updateComplete: function(request) { if (this.options.decay) { this.decay = (request.responseText == this.lastText ? this.decay * this.options.decay : 1); this.lastText = request.responseText; } this.timer = setTimeout(this.onTimerEvent.bind(this), this.decay * this.frequency * 1000); }, onTimerEvent: function() { this.updater = new Ajax.Updater(this.container, this.url, this.options); } }); function $E(element) { if (arguments.length > 1) { for (var i = 0, elements = [], length = arguments.length; i < length; i++) elements.push($E(arguments[i])); return elements; } if (typeof element == 'string') element = document.getElementById(element); return Element.extend(element); } if (Prototype.BrowserFeatures.XPath) { document._getElementsByXPath = function(expression, parentElement) { var results = []; var query = document.evaluate(expression, $E(parentElement) || document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null); for (var i = 0, length = query.snapshotLength; i < length; i++) results.push(query.snapshotItem(i)); return results; }; } document.getElementsByClassName = function(className, parentElement) { if (Prototype.BrowserFeatures.XPath) { var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]"; return document._getElementsByXPath(q, parentElement); } else { var children = ($E(parentElement) || document.body).getElementsByTagName('*'); var elements = [], child; for (var i = 0, length = children.length; i < length; i++) { child = children[i]; if (Element.hasClassName(child, className)) elements.push(Element.extend(child)); } return elements; } }; /*--------------------------------------------------------------------------*/ if (!window.Element) var Element = new Object(); Element.extend = function(element) { if (!element || _nativeExtensions || element.nodeType == 3) return element; if (!element._extended && element.tagName && element != window) { var methods = Object.clone(Element.Methods), cache = Element.extend.cache; if (element.tagName == 'FORM') Object.extend(methods, Form.Methods); if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName)) Object.extend(methods, Form.Element.Methods); Object.extend(methods, Element.Methods.Simulated); for (var property in methods) { var value = methods[property]; if (typeof value == 'function' && !(property in element)) element[property] = cache.findOrStore(value); } } element._extended = true; return element; }; Element.extend.cache = { findOrStore: function(value) { return this[value] = this[value] || function() { return value.apply(null, [this].concat($A(arguments))); } } }; Element.Methods = { visible: function(element) { return $E(element).style.display != 'none'; }, toggle: function(element) { element = $E(element); Element[Element.visible(element) ? 'hide' : 'show'](element); return element; }, hide: function(element) { $E(element).style.display = 'none'; return element; }, show: function(element) { $E(element).style.display = ''; return element; }, remove: function(element) { element = $E(element); element.parentNode.removeChild(element); return element; }, update: function(element, html) { html = typeof html == 'undefined' ? '' : html.toString(); $E(element).innerHTML = html.stripScripts(); setTimeout(function() {html.evalScripts()}, 10); return element; }, replace: function(element, html) { element = $E(element); html = typeof html == 'undefined' ? '' : html.toString(); if (element.outerHTML) { element.outerHTML = html.stripScripts(); } else { var range = element.ownerDocument.createRange(); range.selectNodeContents(element); element.parentNode.replaceChild( range.createContextualFragment(html.stripScripts()), element); } setTimeout(function() {html.evalScripts()}, 10); return element; }, inspect: function(element) { element = $E(element); var result = '<' + element.tagName.toLowerCase(); $H({'id': 'id', 'className': 'class'}).each(function(pair) { var property = pair.first(), attribute = pair.last(); var value = (element[property] || '').toString(); if (value) result += ' ' + attribute + '=' + value.inspect(true); }); return result + '>'; }, recursivelyCollect: function(element, property) { element = $E(element); var elements = []; while (element = element[property]) if (element.nodeType == 1) elements.push(Element.extend(element)); return elements; }, ancestors: function(element) { return $E(element).recursivelyCollect('parentNode'); }, descendants: function(element) { return $A($E(element).getElementsByTagName('*')); }, immediateDescendants: function(element) { if (!(element = $E(element).firstChild)) return []; while (element && element.nodeType != 1) element = element.nextSibling; if (element) return [element].concat($E(element).nextSiblings()); return []; }, previousSiblings: function(element) { return $E(element).recursivelyCollect('previousSibling'); }, nextSiblings: function(element) { return $E(element).recursivelyCollect('nextSibling'); }, siblings: function(element) { element = $E(element); return element.previousSiblings().reverse().concat(element.nextSiblings()); }, match: function(element, selector) { if (typeof selector == 'string') selector = new Selector(selector); return selector.match($E(element)); }, up: function(element, expression, index) { return Selector.findElement($E(element).ancestors(), expression, index); }, down: function(element, expression, index) { return Selector.findElement($E(element).descendants(), expression, index); }, previous: function(element, expression, index) { return Selector.findElement($E(element).previousSiblings(), expression, index); }, next: function(element, expression, index) { return Selector.findElement($E(element).nextSiblings(), expression, index); }, getElementsBySelector: function() { var args = $A(arguments), element = $E(args.shift()); return Selector.findChildElements(element, args); }, getElementsByClassName: function(element, className) { return document.getElementsByClassName(className, element); }, readAttribute: function(element, name) { element = $E(element); if (document.all && !window.opera) { var t = Element._attributeTranslations; if (t.values[name]) return t.values[name](element, name); if (t.names[name]) name = t.names[name]; var attribute = element.attributes[name]; if(attribute) return attribute.nodeValue; } return element.getAttribute(name); }, getHeight: function(element) { return $E(element).getDimensions().height; }, getWidth: function(element) { return $E(element).getDimensions().width; }, classNames: function(element) { return new Element.ClassNames(element); }, hasClassName: function(element, className) { if (!(element = $E(element))) return; var elementClassName = element.className; if (elementClassName.length == 0) return false; if (elementClassName == className || elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) return true; return false; }, addClassName: function(element, className) { if (!(element = $E(element))) return; Element.classNames(element).add(className); return element; }, removeClassName: function(element, className) { if (!(element = $E(element))) return; Element.classNames(element).remove(className); return element; }, toggleClassName: function(element, className) { if (!(element = $E(element))) return; Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className); return element; }, observe: function() { Event.observe.apply(Event, arguments); return $A(arguments).first(); }, stopObserving: function() { Event.stopObserving.apply(Event, arguments); return $A(arguments).first(); }, // removes whitespace-only text node children cleanWhitespace: function(element) { element = $E(element); var node = element.firstChild; while (node) { var nextNode = node.nextSibling; if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) element.removeChild(node); node = nextNode; } return element; }, empty: function(element) { return $E(element).innerHTML.match(/^\s*$/); }, descendantOf: function(element, ancestor) { element = $E(element), ancestor = $E(ancestor); while (element = element.parentNode) if (element == ancestor) return true; return false; }, scrollTo: function(element) { element = $E(element); var pos = Position.cumulativeOffset(element); window.scrollTo(pos[0], pos[1]); return element; }, getStyle: function(element, style) { element = $E(element); if (['float','cssFloat'].include(style)) style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat'); style = style.camelize(); var value = element.style[style]; if (!value) { if (document.defaultView && document.defaultView.getComputedStyle) { var css = document.defaultView.getComputedStyle(element, null); value = css ? css[style] : null; } else if (element.currentStyle) { value = element.currentStyle[style]; } } if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none')) value = element['offset'+style.capitalize()] + 'px'; if (window.opera && ['left', 'top', 'right', 'bottom'].include(style)) if (Element.getStyle(element, 'position') == 'static') value = 'auto'; if(style == 'opacity') { if(value) return parseFloat(value); if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/)) if(value[1]) return parseFloat(value[1]) / 100; return 1.0; } return value == 'auto' ? null : value; }, setStyle: function(element, style) { element = $E(element); for (var name in style) { var value = style[name]; if(name == 'opacity') { if (value == 1) { value = (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0; if(/MSIE/.test(navigator.userAgent) && !window.opera) element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,''); } else if(value == '') { if(/MSIE/.test(navigator.userAgent) && !window.opera) element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,''); } else { if(value < 0.00001) value = 0; if(/MSIE/.test(navigator.userAgent) && !window.opera) element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') + 'alpha(opacity='+value*100+')'; } } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat'; element.style[name.camelize()] = value; } return element; }, getDimensions: function(element) { element = $E(element); var display = $E(element).getStyle('display'); if (display != 'none' && display != null) // Safari bug return {width: element.offsetWidth, height: element.offsetHeight}; // All *Width and *Height properties give 0 on elements with display none, // so enable the element temporarily var els = element.style; var originalVisibility = els.visibility; var originalPosition = els.position; var originalDisplay = els.display; els.visibility = 'hidden'; els.position = 'absolute'; els.display = 'block'; var originalWidth = element.clientWidth; var originalHeight = element.clientHeight; els.display = originalDisplay; els.position = originalPosition; els.visibility = originalVisibility; return {width: originalWidth, height: originalHeight}; }, makePositioned: function(element) { element = $E(element); var pos = Element.getStyle(element, 'position'); if (pos == 'static' || !pos) { element._madePositioned = true; element.style.position = 'relative'; // Opera returns the offset relative to the positioning context, when an // element is position relative but top and left have not been defined if (window.opera) { element.style.top = 0; element.style.left = 0; } } return element; }, undoPositioned: function(element) { element = $E(element); if (element._madePositioned) { element._madePositioned = undefined; element.style.position = element.style.top = element.style.left = element.style.bottom = element.style.right = ''; } return element; }, makeClipping: function(element) { element = $E(element); if (element._overflow) return element; element._overflow = element.style.overflow || 'auto'; if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden') element.style.overflow = 'hidden'; return element; }, undoClipping: function(element) { element = $E(element); if (!element._overflow) return element; element.style.overflow = element._overflow == 'auto' ? '' : element._overflow; element._overflow = null; return element; } }; Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf}); Element._attributeTranslations = {}; Element._attributeTranslations.names = { colspan: "colSpan", rowspan: "rowSpan", valign: "vAlign", datetime: "dateTime", accesskey: "accessKey", tabindex: "tabIndex", enctype: "encType", maxlength: "maxLength", readonly: "readOnly", longdesc: "longDesc" }; Element._attributeTranslations.values = { _getAttr: function(element, attribute) { return element.getAttribute(attribute, 2); }, _flag: function(element, attribute) { return $E(element).hasAttribute(attribute) ? attribute : null; }, style: function(element) { return element.style.cssText.toLowerCase(); }, title: function(element) { var node = element.getAttributeNode('title'); return node.specified ? node.nodeValue : null; } }; Object.extend(Element._attributeTranslations.values, { href: Element._attributeTranslations.values._getAttr, src: Element._attributeTranslations.values._getAttr, disabled: Element._attributeTranslations.values._flag, checked: Element._attributeTranslations.values._flag, readonly: Element._attributeTranslations.values._flag, multiple: Element._attributeTranslations.values._flag }); Element.Methods.Simulated = { hasAttribute: function(element, attribute) { var t = Element._attributeTranslations; attribute = t.names[attribute] || attribute; return $E(element).getAttributeNode(attribute).specified; } }; // IE is missing .innerHTML support for TABLE-related elements if (document.all && !window.opera){ Element.Methods.update = function(element, html) { element = $E(element); html = typeof html == 'undefined' ? '' : html.toString(); var tagName = element.tagName.toUpperCase(); if (['THEAD','TBODY','TR','TD'].include(tagName)) { var div = document.createElement('div'); switch (tagName) { case 'THEAD': case 'TBODY': div.innerHTML = '' + html.stripScripts() + '
    '; depth = 2; break; case 'TR': div.innerHTML = '' + html.stripScripts() + '
    '; depth = 3; break; case 'TD': div.innerHTML = '
    ' + html.stripScripts() + '
    '; depth = 4; } $A(element.childNodes).each(function(node){ element.removeChild(node) }); depth.times(function(){ div = div.firstChild }); $A(div.childNodes).each( function(node){ element.appendChild(node) }); } else { element.innerHTML = html.stripScripts(); } setTimeout(function() {html.evalScripts()}, 10); return element; } }; Object.extend(Element, Element.Methods); var _nativeExtensions = false; if(/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) { var className = 'HTML' + tag + 'Element'; if(window[className]) return; var klass = window[className] = {}; klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__; }); Element.addMethods = function(methods) { Object.extend(Element.Methods, methods || {}); function copy(methods, destination, onlyIfAbsent) { onlyIfAbsent = onlyIfAbsent || false; var cache = Element.extend.cache; for (var property in methods) { var value = methods[property]; if (!onlyIfAbsent || !(property in destination)) destination[property] = cache.findOrStore(value); } } if (typeof HTMLElement != 'undefined') { copy(Element.Methods, HTMLElement.prototype); copy(Element.Methods.Simulated, HTMLElement.prototype, true); copy(Form.Methods, HTMLFormElement.prototype); [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) { copy(Form.Element.Methods, klass.prototype); }); _nativeExtensions = true; } } var Toggle = new Object(); Toggle.display = Element.toggle; /*--------------------------------------------------------------------------*/ Abstract.Insertion = function(adjacency) { this.adjacency = adjacency; } Abstract.Insertion.prototype = { initialize: function(element, content) { this.element = $E(element); this.content = content.stripScripts(); if (this.adjacency && this.element.insertAdjacentHTML) { try { this.element.insertAdjacentHTML(this.adjacency, this.content); } catch (e) { var tagName = this.element.tagName.toUpperCase(); if (['TBODY', 'TR'].include(tagName)) { this.insertContent(this.contentFromAnonymousTable()); } else { throw e; } } } else { this.range = this.element.ownerDocument.createRange(); if (this.initializeRange) this.initializeRange(); this.insertContent([this.range.createContextualFragment(this.content)]); } setTimeout(function() {content.evalScripts()}, 10); }, contentFromAnonymousTable: function() { var div = document.createElement('div'); div.innerHTML = '' + this.content + '
    '; return $A(div.childNodes[0].childNodes[0].childNodes); } } var Insertion = new Object(); Insertion.Before = Class.create(); Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), { initializeRange: function() { this.range.setStartBefore(this.element); }, insertContent: function(fragments) { fragments.each((function(fragment) { this.element.parentNode.insertBefore(fragment, this.element); }).bind(this)); } }); Insertion.Top = Class.create(); Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), { initializeRange: function() { this.range.selectNodeContents(this.element); this.range.collapse(true); }, insertContent: function(fragments) { fragments.reverse(false).each((function(fragment) { this.element.insertBefore(fragment, this.element.firstChild); }).bind(this)); } }); Insertion.Bottom = Class.create(); Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), { initializeRange: function() { this.range.selectNodeContents(this.element); this.range.collapse(this.element); }, insertContent: function(fragments) { fragments.each((function(fragment) { this.element.appendChild(fragment); }).bind(this)); } }); Insertion.After = Class.create(); Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), { initializeRange: function() { this.range.setStartAfter(this.element); }, insertContent: function(fragments) { fragments.each((function(fragment) { this.element.parentNode.insertBefore(fragment, this.element.nextSibling); }).bind(this)); } }); /*--------------------------------------------------------------------------*/ Element.ClassNames = Class.create(); Element.ClassNames.prototype = { initialize: function(element) { this.element = $E(element); }, _each: function(iterator) { this.element.className.split(/\s+/).select(function(name) { return name.length > 0; })._each(iterator); }, set: function(className) { this.element.className = className; }, add: function(classNameToAdd) { if (this.include(classNameToAdd)) return; this.set($A(this).concat(classNameToAdd).join(' ')); }, remove: function(classNameToRemove) { if (!this.include(classNameToRemove)) return; this.set($A(this).without(classNameToRemove).join(' ')); }, toString: function() { return $A(this).join(' '); } }; Object.extend(Element.ClassNames.prototype, Enumerable); var Selector = Class.create(); Selector.prototype = { initialize: function(expression) { this.params = {classNames: []}; this.expression = expression.toString().strip(); this.parseExpression(); this.compileMatcher(); }, parseExpression: function() { function abort(message) { throw 'Parse error in selector: ' + message; } if (this.expression == '') abort('empty expression'); var params = this.params, expr = this.expression, match, modifier, clause, rest; while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) { params.attributes = params.attributes || []; params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''}); expr = match[1]; } if (expr == '*') return this.params.wildcard = true; while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) { modifier = match[1], clause = match[2], rest = match[3]; switch (modifier) { case '#': params.id = clause; break; case '.': params.classNames.push(clause); break; case '': case undefined: params.tagName = clause.toUpperCase(); break; default: abort(expr.inspect()); } expr = rest; } if (expr.length > 0) abort(expr.inspect()); }, buildMatchExpression: function() { var params = this.params, conditions = [], clause; if (params.wildcard) conditions.push('true'); if (clause = params.id) conditions.push('element.readAttribute("id") == ' + clause.inspect()); if (clause = params.tagName) conditions.push('element.tagName.toUpperCase() == ' + clause.inspect()); if ((clause = params.classNames).length > 0) for (var i = 0, length = clause.length; i < length; i++) conditions.push('element.hasClassName(' + clause[i].inspect() + ')'); if (clause = params.attributes) { clause.each(function(attribute) { var value = 'element.readAttribute(' + attribute.name.inspect() + ')'; var splitValueBy = function(delimiter) { return value + ' && ' + value + '.split(' + delimiter.inspect() + ')'; } switch (attribute.operator) { case '=': conditions.push(value + ' == ' + attribute.value.inspect()); break; case '~=': conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break; case '|=': conditions.push( splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect() ); break; case '!=': conditions.push(value + ' != ' + attribute.value.inspect()); break; case '': case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break; default: throw 'Unknown operator ' + attribute.operator + ' in selector'; } }); } return conditions.join(' && '); }, compileMatcher: function() { this.match = new Function('element', 'if (!element.tagName) return false; \ element = $E(element); \ return ' + this.buildMatchExpression()); }, findElements: function(scope) { var element; if (element = $E(this.params.id)) if (this.match(element)) if (!scope || Element.childOf(element, scope)) return [element]; scope = (scope || document).getElementsByTagName(this.params.tagName || '*'); var results = []; for (var i = 0, length = scope.length; i < length; i++) if (this.match(element = scope[i])) results.push(Element.extend(element)); return results; }, toString: function() { return this.expression; } } Object.extend(Selector, { matchElements: function(elements, expression) { var selector = new Selector(expression); return elements.select(selector.match.bind(selector))._map(Element.extend); }, findElement: function(elements, expression, index) { if (typeof expression == 'number') index = expression, expression = false; return Selector.matchElements(elements, expression || '*')[index || 0]; }, findChildElements: function(element, expressions) { return expressions._map(function(expression) { return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) { var selector = new Selector(expr); return results.inject([], function(elements, result) { return elements.concat(selector.findElements(result || element)); }); }); }).flatten(); } }); function $$E() { return Selector.findChildElements(document, $A(arguments)); } var Form = { reset: function(form) { $E(form).reset(); return form; }, serializeElements: function(elements, getHash) { var data = elements.inject({}, function(result, element) { if (!element.disabled && element.name) { var key = element.name, value = $E(element).getValue(); if (value != undefined) { if (result[key]) { if (result[key].constructor != Array) result[key] = [result[key]]; result[key].push(value); } else result[key] = value; } } return result; }); return getHash ? data : Hash.toQueryString(data); } }; Form.Methods = { serialize: function(form, getHash) { return Form.serializeElements(Form.getElements(form), getHash); }, getElements: function(form) { return $A($E(form).getElementsByTagName('*')).inject([], function(elements, child) { if (Form.Element.Serializers[child.tagName.toLowerCase()]) elements.push(Element.extend(child)); return elements; } ); }, getInputs: function(form, typeName, name) { form = $E(form); var inputs = form.getElementsByTagName('input'); if (!typeName && !name) return $A(inputs)._map(Element.extend); for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) { var input = inputs[i]; if ((typeName && input.type != typeName) || (name && input.name != name)) continue; matchingInputs.push(Element.extend(input)); } return matchingInputs; }, disable: function(form) { form = $E(form); form.getElements().each(function(element) { element.blur(); element.disabled = 'true'; }); return form; }, enable: function(form) { form = $E(form); form.getElements().each(function(element) { element.disabled = ''; }); return form; }, findFirstElement: function(form) { return $E(form).getElements().find(function(element) { return element.type != 'hidden' && !element.disabled && ['input', 'select', 'textarea'].include(element.tagName.toLowerCase()); }); }, focusFirstElement: function(form) { form = $E(form); form.findFirstElement().activate(); return form; } } Object.extend(Form, Form.Methods); /*--------------------------------------------------------------------------*/ Form.Element = { focus: function(element) { $E(element).focus(); return element; }, select: function(element) { $E(element).select(); return element; } } Form.Element.Methods = { serialize: function(element) { element = $E(element); if (!element.disabled && element.name) { var value = element.getValue(); if (value != undefined) { var pair = {}; pair[element.name] = value; return Hash.toQueryString(pair); } } return ''; }, getValue: function(element) { element = $E(element); var method = element.tagName.toLowerCase(); return Form.Element.Serializers[method](element); }, clear: function(element) { $E(element).value = ''; return element; }, present: function(element) { return $E(element).value != ''; }, activate: function(element) { element = $E(element); element.focus(); if (element.select && ( element.tagName.toLowerCase() != 'input' || !['button', 'reset', 'submit'].include(element.type) ) ) element.select(); return element; }, disable: function(element) { element = $E(element); element.disabled = true; return element; }, enable: function(element) { element = $E(element); element.blur(); element.disabled = false; return element; } } Object.extend(Form.Element, Form.Element.Methods); var Field = Form.Element; var $F = Form.Element.getValue; /*--------------------------------------------------------------------------*/ Form.Element.Serializers = { input: function(element) { switch (element.type.toLowerCase()) { case 'checkbox': case 'radio': return Form.Element.Serializers.inputSelector(element); default: return Form.Element.Serializers.textarea(element); } }, inputSelector: function(element) { return element.checked ? element.value : null; }, textarea: function(element) { return element.value; }, select: function(element) { return this[element.type == 'select-one' ? 'selectOne' : 'selectMany'](element); }, selectOne: function(element) { var index = element.selectedIndex; return index >= 0 ? this.optionValue(element.options[index]) : null; }, selectMany: function(element) { var values, length = element.length; if (!length) return null; for (var i = 0, values = []; i < length; i++) { var opt = element.options[i]; if (opt.selected) values.push(this.optionValue(opt)); } return values; }, optionValue: function(opt) { // extend element because hasAttribute may not be native return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; } } /*--------------------------------------------------------------------------*/ Abstract.TimedObserver = function() {} Abstract.TimedObserver.prototype = { initialize: function(element, frequency, callback) { this.frequency = frequency; this.element = $E(element); this.callback = callback; this.lastValue = this.getValue(); this.registerCallback(); }, registerCallback: function() { setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); }, onTimerEvent: function() { var value = this.getValue(); var changed = ('string' == typeof this.lastValue && 'string' == typeof value ? this.lastValue != value : String(this.lastValue) != String(value)); if (changed) { this.callback(this.element, value); this.lastValue = value; } } } Form.Element.Observer = Class.create(); Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { getValue: function() { return Form.Element.getValue(this.element); } }); Form.Observer = Class.create(); Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { getValue: function() { return Form.serialize(this.element); } }); /*--------------------------------------------------------------------------*/ Abstract.EventObserver = function() {} Abstract.EventObserver.prototype = { initialize: function(element, callback) { this.element = $E(element); this.callback = callback; this.lastValue = this.getValue(); if (this.element.tagName.toLowerCase() == 'form') this.registerFormCallbacks(); else this.registerCallback(this.element); }, onElementEvent: function() { var value = this.getValue(); if (this.lastValue != value) { this.callback(this.element, value); this.lastValue = value; } }, registerFormCallbacks: function() { Form.getElements(this.element).each(this.registerCallback.bind(this)); }, registerCallback: function(element) { if (element.type) { switch (element.type.toLowerCase()) { case 'checkbox': case 'radio': Event.observe(element, 'click', this.onElementEvent.bind(this)); break; default: Event.observe(element, 'change', this.onElementEvent.bind(this)); break; } } } } Form.Element.EventObserver = Class.create(); Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { getValue: function() { return Form.Element.getValue(this.element); } }); Form.EventObserver = Class.create(); Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { getValue: function() { return Form.serialize(this.element); } }); if (!window.Event) { var Event = new Object(); } Object.extend(Event, { KEY_BACKSPACE: 8, KEY_TAB: 9, KEY_RETURN: 13, KEY_ESC: 27, KEY_LEFT: 37, KEY_UP: 38, KEY_RIGHT: 39, KEY_DOWN: 40, KEY_DELETE: 46, KEY_HOME: 36, KEY_END: 35, KEY_PAGEUP: 33, KEY_PAGEDOWN: 34, element: function(event) { return event.target || event.srcElement; }, isLeftClick: function(event) { return (((event.which) && (event.which == 1)) || ((event.button) && (event.button == 1))); }, pointerX: function(event) { return event.pageX || (event.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)); }, pointerY: function(event) { return event.pageY || (event.clientY + (document.documentElement.scrollTop || document.body.scrollTop)); }, stop: function(event) { if (event.preventDefault) { event.preventDefault(); event.stopPropagation(); } else { event.returnValue = false; event.cancelBubble = true; } }, // find the first node with the given tagName, starting from the // node the event was triggered on; traverses the DOM upwards findElement: function(event, tagName) { var element = Event.element(event); while (element.parentNode && (!element.tagName || (element.tagName.toUpperCase() != tagName.toUpperCase()))) element = element.parentNode; return element; }, observers: false, _observeAndCache: function(element, name, observer, useCapture) { if (!this.observers) this.observers = []; if (element.addEventListener) { this.observers.push([element, name, observer, useCapture]); element.addEventListener(name, observer, useCapture); } else if (element.attachEvent) { this.observers.push([element, name, observer, useCapture]); element.attachEvent('on' + name, observer); } }, unloadCache: function() { if (!Event.observers) return; for (var i = 0, length = Event.observers.length; i < length; i++) { Event.stopObserving.apply(this, Event.observers[i]); Event.observers[i][0] = null; } Event.observers = false; }, observe: function(element, name, observer, useCapture) { element = $E(element); useCapture = useCapture || false; if (name == 'keypress' && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || element.attachEvent)) name = 'keydown'; Event._observeAndCache(element, name, observer, useCapture); }, stopObserving: function(element, name, observer, useCapture) { element = $E(element); useCapture = useCapture || false; if (name == 'keypress' && (navigator.appVersion.match(/Konqueror|Safari|KHTML/) || element.detachEvent)) name = 'keydown'; if (element.removeEventListener) { element.removeEventListener(name, observer, useCapture); } else if (element.detachEvent) { try { element.detachEvent('on' + name, observer); } catch (e) {} } } }); /* prevent memory leaks in IE */ if (navigator.appVersion.match(/\bMSIE\b/)) Event.observe(window, 'unload', Event.unloadCache, false); var Position = { // set to true if needed, warning: firefox performance problems // NOT neeeded for page scrolling, only if draggable contained in // scrollable elements includeScrollOffsets: false, // must be called before calling withinIncludingScrolloffset, every time the // page is scrolled prepare: function() { this.deltaX = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0; this.deltaY = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0; }, realOffset: function(element) { var valueT = 0, valueL = 0; do { valueT += element.scrollTop || 0; valueL += element.scrollLeft || 0; element = element.parentNode; } while (element); return [valueL, valueT]; }, cumulativeOffset: function(element) { var valueT = 0, valueL = 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; } while (element); return [valueL, valueT]; }, positionedOffset: function(element) { var valueT = 0, valueL = 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; element = element.offsetParent; if (element) { if(element.tagName=='BODY') break; var p = Element.getStyle(element, 'position'); if (p == 'relative' || p == 'absolute') break; } } while (element); return [valueL, valueT]; }, offsetParent: function(element) { if (element.offsetParent) return element.offsetParent; if (element == document.body) return element; while ((element = element.parentNode) && element != document.body) if (Element.getStyle(element, 'position') != 'static') return element; return document.body; }, // caches x/y coordinate pair to use with overlap within: function(element, x, y) { if (this.includeScrollOffsets) return this.withinIncludingScrolloffsets(element, x, y); this.xcomp = x; this.ycomp = y; this.offset = this.cumulativeOffset(element); return (y >= this.offset[1] && y < this.offset[1] + element.offsetHeight && x >= this.offset[0] && x < this.offset[0] + element.offsetWidth); }, withinIncludingScrolloffsets: function(element, x, y) { var offsetcache = this.realOffset(element); this.xcomp = x + offsetcache[0] - this.deltaX; this.ycomp = y + offsetcache[1] - this.deltaY; this.offset = this.cumulativeOffset(element); return (this.ycomp >= this.offset[1] && this.ycomp < this.offset[1] + element.offsetHeight && this.xcomp >= this.offset[0] && this.xcomp < this.offset[0] + element.offsetWidth); }, // within must be called directly before overlap: function(mode, element) { if (!mode) return 0; if (mode == 'vertical') return ((this.offset[1] + element.offsetHeight) - this.ycomp) / element.offsetHeight; if (mode == 'horizontal') return ((this.offset[0] + element.offsetWidth) - this.xcomp) / element.offsetWidth; }, page: function(forElement) { var valueT = 0, valueL = 0; var element = forElement; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; // Safari fix if (element.offsetParent==document.body) if (Element.getStyle(element,'position')=='absolute') break; } while (element = element.offsetParent); element = forElement; do { if (!window.opera || element.tagName=='BODY') { valueT -= element.scrollTop || 0; valueL -= element.scrollLeft || 0; } } while (element = element.parentNode); return [valueL, valueT]; }, clone: function(source, target) { var options = Object.extend({ setLeft: true, setTop: true, setWidth: true, setHeight: true, offsetTop: 0, offsetLeft: 0 }, arguments[2] || {}) // find page position of source source = $E(source); var p = Position.page(source); // find coordinate system to use target = $E(target); var delta = [0, 0]; var parent = null; // delta [0,0] will do fine with position: fixed elements, // position:absolute needs offsetParent deltas if (Element.getStyle(target,'position') == 'absolute') { parent = Position.offsetParent(target); delta = Position.page(parent); } // correct by body offsets (fixes Safari) if (parent == document.body) { delta[0] -= document.body.offsetLeft; delta[1] -= document.body.offsetTop; } // set position if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; if(options.setWidth) target.style.width = source.offsetWidth + 'px'; if(options.setHeight) target.style.height = source.offsetHeight + 'px'; }, absolutize: function(element) { element = $E(element); if (element.style.position == 'absolute') return; Position.prepare(); var offsets = Position.positionedOffset(element); var top = offsets[1]; var left = offsets[0]; var width = element.clientWidth; var height = element.clientHeight; element._originalLeft = left - parseFloat(element.style.left || 0); element._originalTop = top - parseFloat(element.style.top || 0); element._originalWidth = element.style.width; element._originalHeight = element.style.height; element.style.position = 'absolute'; element.style.top = top + 'px'; element.style.left = left + 'px'; element.style.width = width + 'px'; element.style.height = height + 'px'; }, relativize: function(element) { element = $E(element); if (element.style.position == 'relative') return; Position.prepare(); element.style.position = 'relative'; var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); element.style.top = top + 'px'; element.style.left = left + 'px'; element.style.height = element._originalHeight; element.style.width = element._originalWidth; } } // Safari returns margins on body which is incorrect if the child is absolutely // positioned. For performance reasons, redefine Position.cumulativeOffset for // KHTML/WebKit only. if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) { Position.cumulativeOffset = function(element) { var valueT = 0, valueL = 0; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; if (element.offsetParent == document.body) if (Element.getStyle(element, 'position') == 'absolute') break; element = element.offsetParent; } while (element); return [valueL, valueT]; } } Element.addMethods();// From http://www.quirksmode.org/js/detect.html var detect = navigator.userAgent.toLowerCase(); var OS,browser,version,total,thestring; if (checkIt('konqueror')) { browser = "Konqueror"; OS = "Linux"; } else if (checkIt('safari')) browser = "Safari" else if (checkIt('omniweb')) browser = "OmniWeb" else if (checkIt('opera')) browser = "Opera" else if (checkIt('webtv')) browser = "WebTV"; else if (checkIt('icab')) browser = "iCab" else if (checkIt('msie')) browser = "IE" else if (!checkIt('compatible')) { browser = "Netscape" version = detect.charAt(8); } else browser = "An unknown browser"; if (!version) version = detect.charAt(place + thestring.length); if (!OS) { if (checkIt('linux')) OS = "Linux"; else if (checkIt('x11')) OS = "Unix"; else if (checkIt('mac')) OS = "Mac" else if (checkIt('win')) OS = "Windows" else OS = "an unknown operating system"; } function checkIt(string) { place = detect.indexOf(string) + 1; thestring = string; return place; } function tgbase32todec(_base32) { var alphabets = "abcdefghijklmnopqrstuvwxyz234567"; _base32 = _base32.toLowerCase(); var i; var result = 0; var digit = 0; for (i = _base32.length-1; i>=0; i--) { var val = alphabets.indexOf(_base32.charAt(i)); if (val == -1) { return -1; } result += Math.pow(32,digit)*val; digit++; } return result; } function tgdectobase32(_dec) { var alphabets = "abcdefghijklmnopqrstuvwxyz234567"; if (_dec <= 0 ) { return ""; } var result = ""; while ( _dec > 0 ) { var modresult = _dec % 32; result = alphabets.charAt(modresult) + result; _dec = parseInt(_dec / 32); } return result.toUpperCase(); } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Latitude/longitude spherical geodesy formulae & scripts (c) Chris Veness 2002-2010 */ /* - www.movable-type.co.uk/scripts/latlong.html */ /* */ /* Sample usage: */ /* var p1 = new LatLon(51.5136, -0.0983); */ /* var p2 = new LatLon(51.4778, -0.0015); */ /* var dist = p1.distanceTo(p2); // in km */ /* var brng = p1.bearingTo(p2); // in degrees clockwise from north */ /* ... etc */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Note that minimal error checking is performed in this example code! */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** * Creates a point on the earth's surface at the supplied latitude / longitude * * @constructor * @param {Number} lat: latitude in numeric degrees * @param {Number} lon: longitude in numeric degrees * @param {Number} [rad=6371]: radius of earth if different value is required from standard 6,371km */ function LatLon(lat, lon, rad) { if (typeof rad == 'undefined') rad = 6371; // earth's mean radius in km this._lat = lat; this._lon = lon; this._radius = rad; } /** * Returns the distance from this point to the supplied point, in km * (using Haversine formula) * * from: Haversine formula - R. W. Sinnott, "Virtues of the Haversine", * Sky and Telescope, vol 68, no 2, 1984 * * @param {LatLon} point: Latitude/longitude of destination point * @param {Number} [precision=4]: no of significant digits to use for returned value * @returns {Number} Distance in km between this point and destination point */ LatLon.prototype.distanceTo = function(point, precision) { // default 4 sig figs reflects typical 0.3% accuracy of spherical model if (typeof precision == 'undefined') precision = 4; var R = this._radius; var lat1 = this._lat.toRad(), lon1 = this._lon.toRad(); var lat2 = point._lat.toRad(), lon2 = point._lon.toRad(); var dLat = lat2 - lat1; var dLon = lon2 - lon1; var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon/2) * Math.sin(dLon/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); var d = R * c; return d.toPrecisionFixed(precision); } /** * Returns the (initial) bearing from this point to the supplied point, in degrees * see http://williams.best.vwh.net/avform.htm#Crs * * @param {LatLon} point: Latitude/longitude of destination point * @returns {Number} Initial bearing in degrees from North */ LatLon.prototype.bearingTo = function(point) { var lat1 = this._lat.toRad(), lat2 = point._lat.toRad(); var dLon = (point._lon-this._lon).toRad(); var y = Math.sin(dLon) * Math.cos(lat2); var x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon); var brng = Math.atan2(y, x); return (brng.toDeg()+360) % 360; } /** * Returns final bearing arriving at supplied destination point from this point; the final bearing * will differ from the initial bearing by varying degrees according to distance and latitude * * @param {LatLon} point: Latitude/longitude of destination point * @returns {Number} Final bearing in degrees from North */ LatLon.prototype.finalBearingTo = function(point) { // get initial bearing from supplied point back to this point... var lat1 = point._lat.toRad(), lat2 = this._lat.toRad(); var dLon = (this._lon-point._lon).toRad(); var y = Math.sin(dLon) * Math.cos(lat2); var x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon); var brng = Math.atan2(y, x); // ... & reverse it by adding 180 return (brng.toDeg()+180) % 360; } /** * Returns the midpoint between this point and the supplied point. * see http://mathforum.org/library/drmath/view/51822.html for derivation * * @param {LatLon} point: Latitude/longitude of destination point * @returns {LatLon} Midpoint between this point and the supplied point */ LatLon.prototype.midpointTo = function(point) { lat1 = this._lat.toRad(), lon1 = this._lon.toRad(); lat2 = point._lat.toRad(); var dLon = (point._lon-this._lon).toRad(); var Bx = Math.cos(lat2) * Math.cos(dLon); var By = Math.cos(lat2) * Math.sin(dLon); lat3 = Math.atan2(Math.sin(lat1)+Math.sin(lat2), Math.sqrt( (Math.cos(lat1)+Bx)*(Math.cos(lat1)+Bx) + By*By) ); lon3 = lon1 + Math.atan2(By, Math.cos(lat1) + Bx); return new LatLon(lat3.toDeg(), lon3.toDeg()); } /** * Returns the destination point from this point having travelled the given distance (in km) on the * given initial bearing (bearing may vary before destination is reached) * * see http://williams.best.vwh.net/avform.htm#LL * * @param {Number} brng: Initial bearing in degrees * @param {Number} dist: Distance in km * @returns {LatLon} Destination point */ LatLon.prototype.destinationPoint = function(brng, dist) { dist = dist/this._radius; // convert dist to angular distance in radians brng = brng.toRad(); // var lat1 = this._lat.toRad(), lon1 = this._lon.toRad(); var lat2 = Math.asin( Math.sin(lat1)*Math.cos(dist) + Math.cos(lat1)*Math.sin(dist)*Math.cos(brng) ); var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(dist)*Math.cos(lat1), Math.cos(dist)-Math.sin(lat1)*Math.sin(lat2)); lon2 = (lon2+3*Math.PI)%(2*Math.PI) - Math.PI; // normalise to -180...+180 if (isNaN(lat2) || isNaN(lon2)) return null; return new LatLon(lat2.toDeg(), lon2.toDeg()); } /** * Returns the point of intersection of two paths defined by point and bearing * * see http://williams.best.vwh.net/avform.htm#Intersection * * @param {LatLon} p1: First point * @param {Number} brng1: Initial bearing from first point * @param {LatLon} p2: Second point * @param {Number} brng2: Initial bearing from second point * @returns {LatLon} Destination point (null if no unique intersection defined) */ LatLon.intersection = function(p1, brng1, p2, brng2) { lat1 = p1._lat.toRad(), lon1 = p1._lon.toRad(); lat2 = p2._lat.toRad(), lon2 = p2._lon.toRad(); brng13 = brng1.toRad(), brng23 = brng2.toRad(); dLat = lat2-lat1, dLon = lon2-lon1; dist12 = 2*Math.asin( Math.sqrt( Math.sin(dLat/2)*Math.sin(dLat/2) + Math.cos(lat1)*Math.cos(lat2)*Math.sin(dLon/2)*Math.sin(dLon/2) ) ); if (dist12 == 0) return null; // initial/final bearings between points brngA = Math.acos( ( Math.sin(lat2) - Math.sin(lat1)*Math.cos(dist12) ) / ( Math.sin(dist12)*Math.cos(lat1) ) ); if (isNaN(brngA)) brngA = 0; // protect against rounding brngB = Math.acos( ( Math.sin(lat1) - Math.sin(lat2)*Math.cos(dist12) ) / ( Math.sin(dist12)*Math.cos(lat2) ) ); if (Math.sin(lon2-lon1) > 0) { brng12 = brngA; brng21 = 2*Math.PI - brngB; } else { brng12 = 2*Math.PI - brngA; brng21 = brngB; } alpha1 = (brng13 - brng12 + Math.PI) % (2*Math.PI) - Math.PI; // angle 2-1-3 alpha2 = (brng21 - brng23 + Math.PI) % (2*Math.PI) - Math.PI; // angle 1-2-3 if (Math.sin(alpha1)==0 && Math.sin(alpha2)==0) return null; // infinite intersections if (Math.sin(alpha1)*Math.sin(alpha2) < 0) return null; // ambiguous intersection //alpha1 = Math.abs(alpha1); //alpha2 = Math.abs(alpha2); // ... Ed Williams takes abs of alpha1/alpha2, but seems to break calculation? alpha3 = Math.acos( -Math.cos(alpha1)*Math.cos(alpha2) + Math.sin(alpha1)*Math.sin(alpha2)*Math.cos(dist12) ); dist13 = Math.atan2( Math.sin(dist12)*Math.sin(alpha1)*Math.sin(alpha2), Math.cos(alpha2)+Math.cos(alpha1)*Math.cos(alpha3) ) lat3 = Math.asin( Math.sin(lat1)*Math.cos(dist13) + Math.cos(lat1)*Math.sin(dist13)*Math.cos(brng13) ); dLon13 = Math.atan2( Math.sin(brng13)*Math.sin(dist13)*Math.cos(lat1), Math.cos(dist13)-Math.sin(lat1)*Math.sin(lat3) ); lon3 = lon1+dLon13; lon3 = (lon3+Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..180 return new LatLon(lat3.toDeg(), lon3.toDeg()); } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** * Returns the distance from this point to the supplied point, in km, travelling along a rhumb line * * see http://williams.best.vwh.net/avform.htm#Rhumb * * @param {LatLon} point: Latitude/longitude of destination point * @returns {Number} Distance in km between this point and destination point */ LatLon.prototype.rhumbDistanceTo = function(point) { var R = this._radius; var lat1 = this._lat.toRad(), lat2 = point._lat.toRad(); var dLat = (point._lat-this._lat).toRad(); var dLon = Math.abs(point._lon-this._lon).toRad(); var dPhi = Math.log(Math.tan(lat2/2+Math.PI/4)/Math.tan(lat1/2+Math.PI/4)); var q = (!isNaN(dLat/dPhi)) ? dLat/dPhi : Math.cos(lat1); // E-W line gives dPhi=0 // if dLon over 180 take shorter rhumb across 180 meridian: if (dLon > Math.PI) dLon = 2*Math.PI - dLon; var dist = Math.sqrt(dLat*dLat + q*q*dLon*dLon) * R; return dist.toPrecisionFixed(4); // 4 sig figs reflects typical 0.3% accuracy of spherical model } /** * Returns the bearing from this point to the supplied point along a rhumb line, in degrees * * @param {LatLon} point: Latitude/longitude of destination point * @returns {Number} Bearing in degrees from North */ LatLon.prototype.rhumbBearingTo = function(point) { var lat1 = this._lat.toRad(), lat2 = point._lat.toRad(); var dLon = (point._lon-this._lon).toRad(); var dPhi = Math.log(Math.tan(lat2/2+Math.PI/4)/Math.tan(lat1/2+Math.PI/4)); if (Math.abs(dLon) > Math.PI) dLon = dLon>0 ? -(2*Math.PI-dLon) : (2*Math.PI+dLon); var brng = Math.atan2(dLon, dPhi); return (brng.toDeg()+360) % 360; } /** * Returns the destination point from this point having travelled the given distance (in km) on the * given bearing along a rhumb line * * @param {Number} brng: Bearing in degrees from North * @param {Number} dist: Distance in km * @returns {LatLon} Destination point */ LatLon.prototype.rhumbDestinationPoint = function(brng, dist) { var R = this._radius; var d = parseFloat(dist)/R; // d = angular distance covered on earth's surface var lat1 = this._lat.toRad(), lon1 = this._lon.toRad(); brng = brng.toRad(); var lat2 = lat1 + d*Math.cos(brng); var dLat = lat2-lat1; var dPhi = Math.log(Math.tan(lat2/2+Math.PI/4)/Math.tan(lat1/2+Math.PI/4)); var q = (!isNaN(dLat/dPhi)) ? dLat/dPhi : Math.cos(lat1); // E-W line gives dPhi=0 var dLon = d*Math.sin(brng)/q; // check for some daft bugger going past the pole if (Math.abs(lat2) > Math.PI/2) lat2 = lat2>0 ? Math.PI-lat2 : -(Math.PI-lat2); lon2 = (lon1+dLon+3*Math.PI)%(2*Math.PI) - Math.PI; return new LatLon(lat2.toDeg(), lon2.toDeg()); } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /** * Returns the latitude of this point; signed numeric degrees if no format, otherwise format & dp * as per Geo.toLat() * * @param {String} [format]: Return value as 'd', 'dm', 'dms' * @param {Number} [dp=0|2|4]: No of decimal places to display * @returns {Number|String} Numeric degrees if no format specified, otherwise deg/min/sec * * @requires Geo */ LatLon.prototype.lat = function(format, dp) { if (typeof format == 'undefined') return this._lat; return Geo.toLat(this._lat, format, dp); } /** * Returns the longitude of this point; signed numeric degrees if no format, otherwise format & dp * as per Geo.toLon() * * @param {String} [format]: Return value as 'd', 'dm', 'dms' * @param {Number} [dp=0|2|4]: No of decimal places to display * @returns {Number|String} Numeric degrees if no format specified, otherwise deg/min/sec * * @requires Geo */ LatLon.prototype.lon = function(format, dp) { if (typeof format == 'undefined') return this._lon; return Geo.toLon(this._lon, format, dp); } /** * Returns a string representation of this point; format and dp as per lat()/lon() * * @param {String} [format]: Return value as 'd', 'dm', 'dms' * @param {Number} [dp=0|2|4]: No of decimal places to display * @returns {String} Comma-separated latitude/longitude * * @requires Geo */ LatLon.prototype.toString = function(format, dp) { if (typeof format == 'undefined') format = 'dms'; return Geo.toLat(this._lat, format, dp) + ', ' + Geo.toLon(this._lon, format, dp); } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ // extend Number object with methods for converting degrees/radians /** Convert numeric degrees to radians */ if (typeof(String.prototype.toRad) === "undefined") { Number.prototype.toRad = function() { return this * Math.PI / 180; } } /** Convert radians to numeric (signed) degrees */ if (typeof(String.prototype.toDeg) === "undefined") { Number.prototype.toDeg = function() { return this * 180 / Math.PI; } } /** * Format the significant digits of a number, using only fixed-point notation (no exponential) * * @param {Number} precision: Number of significant digits to appear in the returned string * @returns {String} A string representation of number which contains precision significant digits */ if (typeof(Number.prototype.toPrecisionFixed) === "undefined") { Number.prototype.toPrecisionFixed = function(precision) { var numb = this < 0 ? -this : this; // can't take log of -ve number... var sign = this < 0 ? '-' : ''; if (numb == 0) { n = '0.'; while (precision--) n += '0'; return n }; // can't take log of zero var scale = Math.ceil(Math.log(numb)*Math.LOG10E); // no of digits before decimal var n = String(Math.round(numb * Math.pow(10, precision-scale))); if (scale > 0) { // add trailing zeros & insert decimal as required l = scale - n.length; while (l-- > 0) n = n + '0'; if (scale < n.length) n = n.slice(0,scale) + '.' + n.slice(scale); } else { // prefix decimal and leading zeros if required while (scale++ < 0) n = '0' + n; n = '0.' + n; } return sign + n; } } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /* Geodesy representation conversion functions (c) Chris Veness 2002-2010 */ /* - www.movable-type.co.uk/scripts/latlong.html */ /* */ /* Sample usage: */ /* var lat = Geo.parseDMS(' 51 28 40.12 N'); */ /* var lon = Geo.parseDMS('000 00 05.31 W'); */ /* var p1 = new LatLon(lat, lon); */ /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ var Geo = {}; // Geo namespace, representing static class /** * Parses string representing degrees/minutes/seconds into numeric degrees * * This is very flexible on formats, allowing signed decimal degrees, or deg-min-sec optionally * suffixed by compass direction (NSEW). A variety of separators are accepted (eg 3 37' 09"W) * or fixed-width format without separators (eg 0033709W). Seconds and minutes may be omitted. * (Note minimal validation is done). * * @param {String|Number} dmsStr: Degrees or deg/min/sec in variety of formats * @returns {Number} Degrees as decimal number * @throws {TypeError} dmsStr is an object, perhaps DOM object without .value? */ Geo.parseDMS = function(dmsStr) { if (typeof deg == 'object') throw new TypeError('Geo.parseDMS - dmsStr is [DOM?] object'); if (!isNaN(dmsStr)) return Number(dmsStr); // ... signed decimal degrees without NSEW // strip off any sign or compass dir'n & split out separate d/m/s var dms = String(dmsStr).trim().replace(/^-/,'').replace(/[NSEW]$/i,'').split(/[^0-9.,]+/); if (dms[dms.length-1]=='') dms.splice(dms.length-1); // from trailing symbol if (dms == '') return NaN; // and convert to decimal degrees... switch (dms.length) { case 3: // interpret 3-part result as d/m/s var deg = dms[0]/1 + dms[1]/60 + dms[2]/3600; break; case 2: // interpret 2-part result as d/m var deg = dms[0]/1 + dms[1]/60; break; case 1: // just d (possibly decimal) or non-separated dddmmss var deg = dms[0]; // check for fixed-width unseparated format eg 0033709W if (/[NS]/i.test(dmsStr)) deg = '0' + deg; // - normalise N/S to 3-digit degrees if (/[0-9]{7}/.test(deg)) deg = deg.slice(0,3)/1 + deg.slice(3,5)/60 + deg.slice(5)/3600; break; default: return NaN; } if (/^-|[WS]$/i.test(dmsStr.trim())) deg = -deg; // take '-', west and south as -ve return Number(deg); } /** * Convert decimal degrees to deg/min/sec format * - degree, prime, double-prime symbols are added, but sign is discarded, though no compass * direction is added * * @private * @param {Number} deg: Degrees * @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' * @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d * @returns {String} deg formatted as deg/min/secs according to specified format * @throws {TypeError} deg is an object, perhaps DOM object without .value? */ Geo.toDMS = function(deg, format, dp) { if (typeof deg == 'object') throw new TypeError('Geo.toDMS - deg is [DOM?] object'); if (isNaN(deg)) return ''; // give up here if we can't make a number from deg // default values if (typeof format == 'undefined') format = 'dms'; if (typeof dp == 'undefined') { switch (format) { case 'd': dp = 4; break; case 'dm': dp = 2; break; case 'dms': dp = 0; break; default: format = 'dms'; dp = 0; // be forgiving on invalid format } } deg = Math.abs(deg); // (unsigned result ready for appending compass dir'n) switch (format) { case 'd': d = deg.toFixed(dp); // round degrees if (d<100) d = '0' + d; // pad with leading zeros if (d<10) d = '0' + d; dms = d + '\u00B0'; // add symbol break; case 'dm': var min = (deg*60).toFixed(dp); // convert degrees to minutes & round var d = Math.floor(min / 60); // get component deg/min var m = (min % 60).toFixed(dp); // pad with trailing zeros if (d<100) d = '0' + d; // pad with leading zeros if (d<10) d = '0' + d; if (m<10) m = '0' + m; dms = d + '\u00B0' + m + '\u2032'; // add , ' symbols break; case 'dms': var sec = (deg*3600).toFixed(dp); // convert degrees to seconds & round var d = Math.floor(sec / 3600); // get component deg/min/sec var m = Math.floor(sec/60) % 60; var s = (sec % 60).toFixed(dp); // pad with trailing zeros if (d<100) d = '0' + d; // pad with leading zeros if (d<10) d = '0' + d; if (m<10) m = '0' + m; if (s<10) s = '0' + s; dms = d + '\u00B0' + m + '\u2032' + s + '\u2033'; // add , ', " symbols break; } return dms; } /** * Convert numeric degrees to deg/min/sec latitude (suffixed with N/S) * * @param {Number} deg: Degrees * @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' * @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d * @returns {String} Deg/min/seconds */ Geo.toLat = function(deg, format, dp) { var lat = Geo.toDMS(deg, format, dp); return lat=='' ? '' : lat.slice(1) + (deg<0 ? 'S' : 'N'); // knock off initial '0' for lat! } /** * Convert numeric degrees to deg/min/sec longitude (suffixed with E/W) * * @param {Number} deg: Degrees * @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' * @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d * @returns {String} Deg/min/seconds */ Geo.toLon = function(deg, format, dp) { var lon = Geo.toDMS(deg, format, dp); return lon=='' ? '' : lon + (deg<0 ? 'W' : 'E'); } /** * Convert numeric degrees to deg/min/sec as a bearing (0..360) * * @param {Number} deg: Degrees * @param {String} [format=dms]: Return value as 'd', 'dm', 'dms' * @param {Number} [dp=0|2|4]: No of decimal places to use - default 0 for dms, 2 for dm, 4 for d * @returns {String} Deg/min/seconds */ Geo.toBrng = function(deg, format, dp) { deg = (Number(deg)+360) % 360; // normalise -ve values to 180..360 var brng = Geo.toDMS(deg, format, dp); return brng.replace('360', '0'); // just in case rounding took us up to 360! } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /// /// A UTM -> Lat/Long (or vice versa) converter adapted from the script used at /// http://www.uwgb.edu/dutchs/UsefulData/ConvertUTMNoOZ.HTM /// I've taken the calculations portion of his script and turned it into a singleton /// javascript object so that it is no longer dependent on the controls used on the page /// to use this script, call setDatum with the index of the datum to be used and then /// call the various conversion functions latLngToUtm(), utmToLatLng() or natoToLatLng(), utmToNato(), natoToUtm() /// to convert between the various coordinate systems, hopefully accurately! /// /// NOTE: no attempt is made to compensate for the irregular grid in the area around the southern coast of Norway and /// Svalbard (zones 32V and 31X, 33X, 35X and 37X) because of this results returned for NATO coordinates for lat/lng or /// UTM values located in these regions will not be correct. /// var utmconv = { // // constants taken from or calculated from the datum // a: 0, // equatorial radius in meters f: 0, // polar flattening b: 0, // polar radius in meters e: 0, // eccentricity e0: 0, // e' // // constants used in calculations // k: 1, k0: 0.9996, drad: Math.PI / 180, digraphLettersE: "ABCDEFGHJKLMNPQRSTUVWXYZ", digraphLettersN: "ABCDEFGHJKLMNPQRSTUV", digraphLettersAll: "ABCDEFGHJKLMNPQRSTUVABCDEFGHJKLMNPQRSTUVABCDEFGHJKLMNPQRSTUVABCDEFGHJKLMNPQRSTUVABCDEFGHJKLMNPQRSTUVABCDEFGHJKLMNPQRSTUVABCDEFGHJKLMNPQRSTUVABCDEFGHJKLMNPQRSTUVABCDEFGHJKLMNPQRSTUVABCDEFGHJKLMNPQRSTUV", datumTable: [ { eqRad: 6378137.0, flat: 298.2572236 }, // WGS 84 { eqRad: 6378137.0, flat: 298.2572236 }, // NAD 83 { eqRad: 6378137.0, flat: 298.2572215 }, // GRS 80 { eqRad: 6378135.0, flat: 298.2597208 }, // WGS 72 { eqRad: 6378160.0, flat: 298.2497323 }, // Austrailian 1965 { eqRad: 6378245.0, flat: 298.2997381 }, // Krasovsky 1940 { eqRad: 6378206.4, flat: 294.9786982 }, // North American 1927 { eqRad: 6378388.0, flat: 296.9993621 }, // International 1924 { eqRad: 6378388.0, flat: 296.9993621 }, // Hayford 1909 { eqRad: 6378249.1, flat: 293.4660167 }, // Clarke 1880 { eqRad: 6378206.4, flat: 294.9786982 }, // Clarke 1866 { eqRad: 6377563.4, flat: 299.3247788 }, // Airy 1830 { eqRad: 6377397.2, flat: 299.1527052 }, // Bessel 1841 { eqRad: 6377276.3, flat: 300.8021499 } // Everest 1830 ], /// /// calculate constants used for doing conversions using a given map datum /// setDatum: function (index) { var datum = this.datumTable[index]; this.a = datum.eqRad; this.f = 1 / datum.flat; this.b = this.a * (1 - this.f); // polar radius this.e = Math.sqrt(1 - Math.pow(this.b, 2) / Math.pow(this.a, 2)); this.e0 = this.e / Math.sqrt(1 - Math.pow(this.e, 1)); }, /// /// given a lat/lng pair, returns both global UTM and NATO UTM in the following form: /// utm: /// { /// global: { northing: n, easting: e, zone: z, southern: x }, /// nato: { northing: n, easting: e, latzone: z0, lngzone: z1, digraph: xx } /// } /// /// this function assumes that all data validation has been performed prior to calling /// it. /// latLngToUtm: function (lat, lngd) { var phi = lat * this.drad; // convert latitude to radians var lng = lngd * this.drad; // convert longitude to radians var utmz = 1 + Math.floor((lngd + 180) / 6); // longitude to utm zone var zcm = 3 + 6 * (utmz - 1) - 180; // central meridian of a zone var latz = 0; // this gives us zone A-B for below 80S var esq = (1 - (this.b / this.a) * (this.b / this.a)); var e0sq = this.e * this.e / (1 - Math.pow(this.e, 2)); var M = 0; // convert latitude to latitude zone for nato if (lat > -80 && lat < 72) { latz = Math.floor((lat + 80) / 8) + 2; // zones C-W in this range } if (lat > 72 && lat < 84) { latz = 21; // zone X } else if (lat > 84) { latz = 23; // zone Y-Z } var N = this.a / Math.sqrt(1 - Math.pow(this.e * Math.sin(phi), 2)); var T = Math.pow(Math.tan(phi), 2); var C = e0sq * Math.pow(Math.cos(phi), 2); var A = (lngd - zcm) * this.drad * Math.cos(phi); // calculate M (USGS style) M = phi * (1 - esq * (1 / 4 + esq * (3 / 64 + 5 * esq / 256))); M = M - Math.sin(2 * phi) * (esq * (3 / 8 + esq * (3 / 32 + 45 * esq / 1024))); M = M + Math.sin(4 * phi) * (esq * esq * (15 / 256 + esq * 45 / 1024)); M = M - Math.sin(6 * phi) * (esq * esq * esq * (35 / 3072)); M = M * this.a; //Arc length along standard meridian M0 = 0; // if another point of origin is used than the equator // now we are ready to calculate the UTM values... // first the easting var x = this.k0 * N * A * (1 + A * A * ((1 - T + C) / 6 + A * A * (5 - 18 * T + T * T + 72 * C - 58 * e0sq) / 120)); //Easting relative to CM x = x + 500000; // standard easting // now the northing y = this.k0 * (M - M0 + N * Math.tan(phi) * (A * A * (1 / 2 + A * A * ((5 - T + 9 * C + 4 * C * C) / 24 + A * A * (61 - 58 * T + T * T + 600 * C - 330 * e0sq) / 720)))); // first from the equator yg = y + 10000000; //yg = y global, from S. Pole if (y < 0) { y = 10000000 + y; // add in false northing if south of the equator } var digraph = this.makeDigraph(x, y, utmz); var rv = { global: { easting: Math.round(10*(x))/10, northing: Math.round(10*y)/10, zone: utmz, southern: phi < 0 }, nato: { easting: Math.round(10*(x-100000*Math.floor(x/100000)))/10, northing: Math.round(10*(y-100000*Math.floor(y/100000)))/10, latZone: this.digraphLettersN[latz], lngZone: utmz, digraph: digraph } } return rv; }, /// /// convert a set of global UTM coordinates to lat/lng returned as follows /// /// { lat: y, lng: x } /// /// inputs: /// x: easting /// y: northing /// utmz: utm zone /// southern: bool indicating coords are in southern hemisphere /// utmToLatLng: function(x, y, utmz, southern) { var esq = (1 - (this.b / this.a) * (this.b / this.a)); var e0sq = this.e * this.e / (1 - Math.pow(this.e, 2)); var zcm = 3 + 6 * (utmz - 1) - 180; // Central meridian of zone var e1 = (1 - Math.sqrt(1 - Math.pow(this.e, 2))) / (1 + Math.sqrt(1 - Math.pow(this.e, 2))); var M0 = 0; var M = 0; if (!southern) M = M0 + y / this.k0; // Arc length along standard meridian. else M = M0 + (y - 10000000) / this.k; var mu = M / (this.a * (1 - esq * (1 / 4 + esq * (3 / 64 + 5 * esq / 256)))); var phi1 = mu + e1 * (3 / 2 - 27 * e1 * e1 / 32) * Math.sin(2 * mu) + e1 * e1 * (21 / 16 - 55 * e1 * e1 / 32) * Math.sin(4 * mu); //Footprint Latitude phi1 = phi1 + e1 * e1 * e1 * (Math.sin(6 * mu) * 151 / 96 + e1 * Math.sin(8 * mu) * 1097 / 512); var C1 = e0sq * Math.pow(Math.cos(phi1), 2); var T1 = Math.pow(Math.tan(phi1), 2); var N1 = this.a / Math.sqrt(1 - Math.pow(this.e * Math.sin(phi1), 2)); var R1 = N1 * (1 - Math.pow(this.e, 2)) / (1 - Math.pow(this.e * Math.sin(phi1), 2)); var D = (x - 500000) / (N1 * this.k0); var phi = (D * D) * (1 / 2 - D * D * (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * e0sq) / 24); phi = phi + Math.pow(D, 6) * (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * e0sq - 3 * C1 * C1) / 720; phi = phi1 - (N1 * Math.tan(phi1) / R1) * phi; var lat = Math.floor(1000000 * phi / this.drad) / 1000000; var lng = D * (1 + D * D * ((-1 - 2 * T1 - C1) / 6 + D * D * (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * e0sq + 24 * T1 * T1) / 120)) / Math.cos(phi1); lng = lngd = zcm + lng / this.drad; return { lat: lat, lng: lng }; }, /// /// takes a set of NATO style UTM coordinates and converts them to a lat/lng pair. /// /// { lat: y, lng: x } /// /// inputs: /// utme: easting /// utmn: northing /// utmz: longitudinal zone /// latz: character representing latitudinal zone /// digraph: string representing grid /// /// natoToLatLng: function (utme, utmn, utmz, latz, digraph) { var coords = this.natoToUtm(utme, utmn, utmz, latz, digraph); return this.utmToLatLng(coords.easting, coords.northing, coords.zone, coords.southern); }, /// /// convert a set of nato coordinates to the global system. returns a structure /// /// { norhting: y, easting: x, zone: zone, southern: hemisphere } /// /// inputs: /// utme: easting /// utmn: northing /// utmz: longitudinal zone /// latz: character representing latitudinal zone /// digraph: string representing grid /// /// checks for digraph validity /// natoToUtm: function (utme, utmn, utmz, latz, digraph) { latz = latz.toUpperCase(); digraph = digraph.toUpperCase(); var eltr = digraph.charAt(0); var nltr = digraph.charAt(1); /// /// make sure the digraph is consistent /// if (nltr == "I" || eltr == "O") throw "I and O are not legal digraph characters"; if (nltr == "W" || nltr == "X" || nltr == "Y" || nltr == "Z") throw "W, X, Y and Z are not legal second characters in a digraph"; var eidx = this.digraphLettersE.indexOf(eltr); var nidx = this.digraphLettersN.indexOf(nltr); if (utmz / 2 == Math.floor(utmz / 2)) { nidx -= 5; // correction for even numbered zones } var ebase = 100000*(1 + eidx - 8 * Math.floor(eidx / 8)); var latBand = this.digraphLettersE.indexOf(latz); var latBandLow = 8 * latBand - 96; var latBandHigh = 8 * latBand - 88; if (latBand < 2) { latBandLow = -90; latBandHigh = -80; } else if (latBand == 21) { latBandLow = 72; latBandHigh = 84; } else if (latBand > 21) { latBandLow = 84; latBandHigh = 90; } var lowLetter = Math.floor(100 + 1.11 * latBandLow); var highLetter = Math.round(100 + 1.11 * latBandHigh); var latBandLetters = null; if (utmz / 2 == Math.floor(utmz / 2)) { latBandLetters = this.digraphLettersAll.slice(lowLetter + 5, highLetter + 5); } else { latBandLetters = this.digraphLettersAll.slice(lowLetter, highLetter); } var nbase = 100000 * (lowLetter + latBandLetters.indexOf(nltr)); var x = ebase + utme; var y = nbase + utmn; if (y > 10000000) { y = y - 10000000; } if (nbase >= 10000000) { y = nbase + utmn - 10000000; } var southern = nbase < 10000000; return { northing: y, easting: x, zone: utmz, southern: southern }; }, /// /// returns a set of nato coordinates from a set of global UTM coordinates /// return is an object with the following structure: /// { northing: n, easting: e, latZone: z0, lngZone: z1, digraph: xx } /// /// inputs: /// x: easting /// y: northing /// utmz: the utm zone /// southern: hemisphere indicator /// utmToNato: function (x, y, utmz, southern) { var esq = (1 - (this.b / this.a) * (this.b / this.a)); var e0sq = this.e * this.e / (1 - Math.pow(this.e, 2)); var e1 = (1 - Math.sqrt(1 - Math.pow(this.e, 2))) / (1 + Math.sqrt(1 - Math.pow(this.e, 2))); var M0 = 0; if (!southern) M = M0 + y / this.k0; // Arc length along standard meridian. else M = M0 + (y - 10000000) / this.k; // // calculate the latitude so that we can derive the latitude zone // var mu = M / (this.a * (1 - esq * (1 / 4 + esq * (3 / 64 + 5 * esq / 256)))); var phi1 = mu + e1 * (3 / 2 - 27 * e1 * e1 / 32) * Math.sin(2 * mu) + e1 * e1 * (21 / 16 - 55 * e1 * e1 / 32) * Math.sin(4 * mu); //Footprint Latitude phi1 = phi1 + e1 * e1 * e1 * (Math.sin(6 * mu) * 151 / 96 + e1 * Math.sin(8 * mu) * 1097 / 512); var C1 = e0sq * Math.pow(Math.cos(phi1), 2); var T1 = Math.pow(Math.tan(phi1), 2); var N1 = this.a / Math.sqrt(1 - Math.pow(this.e * Math.sin(phi1), 2)); var R1 = N1 * (1 - Math.pow(this.e, 2)) / (1 - Math.pow(this.e * Math.sin(phi1), 2)); var D = (x - 500000) / (N1 * this.k0); var phi = (D * D) * (1 / 2 - D * D * (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * e0sq) / 24); phi = phi + Math.pow(D, 6) * (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * e0sq - 3 * C1 * C1) / 720; phi = phi1 - (N1 * Math.tan(phi1) / R1) * phi; var lat = Math.floor(1000000 * phi / this.drad) / 1000000; // convert latitude to latitude zone for nato if (lat > -80 && lat < 72) { latz = Math.floor((lat + 80) / 8) + 2; // zones C-W in this range } if (lat > 72 && lat < 84) { latz = 21; // zone X } else if (lat > 84) { latz = 23; // zone Y-Z } var digraph = this.makeDigraph(x, y, utmz); x = Math.round(10 * (x - 100000 * Math.floor(x / 100000))) / 10; y = Math.round(10 * (y - 100000 * Math.floor(y / 100000))) / 10; return { easting: x, northing: y, latZone: this.digraphLettersN[latz], lngZone: utmz, digraph: digraph } }, /// /// create a nato grid digraph. /// /// inputs: /// x: easting /// y: northing /// utmz: utm zone /// makeDigraph: function (x, y, utmz) { // // first get the east digraph letter // var letter = Math.floor((utmz - 1) * 8 + (x) / 100000); letter = letter - 24 * Math.floor(letter / 24) - 1; var digraph = this.digraphLettersE.charAt(letter); letter = Math.floor(y / 100000); if (utmz / 2 == Math.floor(utmz / 2)) { letter = letter + 5; } letter = letter - 20 * Math.floor(letter / 20); digraph = digraph + this.digraphLettersN.charAt(letter); return digraph; } }/*** JS Library Function ***/ function createCookie(name,value,days) { if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else var expires = ""; document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function isNumber(n) { return typeof(n) != 'undefined' && n && !isNaN(parseFloat(n)) && isFinite(n); } function stripHtml(htmlString) { if(htmlString){ var mydiv = document.createElement("div"); mydiv.innerHTML = htmlString; if (document.all) // IE Stuff return mydiv.innerText; else // Mozilla does not work with innerText return mydiv.textContent; } return false; } function mergeObject(obj1,obj2){ var obj3 = {}; for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; } for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; } return obj3; } function setOpacity(obj, opacity) { obj.style.filter = (opacity == 100) ? "none" : "alpha(opacity:"+opacity+")"; // IE/Win obj.style.KHTMLOpacity = opacity/100; // Safari<1.2, Konqueror obj.style.MozOpacity = opacity/100; // Older Mozilla and Firefox obj.style.opacity = opacity/100; // Safari 1.2, newer Firefox and Mozilla, CSS3 } function isInArray(item, arr, argStrict) { var key = '', strict = !! argStrict; if (strict) { for (key in arr) { if (arr[key] === item) { return true; } } } else { for (key in arr) { if (arr[key] == item) { return true; } } } return false; } function isInt(n) { return !isNaN(n) && parseFloat(n) == parseInt(n, 10) && !isNaN(n); } function checkWindowSize() { var window_h = window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0; var window_w = window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0; return {w: window_w, h: window_h}; } function checkDivSize(ele_id, op) { var ele = false; if(typeof(ele_id) == 'string') { ele = document.getElementById(ele_id); } else if (typeof(ele_id) == 'object') { ele = ele_id; } if(!ele || typeof(ele) != 'object') return 0; if(op && op == 'h') { return ele.clientHeight || ele.offsetHeight || 0; } else if(op && op == 'w') { return ele.clientWidth || ele.offsetWidth || 0; } var div_h = ele.clientHeight || ele.offsetHeight || 0; var div_w = ele.clientWidth || ele.offsetWidth || 0; return {w: div_w, h: div_h}; } function lpad(str, padString, length) { if(!str || !padString || !length) return str; while (str.length < length) str = padString + str; return str; } function getRgbColorFromHex(hexcolor) { var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hexcolor = hexcolor.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexcolor); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; } function getHexColorFromRGBA(color) { if(!color) return ''; var rgba = /rgba\((.+),\s*(.+),\s*(.+),\s*(.+)\)/.exec(color); var red = parseInt(rgba[1]); var green = parseInt(rgba[2]); var blue = parseInt(rgba[3]); var rgb = (blue | (green << 8) | (red << 16)).toString(16); rgb = lpad(rgb, '0', 6); return '#' + rgb; } function getOpacityFromRGBA(color) { if(!color) return ''; var rgba = /rgba\((.+),\s*(.+),\s*(.+),\s*(.+)\)/.exec(color); return rgba[4]; } function updateQueryStringParam(param, value) { var pathname, baseUrl; if (param == 'ooi' && value != '') { pathname = '/p/'+value; baseUrl = [location.protocol, '//', location.host, pathname].join(''); var params = document.location.search; window.history.replaceState({}, "", baseUrl + params); updateQueryStringParam(param, ''); } else { pathname = location.pathname; var urlQueryString = document.location.search; if (param == 'all' && value == '') { urlQueryString = ''; pathname = '/'; } baseUrl = [location.protocol, '//', location.host, pathname].join(''); var newParam = param + '=' + value, params = '?' + newParam; // If the "search" string exists, then build params from it if (urlQueryString) { keyRegex = new RegExp('([\?&])' + param + '[^&]*'); // If param exists already, update it if (urlQueryString.match(keyRegex) !== null) { if (!value) { params = urlQueryString.replace(keyRegex, ''); } else { params = urlQueryString.replace(keyRegex, "$1" + newParam); } } else { // Otherwise, add it to end of query string if(value) { params = urlQueryString + '&' + newParam; } else { params = urlQueryString; } } } else { if (!value) { params = ''; } } window.history.replaceState({}, "", baseUrl + params); } } function LongdoLib() { this.hideElement = function (ele) { let elements = []; if (typeof(ele) == 'object') { elements = [ele]; } else { elements = document.body.querySelectorAll(ele); } for(let idx=0; idx < elements.length; idx++ ) { elements[idx].original_display = elements[idx].style.display; elements[idx].style.display = 'none'; } } this.showElement = function (ele) { let elements = []; if (typeof(ele) == 'object') { elements = [ele]; } else { elements = document.body.querySelectorAll(ele); } for(let idx=0; idx < elements.length; idx++ ) { if (elements[idx].original_display) { elements[idx].style.display = elements[idx].original_display; } else { elements[idx].style.display = ''; } } } this.getElementSize = function (ele) { if (typeof(ele) == 'string') { let elements = document.body.querySelectorAll(ele); ele = elements[0]; } if (typeof(ele) == 'object') { if (ele == window) { return {w:(window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0), h:(window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0)}; } return {w:ele.clientWidth, h:ele.clientHeight, w_size:ele.getWidth(), h_size:ele.getHeight()}; } return {w:0, h:0, w_size:0, h_size:0}; } this.setElementStyle = function (ele, style_object) { if (typeof(ele) == 'string') { let elements = document.body.querySelectorAll(ele); for(let idx=0; idx < elements.length; idx++ ) { this.setElementStyle(elements[idx], style_object); } return; } else if (typeof(ele) == 'object') { for (var key in style_object) { if (!style_object.hasOwnProperty(key)) continue; ele.style[key] = style_object[key]; } } } } var OOI_OVERLAYS = new Array(); var SEARCHRESULT_OVERLAYS = new Array(); var MAPSERVER_IMG_URL = '//ms.longdo.com/mmmap/img.php'; var loading_popup = "
    "; function convertDMSToLatLon(_dms_lat, _dms_lon) { // ex. ' 51 28 40.12 N', '000 00 05.31 W' var lat = Geo.parseDMS(_dms_lat); var lon = Geo.parseDMS(_dms_lon); if (lat && lon) { lat = lat.toFixed(6); lon = lon.toFixed(6); var p1 = new LatLon(lat, lon); if (p1) return { "lat": lat, "lon" : lon }; } return false; } function convertLatLonToDMS(_lat, _lon) { var lat = Geo.toLat(_lat, "dms", 2); var lon = Geo.toLon(_lon, "dms", 2); if (lat && lon) { return { "lat": lat, "lon" : lon }; } return false; } function convertUTMToLatLon(easting, northing, zone, hemi) { if (!zone) { zone = 47; } if (!hemi) { hemi = 'N'; } var southern = (hemi.toLowerCase() == 's'); var error_msg = '' if (zone < 1 || zone > 60) { return { "lat": 0, "lon" : 0, "error" : 'ระบุ Zone ('+zone+') ไม่ถูกต้อง
    ค่า Longitude zone ต้องอยู่ระหว่าง 1 ถึง 60'}; } if (northing < 0 || northing > 10000000) { return { "lat": 0, "lon" : 0, "error" : 'ระบุ Northing ('+northing+') ไม่ถูกต้อง
    ค่า Northing ต้องอยู่ระหว่าง 0 ถึง 10000000'}; } if (easting < 160000 || easting > 834000) { return { "lat": 0, "lon" : 0, "error" : 'ระบุ Easting ('+easting+') ไม่ถูกต้อง
    ค่า Easting ต้องอยู่ระหว่าง 160000 ถึง 834000'}; } var datum = southern ? 1 : 0; utmconv.setDatum(datum); var latlon = utmconv.utmToLatLng(easting, northing, zone, southern); // get lat/lon for this set of coordinates if (!isNaN(latlon.lat) && !isNaN(latlon.lng)) { return { "lat": latlon.lat, "lon" : latlon.lng }; } return false; } function convertLatLonToUTM(_lat, _lon) { utmconv.setDatum(0); var utm_format = utmconv.latLngToUtm(parseFloat(_lat), parseFloat(_lon)); var utm_txt = ''; if (utm_format && utm_format.global) { return {"e": utm_format.global.easting, "n": utm_format.global.northing, "zone": utm_format.global.zone, "hemi": (utm_format.global.southern ? 'S' : 'N'), "full": utm_format.global.easting + ", " + utm_format.global.northing + ", " + utm_format.global.zone + (utm_format.global.southern ? 'S' : 'N') }; } return false; } function setCenterByTG(_tg_x, _tg_y) { // Thai Geocode XXXXX-YYYYY // XXXXX = 100,000 * (latitude - 5 ) // YYYYY = 100,000 * (longitude - 97 ) var mylat = tgbase32todec(_tg_y)/100000 + 5; var mylong = tgbase32todec(_tg_x)/100000 + 97; return moveLocation(mylat,mylong); } function getMaxZoom() { return mmmap2.projection().maxZoom; } function getMapProjection() { return mmmap2.projection().longdoName; } function mapZoom(zoom) { if(!mmmap2) return false; if(isNumber(zoom)) { mmmap2.zoom(zoom); } else { return mmmap2.zoom(); } } function getMouseLocation() { if(!mmmap2) return false; return mmmap2.location(longdo.LocationMode.Pointer); } function getCenterLocation() { if(!mmmap2) return false; return mmmap2.location(); } function mapBoundary(bound, pivot) { if(!mmmap2) return false; if(bound) mmmap2.bound(bound, pivot); else return mmmap2.bound(); } function moveLocation(lat, lon, zoom) { if(!mmmap2) return false; if(isNumber(lat) && isNumber(lon)) { var rs; try { rs = mmmap2.location({lat: lat, lon: lon}); } catch(ex) { // ex == 'Invalid location' return false; } } if(isNumber(zoom)) { mmmap2.zoom(zoom); } return true; } function boundaryIsOutOfBoundary(boundary) { if(!boundary) return false; var outofboundary = false; if(!outofboundary) { outofboundary = isOutOfBoundary(boundary.minLat, boundary.minLon); } if(!outofboundary) { outofboundary = isOutOfBoundary(boundary.maxLat, boundary.minLon); } if(!outofboundary) { outofboundary = isOutOfBoundary(boundary.minLat, boundary.maxLon); } if(!outofboundary) { outofboundary = isOutOfBoundary(boundary.maxLat, boundary.maxLon); } return outofboundary; } function pointArrayIsOutOfBoundary(point_array) { var boundary = getMinMaxBoundary(point_array); return boundaryIsOutOfBoundary(boundary); } function isOutOfBoundary(lat, lon) { if(!mmmap2) return false; if(isNumber(lat) && isNumber(lon)) { lat = parseFloat(lat); lon = parseFloat(lon); var bound = mapBoundary(); if ( lat < bound.minLat || lat > bound.maxLat || lon < bound.minLon || lon > bound.maxLon ) { return true; } } return false; } function moveLocationWhenOutOfBoundary(lat, lon) { if(!mmmap2) return false; if(isNumber(lat) && isNumber(lon)) { if ( isOutOfBoundary(lat, lon) ) { moveLocation(lat, lon); } } } function showPopup(lat, lon, title, detail, op) { if(!mmmap2 || !longdo) return false; var popup_op = {title: title, detail: detail, autoFocus: true}; if(op) popup_op = mergeObject(popup_op, op); var popup = new longdo.Popup( { lon: lon, lat: lat }, popup_op ); mmmap2.Overlays.add(popup); } function clearShape(shape) { mmmap2.Overlays.remove(shape); } function clearMarker(marker) { mmmap2.Overlays.remove(marker); } function clearPopup(popup) { mmmap2.Overlays.remove(popup); } function clearActivePopup() { clearPopup(getActivePopup()); } function getOOIID(id, prefix) { if(typeof prefix == 'undefined') { prefix = 'A' } if(isInt(id) && id+'' != '-1') { while (id.length < 8) { id = "0" + id; } id = prefix + id; } return id; } function drawDefaultMarker(lat, lon, title, detail, id, focusmarker, hidepopup) { var imageObject = document.createElement('img'); imageObject.mark_lat = lat; imageObject.mark_long = lon; if(typeof(id) != 'undefined' && id !== false && id+'' !== '-1') { imageObject.poi_id = id; imageObject.onmousedown = poiClicked; imageObject.style.cursor = "pointer"; } imageObject.title = title; imageObject.border=0; imageObject.style.zIndex = 1000; if(browser=='IE' && version<7) { imageObject.src="//mmmap15.longdo.com/mmmap/images/pin.gif"; } else imageObject.src="//mmmap15.longdo.com/mmmap/images/pin.png"; hidepopup = (hidepopup == true || hidepopup == 1); drawMarker(imageObject, lat, lon, title, detail, id, {offset: { x: 12, y: 42 }}, {hidepopup: hidepopup, focusmarker: focusmarker}); } function drawMarker(markersrc, lat, lon, title, detail, id, icon_op, marker_op, animation) { if(!mmmap2 || !longdo) return false; if(typeof animation == 'undefined' || !animation) { animation = false; } id = getOOIID(id); if(typeof(id) != 'undefined' && id !== false && id+'' !== '-1' && !detail) { detail = loading_popup; } var _icon_op = {}; if(typeof(markersrc) == 'object') { var wrap = document.createElement('div'); wrap.appendChild(markersrc.cloneNode(true)); markersrc = wrap.innerHTML; _icon_op.html = markersrc; } else if(typeof(markersrc) == 'string') { _icon_op.url = markersrc; } for(var property in icon_op) { if(typeof property == "string" && property != "") { _icon_op[property] = icon_op[property]; } } var location = { lon: lon, lat: lat }; var markerop = {}; markerop.title = title; markerop.icon = _icon_op; markerop.detail = detail; markerop.weight = longdo.OverlayWeight.Top; for(var property in marker_op) { if(typeof property == "string" && property != "" && property != "longdomap") { markerop[property] = marker_op[property]; } } var marker = new longdo.Marker(location, markerop); //var marker = new longdo.Marker({ lon: lon, lat: lat }, { title: title, icon: { html: markersrc, offset: { x: 12, y: 44 }}, popup: { html: detail }}) //var marker = new longdo.Marker(location, markerop); marker.mark_lat = lat; marker.mark_long = lon; if(id && id+'' != '-1') { marker.poi_id = id; marker.data = {'id': id}; } if(marker_op) { if(marker_op.hidepopup) { marker.hidepopup = true; } if(marker_op.focusmarker) { marker.focusmarker = true; } if(typeof marker_op.longdomap != "undefined") { marker.longdomap = marker_op.longdomap } } if(animation) { mmmap2.Overlays.drop(marker); } else { mmmap2.Overlays.add(marker); } return marker; } function getShapeOption(linewidth, linecolor, fillcolor, title, detail, label, editable) { var op = {}; if(typeof title != 'undefined') { op.title = title; } if(typeof detail != 'undefined') { op.detail = detail; } if(typeof label != 'undefined') { op.label = label; } if(typeof linewidth != 'undefined'){ op.lineWidth = linewidth; } if(typeof linecolor != 'undefined'){ op.lineColor = linecolor; } if(typeof fillcolor != 'undefined'){ op.fillColor = fillcolor; } if(typeof editable != 'undefined'){ op.editable = editable; } return op; } function cloneShape(shape, diffop, keep_ori_shape) { if(typeof diffop != 'undefined') { for(var property in diffop) { if(typeof property == "string" && property != "") { shape[property] = diffop[property]; } } } var obj = false; var shape_type = getShapeType(shape); var label = shape.editable && typeof(shape.editable) == 'object' ? true : shape.label; if(shape_type == 'polygon') { obj = drawPolygon(shape.location(), shape.lineWidth, shape.lineColor, shape.fillColor, shape.title, shape.detail, label, shape.editable); } else if(shape_type == 'line') { obj = drawLine(shape.location(), shape.lineWidth, shape.lineColor, shape.fillColor, shape.title, shape.detail, label, shape.editable); } if(typeof keep_ori_shape == 'undefined' || !keep_ori_shape) clearShape(shape); return obj; } function drawLine(points, linewidth, linecolor, fillcolor, title, detail, label, editable) { var line = new longdo.Polyline(points, getShapeOption(linewidth, linecolor, fillcolor, title, detail, label, editable)); mmmap2.Overlays.add(line); return line; } function drawPolygon(points, linewidth, linecolor, fillcolor, title, detail, label, editable) { var polygon = new longdo.Polygon(points, getShapeOption(linewidth, linecolor, fillcolor, title, detail, label, editable)); mmmap2.Overlays.add(polygon); return polygon; } function drawDot(point, linewidth, linecolor, fillcolor, title, detail, label, editable) { var dot = new longdo.Dot(point, getShapeOption(linewidth, linecolor, fillcolor, title, detail, label, editable)); mmmap2.Overlays.add(dot); return dot; } function showPopupLocationDetail(id, overlay) { var service; if(/^foursquare:/.test(id)) { service = 'foursquare'; id = id.replace("foursquare:",""); } else if(/^google:/.test(id)) { service = 'google'; id = id.replace("google:",""); } else if(/^osm:/.test(id)) { service = 'osm'; id = id.replace("osm:",""); } else { service = 'longdo'; } if(service == 'longdo' && !(/^(A|G|M|Y|S)/i.test(id) || !isNaN(id))) { //mmmap.showLocationDetail(id, popup_idx); return; } if (service == 'longdo') { if(window.setPermalinkParam) setPermalinkParam('ooi', id); } updateActivePopupContent(loading_popup, overlay); var d = new Date; var timestamp = d.getTime(); var pars = "timestamp=" + encodeURIComponent( timestamp ); var url = '/mmmap/rpc.php'; var pars = "id=" + encodeURIComponent( id ) + "×tamp=" + encodeURIComponent( timestamp ) + "&locale=" + mylang + "&mmroute=" + isEnableRouting() + "&map=" + "&action=showpoidetails" + "&service=" + service + "&popup_idx=0"; var callbackFn = function(txt) { handleResponse(txt, overlay); if(gapi && (browser!='IE' || (browser=='IE' && version>7))) { setTimeout(function() {gapi.plusone.go()}, 1500); } if(service == 'longdo' && !/^\/snippet\/iframe/.text(document.location.pathname)) { updateQueryStringParam('ooi', id); } } var myAjax = new Ajax.Request(url, {method: 'get', parameters: pars, onSuccess: callbackFn}); } function isEnableRouting() { return (mmmap2 && typeof mmmap2.Route != 'undefined'); } function showTrafficCamerasAndEvent() { if(!mmmap2) return; mmmap2.Overlays.load(longdo.Overlays.events); mmmap2.Overlays.load(longdo.Overlays.cameras); } function hideTrafficCamerasAndEvent() { if(!mmmap2) return; mmmap2.Overlays.unload(longdo.Overlays.events); mmmap2.Overlays.unload(longdo.Overlays.cameras); } function getActivePopup() { if(mmmap2.Overlays && mmmap2.Overlays.list) { var overlay_list = mmmap2.Overlays.list(); if(overlay_list && overlay_list.length > 0) { for(var i=0; i boundary.maxLat) { boundary.maxLat = lat; } if(lat < boundary.minLat) { boundary.minLat = lat; } if(lon < boundary.minLon) { boundary.minLon = lon; } if(lon > boundary.maxLon) { boundary.maxLon = lon; } } } return boundary; } function clearBusStopTagfromSearching() { if(_tag_busstop_from_searching && _tag_busstop_from_searching.length > 0) { var num_tag = _tag_busstop_from_searching.length for(var i=0; i 0 && k == 0) continue; geom.push(points[k]); } } }*/ var title = getRoutingDestinationName(); /* var first_path = guides[0].path[0]; var polyobj = drawLine(geom, first_path.lineWidth, first_path.lineColor, first_path.fillColor, "New Shape", "     ", title, true); */ var polyobj = drawLine(geom, 5, "rgba(255,131,205,0.7)", false, "New Shape", "     ", title, true); polyobj.longdomapcloned = true var mmooi = addMMooi(mmmap2, polyobj); polyobj.longdomap = {ooi: mmooi}; document.selectedOOI = mmooi; document.selectedOOI.setLineColor(getHexColorFromRGBA(polyobj.lineColor)); document.selectedOOI.setLineOpacity(0.7); document.selectedOOI.setLineWidth(5); document.selectedOOI.setGeotype('Line'); document.selectedOOI.setTitleTh(title); document.selectedOOI.setTitleEn(title); document.selectedOOI.setTitleJa(title); document.selectedOOI.lineobject = document.selectedShape; document.selectedOOI.displayPopup(); mmmap2.Route.clear(); } function focusLongdoPOI(lat, lon, id, dozoom, ds) { moveLocationWhenOutOfBoundary(lat, lon); showLongdoPOI(id, dozoom, ds); } function showLongdoPOI(id, dozoom, ds, hidePopup, showicon, icon_src) { if(!mmmap2) return; //mmmap.showObject({id:'G00000355',dozoom:1}); if(typeof(ds) == 'undefined' || !ds) {ds = 'LONGDO';} if(ds == 'LONGDO') { id = getOOIID(id); } var icon = false; if (icon_src && typeof(icon_src) == 'string') { icon = {'icon': { 'html' : ''}}; } var overlay = new longdo.Overlays.Object(id, ds, icon); if(typeof(dozoom) != 'undefined') {overlay.dozoom = dozoom;} if(hidePopup === true || hidePopup == 1) { overlay.hidepopup = true; } if(ds == 'LONGDO') { overlay.poi_id = id; overlay.data = {'id': id}; overlay.longdotype = 'ooi'; overlay.ooitype = 'point'; if(typeof showicon != 'undefined' && showicon == 'showicon') overlay.showicon = showicon; } OOI_OVERLAYS[id] = overlay; mmmap2.Overlays.load(overlay); return overlay; } function isResetSearchAndTagResults() { return (document.getElementById('clear-old-tag') && document.getElementById('clear-old-tag').checked); } function showTag(tagname, tag_op, usedefaultmode, set_search_val) { if (window.selectMapTab) { selectMapTab()}; if(set_search_val) { setSearchLocationValue('tag: '+tagname); if(getSelectedMapdata() == 'tomtom') { longdomapSearch(''); } } if(!mmmap2 || getSelectedMapdata() == 'tomtom') return false; if(tagname != '%') { hideMyFavoriteIcons(); if(window.setPermalinkParam) setPermalinkParam('tag', tagname); } if (typeof(usedefaultmode) == 'undefined' || !usedefaultmode) { var mode = "GRAY"; if (mylang && mylang == "en") { mode = "GRAY_EN"; } setMapMode(mode); } if (!tag_op) { var min_showlevel_visible_tag = 7; var max_showlevel_visible_tag = 21; var current_zoom = mapZoom(); tag_op = {visibleRange: { min: min_showlevel_visible_tag, max: max_showlevel_visible_tag }}; if(current_zoom < min_showlevel_visible_tag) { mapZoom(min_showlevel_visible_tag); } else if(current_zoom > max_showlevel_visible_tag) { mapZoom(max_showlevel_visible_tag); } } if (isResetSearchAndTagResults() && tagname != '%') { mmmap2.Tags.set(tagname, tag_op); } else { mmmap2.Tags.add(tagname, tag_op); } } function convertMapModeV2ToV1(mapmode) { var overlay = false; var mode; if(typeof mapmode == 'string') { mode = mapmode; } else { // array mode = mapmode[0]; if(mapmode[1]) { overlay = mapmode[1]; } } mode = mode.toLowerCase().replace(/_/g, "-"); if(/^poi/ig.test(mode)) { mode = mode.replace(/^poi/ig, "icons"); } else if(/^satellite/ig.test(mode)) { mode = mode.replace(/^satellite/ig, "google_satellite"); } else if(/^iconstransp/ig.test(mode) && getGoogleMapModeV1() == "hybrid") { mode = mode.replace(/^iconstransp/ig, "hybrid_google"); } else if(/^tomtom/ig.test(mode)) { mode = mode.replace(/^tomtom-/ig, "tom").replace(/poi$/ig, "icons"); } if(overlay) { if(overlay == 'trafficoverlay') { mode += '+overlay'; } else if (mode == 'thaichote') { if (/-en$/ig.test(overlay)) { mode += '-en'; } } } return mode; } function convertMapModeV1ToV2(mode) { switch(mode) { case 'tomicons': mode = 'TOMTOM_POI'; break; case 'tomnormal': mode = 'TOMTOM_NORMAL'; break; case 'tomhydro': mode = 'TOMTOM_HYDRO'; break; default: if(mode.indexOf('+') > -1) { mode = mode.split('+')[0]; } mode = mode.toUpperCase().replace(/-/g, "_").replace(/^icons/ig, "POI"); break; } return mode; } function getLayerMapModeV1ToV2(mode) { var overlay = false; if(mode.indexOf('+') > -1) { if(mode.split('+')[1] == 'overlay') { overlay = 'TRAFFIC'; } } return overlay; } function isMapMode(mode) { if (mode == 'icons' || mode == 'icons-en') { if (longdo.Layers.THAICHOTE && mmmap2.Layers.contains(longdo.Layers.THAICHOTE)) { return false; } } else if (mode == 'gray' || mode == 'gray-en') { if (longdo.Layers.TRAFFIC && mmmap2.Layers.contains(longdo.Layers.TRAFFIC)) { return false; } } return isInArray(mode, getMapMode()); } function getMapModeV1() { return convertMapModeV2ToV1(getMapMode()); } function getGoogleMapModeV1() { if(!mmmap2) return false; var google_mode = mmmap2.Layers.externalMap(); if(/^google/g.test(google_mode)) return "hybrid"; else if(isMapMode("satellite")) return "gmap"; return false; } function getMapMode() { if(!mmmap2 || !longdo) return false; var all_mode = mmmap2.Layers.list(); var num_mode = all_mode.length; var map_mode = new Array(); for(var i=0; i mapZoom()) { mapZoom(showlevel); } moveLocation(lat,mylong); } else if(dozoom == 2) { mapZoom(showlevel); moveLocation(lat,mylong); } else { moveLocationWhenOutOfBoundary(lat,mylong); } /* var popup_idx = 0; showLocationDetailPopup(id,name,mylong,lat,'',popup_idx); if (info == "" && (id+"" != "") && (id > -1 || (/^H/i.test(id)) )) { // get from network if (window.showLocationDetail && !(/^H/i.test(id)) ) { showLocationDetail(id, popup_idx); } else { mmmap.showLocationDetail(id, popup_idx); } } else { // otherwise just print what I have showDiv("locationdetails_contents", info); //setTimeout("set_popup_div_size('" + info + "','" + popup_idx + "');",400); mmmap_set_popup_div_size(popup_idx); } */ showLocationDetailPopup(id,name,mylong,lat,info); } function showLocationDetailPopup(id,name,mylong,lat,detail) { var bool_force_id = (typeof(id) != 'undefined' && id !== false && id+'' !== '-1'); if(bool_force_id) { id = getOOIID(id); if(!detail) { detail = loading_popup; } } var popup = new longdo.Popup( { lon: mylong, lat: lat }, { title: name, detail: detail } ); if(bool_force_id) { popup.poi_id = id; } mmmap2.Overlays.add(popup); if(bool_force_id) { showPopupLocationDetail(id, popup); } } function markPoint(id,name,lat,mylong,marker_op) { var imageObject = document.createElement('img'); imageObject.mark_lat = lat; imageObject.mark_long = mylong; imageObject.poi_id = id; imageObject.title = name; imageObject.onmousedown = poiClicked; imageObject.border=0; imageObject.style.zIndex = 1000; imageObject.style.cursor = "pointer"; if(browser=='IE' && version<7) { imageObject.src="//mmmap15.longdo.com/mmmap/images/pin.gif"; } else imageObject.src="//mmmap15.longdo.com/mmmap/images/pin.png"; drawMarker(imageObject, lat, mylong, name, '', id, {offset: { x: 12, y: 42 }}, marker_op); var imageShadow = document.createElement('img'); // store the location/resolution imageShadow.mark_lat = lat; imageShadow.mark_long = mylong; imageShadow.poi_id = id; imageShadow.onmousedown = poiClicked; imageShadow.border=0; imageShadow.style.zIndex = 900; if(browser=='IE' && version<7) { imageShadow.src="//mmmap15.longdo.com/mmmap//images/pin_shadow.gif"; } else imageShadow.src="//mmmap15.longdo.com/mmmap//images/pin_shadow.png"; drawMarker(imageShadow, lat, mylong, name, '', id, {offset: { x: 12, y: 6 }}, marker_op); return; } function hideMyFavoriteIcons() { if (!(typeof user_uid != 'undefined' && isNumber(user_uid) && user_uid > 0) || !longdomap || getSelectedMapdata() == 'tomtom') { return; } longdomap.hideMyFavoritePOIs(); } function showMyFavoriteIcons() { if (!(typeof user_uid != 'undefined' && isNumber(user_uid) && user_uid > 0) || !longdomap || getSelectedMapdata() == 'tomtom') { return; } longdomap.showMyFavoritePOIs(); } function poiClicked(e) { if(document.getElementById('mmmap-popup-trafficcamera-image') && window.stop) {window.stop();} // stop mjpeg process this.poiClicked = true; highLightPOI(this.poi_id); mmmap.updateMouseCursorLocation(); // FIXME now supports only popup_idx = 0 //var popup_idx = 0; var popup_idx = 0; //mmmap.popupinfo.length; // FIXME right now supports only one popup if (typeof(mmmap.popupinfo[popup_idx]) == 'undefined') { mmmap.popupinfo[popup_idx] = new Object(); } // save _lat, _long, ..... to this.popupinfo[this.popupinfo.length] //mmmap.popupinfo[popup_idx].lat = pointToLat(mouse_cursor_y,resolution); //mmmap.popupinfo[popup_idx].lon = pointToLong(mouse_cursor_x,resolution); var lat = this.mark_lat ? this.mark_lat : pointToLat(mouse_cursor_y,resolution); var lon = this.mark_long ? this.mark_long : pointToLong(mouse_cursor_x,resolution); mmmap.popupinfo[popup_idx].lat = lat; mmmap.popupinfo[popup_idx].lon = lon; showLocationDetailPopup(this.poi_id,this.title,lon, lat, '', popup_idx); if (this.poi_id && /^CAMERA/i.test(this.poi_id)) { mmmap.popupinfo[popup_idx].maxwidth = 355; mmmap.popupinfo[popup_idx].maxheight = 350; mmmap.popupinfo[popup_idx].wrapcontent = false; mmmap.popupinfo[popup_idx].fixpopupsize = true; } else { mmmap.popupinfo[popup_idx].wrapcontent = true; mmmap.popupinfo[popup_idx].fixpopupsize = false; mmmap.popupinfo[popup_idx].maxwidth = false; mmmap.popupinfo[popup_idx].maxheight = false; } if (window.showLocationDetail) { showLocationDetail(this.poi_id, popup_idx); } else { mmmap.showLocationDetail(this.poi_id, popup_idx); } // NOT propagate the event if (!e) var e = window.event; return cancelEvent(e); } function setSizeMapArea(map_div, w, h) { if(!mmmap2) return false; if(typeof(map_div) == 'string') { map_div = document.getElementById(map_div); } if(!map_div || typeof(map_div) != 'object') return; map_div.style.width = w + 'px'; map_div.style.height = h + 'px'; mmmap2.resize(); } function hideMapTools(tool) { if(!mmmap2 || !mmmap2.Ui) return false; switch(tool) { case 'centermark': if(mmmap2.Ui.Crosshair && mmmap2.Ui.Crosshair.visible) mmmap2.Ui.Crosshair.visible(false); break; case 'zoombar': if(mmmap2.Ui.Zoombar && mmmap2.Ui.Zoombar.visible) mmmap2.Ui.Zoombar.visible(false); break; case 'movingpad': if(mmmap2.Ui.DPad && mmmap2.Ui.DPad.visible) mmmap2.Ui.DPad.visible(false); break; case 'controltools': if(mmmap2.Ui.Toolbar && mmmap2.Ui.Toolbar.visible) mmmap2.Ui.Toolbar.visible(false); break; case 'mapmodeselector': if(mmmap2.Ui.LayerSelector && mmmap2.Ui.LayerSelector.visible) mmmap2.Ui.LayerSelector.visible(false); if(mmmap2.Ui.LongdoMapModeSelector && mmmap2.Ui.LongdoMapModeSelector.visible) mmmap2.Ui.LongdoMapModeSelector.visible(false); break; case 'scalebar': if(mmmap2.Ui.Scale && mmmap2.Ui.Scale.visible) mmmap2.Ui.Scale.visible(false); break; default: break; } } function resizeMapLegend(map_div) { var legend_div_id = 'longdomap-legend-div'; var legend = document.getElementById(legend_div_id); if (!legend) { return; } if ( (" " + legend.className + " ").replace(/[\n\t]/g, " ").indexOf(" longdomap-legend-hidden ") > -1 ) { return; } var legend_content_div_id = 'longdomap-legend-content-div'; var collapse_div_id = 'longdomap-legend-collapse-div'; var content = document.getElementById(legend_content_div_id); var collapse = document.getElementById(collapse_div_id); content.style.height = ''; content.style.width = ''; content.style.overflowX = ''; var map_area_size = checkDivSize(map_div); var content_size_h = checkDivSize(content, 'h'); var collapse_h = checkDivSize(collapse, 'h'); var legend_padding_h = 10; var legend_padding_w = 20; var padding_for_map_h = 60; // toolbar area var padding_for_map_w = 20; // toolbar area var fit_h = map_area_size.h - padding_for_map_h - collapse_h - legend_padding_h - 80; // bottom: 80 var fit_w = map_area_size.w - padding_for_map_w - legend_padding_w; var content_size_w; if (content_size_h > fit_h) { content.style.height = fit_h + 'px'; content_size_w = checkDivSize(content, 'w'); content.style.width = (content_size_w + 30) + 'px'; // 20: scrollbar width } content_size_w = checkDivSize(content, 'w'); if (content_size_w > fit_w) { content.style.width = fit_w + 'px'; content.style.overflowX = 'auto'; } } function collapseMapLegend(map_div, op) { var legend_div_id = 'longdomap-legend-div'; var collapse_text_id = 'longdomap-legend-collapse-text'; var title_id = 'longdomap-legend-collapse-title'; var legend = document.getElementById(legend_div_id); if ( legend.forcehide && op != 'hide' ) { legend.className = ""; document.getElementById(collapse_text_id).innerHTML = 'ซ่อน'; document.getElementById(title_id).style.display = 'inline'; resizeMapLegend(map_div); legend.forcehide = false; } else { legend.className = "longdomap-legend-hidden"; document.getElementById(collapse_text_id).innerHTML = 'คำอธิบายความหมายของสี'; document.getElementById(title_id).style.display = 'none'; legend.forcehide = true; } } function showMapLegend(map_div, content, op) { if(!mmmap2) return false; if (typeof(op) == 'undefined') { op = 'show'; } if(typeof(map_div) == 'string') { map_div = document.getElementById(map_div); } if(!map_div || typeof(map_div) != 'object') return; var legend_div_id = 'longdomap-legend-div'; var legend_content_div_id = 'longdomap-legend-content-div'; var legenddiv = document.getElementById(legend_div_id); if (legenddiv) { document.getElementById(legend_content_div_id).innerHTML = content; if (legenddiv.style.display == 'none') { legenddiv.style.display = 'block'; } } else { legenddiv = document.createElement("div"); legenddiv.id = legend_div_id; var collapse_div_id = 'longdomap-legend-collapse-div'; var collapse_div_text_id = 'longdomap-legend-collapse-text'; legenddiv.innerHTML = '
    ซ่อน
    คำอธิบายความหมายของสี
    '+content+'
    '; map_div.appendChild(legenddiv); var collapse = document.getElementById(collapse_div_id); collapse.map_div = map_div collapse.onclick = function() { collapseMapLegend(this.map_div); }; } resizeMapLegend(map_div); var content = document.getElementById(legend_content_div_id); var content_img = content.getElementsByTagName('img'); var num_img = content_img.length; var each_img; for(var i=0; i 0) { var num_overlays = allOverlays.length; for(var i=0; i#{label} ', select: function(event, ui) { if(ui.panel.id != "longdomap-tab") { if(jQuery.browser.msie && Math.floor(parseFloat(jQuery.browser.version, 10)) <= 7) { jQuery("#longdomap-tabs").find("ul.ui-tabs-nav").addClass("ui-tabs-nav-padding-bottom"); } if(jQuery("#googlemap_div").length > 0) jQuery("#googlemap_div").hide(); } else { if(jQuery.browser.msie && Math.floor(parseFloat(jQuery.browser.version, 10)) <= 7) { jQuery("#longdomap-tabs").find("ul.ui-tabs-nav").removeClass("ui-tabs-nav-padding-bottom"); } if(jQuery("#googlemap_div").length > 0) jQuery("#googlemap_div").show(); } }, show: function(event, ui) { if(ui.panel.selector == "#longdomap-tab" && !mmmap) { initMap(); } }, add: function(event, ui) { //var path = ui.panel.id.replace("ooiid-", ""); var path = ui.panel.id.replace("-", "/"); jQuery("#"+ui.panel.id).load(path, function(response, status, xhr) { if (status == "error") { jQuery( "#"+ui.panel.id ).html("Couldn't load this tab.") } }); resize_frontpage(true); }, spinner: "", cache: true, cookie: { // store cookie for a day, without, it would be a session cookie expires: 1 } }); //showOOITab("kfofko", "A10000001"); resize_frontpage(); }); */ var set_paging_tab = false; function resize_frontpage(op) { var contentleft_w = typeof _longdomap_fullscreen == 'undefined' || _longdomap_fullscreen ? 0 : (jQuery("#content-left").width() + 1); // var contenttop_h = typeof _longdomap_fullscreen == 'undefined' || _longdomap_fullscreen ? 0 : (jQuery("#header").height() + jQuery("#longdomap-tabs ul.ui-tabs-nav").height() + 30 + 1); var contenttop_h = typeof _longdomap_fullscreen == 'undefined' || _longdomap_fullscreen ? 0 : (jQuery("#header").height() + 30 + 1); var iframe_minus_padding = 30; var right_content_w = (jQuery(window).width() - contentleft_w); var right_content_h = (jQuery(window).height() - contenttop_h); checkAreaForAdsIframe(); var selected_tab_id = jQuery("#longdomap-tabs div.ui-tabs-panel")[getCurrentTabIndex()].id; if(op != 'resizeleftpanelonly') { iframe_panel_id = selected_tab_id.match(/iframe/i) ? selected_tab_id : false; var panel_id = iframe_panel_id ? iframe_panel_id : "longdomap-tabs .ui-tabs-panel" var panel_all_iframe_id = iframe_panel_id ? iframe_panel_id : "longdomap-tabs .ui-tabs-panel-iframe"; jQuery("#longdomap-tabs").width("100%"); jQuery("#"+panel_id).width(right_content_w - (iframe_panel_id ? 0 : iframe_minus_padding)); jQuery("#longdomap-tabs ul.ui-tabs-nav").width(right_content_w - jQuery("#longdomap-jump").width() - jQuery("#longdomap-permalink").width() + 1); jQuery("#longdomap-tab").width("100%"); jQuery("#"+panel_id).height(right_content_h + (iframe_panel_id ? iframe_minus_padding : 0)); jQuery("#"+panel_all_iframe_id).height(right_content_h + iframe_minus_padding); if(!set_paging_tab) { jQuery("#longdomap-tabs").tabs("paging", { followOnSelect: true, selectOnAdd: true }); jQuery("#longdomap-tabs").tabs("option", "ajaxOptions", { async: false, cache: true }); set_paging_tab = true; } $("#longdomap-area").width("100%"); resizeMapLegend($("#longdomap-area")[0]); // function @mmmap-library } if(op != 'resizetabonly') { var tab_content_area = jQuery(window).height() - jQuery("#header").height() - jQuery("#content-left-menu").height() - 3; var search_result_height = tab_content_area - jQuery("#search-tools-area").height() - jQuery("#truehits").height() - 12; var float_content_max_height = parseInt(jQuery('#content-left').css("max-height")) * 0.85; var tool_content_height = parseInt($("#content-left").height()); var tool_content_top = parseInt($("#content-left").top()); if (jQuery("#search-result").height() > $(document).height() * 0.6) { jQuery("#search-result").height(($(document).height()-200) * 0.6); } else { jQuery("#search-result").height($(document).height() * 0.6) } resizeRoutingResult(tab_content_area); jQuery("#content-menu-routing-area").height("auto"); iframe_panel_id = selected_tab_id.match(/iframe/i) ? selected_tab_id : false; $(".ui-tabs-panel-ooi").height(right_content_h + (iframe_panel_id ? iframe_minus_padding : 0)) if ($(".recent-location-controller").children("i").hasClass("maximize")) adjest_result_content() // if ( $("#content-left-result").hasClass("maximize")) { // jQuery("#content-left-result").top(tool_content_height + tool_content_top + 30) // } //FIXME API V2 //if(mmmap && jQuery("#MMMAP_tag_catagories_contents") && jQuery("#MMMAP_tag_catagories_contents").length > 0) { // mmmap.resizeDropdownContent(document.getElementById("MMMAP_tag_catagories_contents").parentNode, 13); //} } if(document.getElementById("moreIconTag") && document.getElementById("moreIconTag").style.visibility == "visible") { resizeMoreIconTagDiv(); } $(window).scrollTop(0); if(mmmap2) { mmmap2.resize(); mmmap2.repaint(true); } if(mmmap_map) mmmap_map.onResize(); if(mmmap_map && mmmap_map.longdomap_pano) { mmmap_map.longdomap_pano.onResize(); } } function resizeMoreIconTagDiv() { if (!document.getElementById("moreIconTag")) { return; } var window_h = window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0; var logo_h = document.getElementById("logo-area") ? document.getElementById("logo-area").clientHeight || document.getElementById("logo-area").offsetHeight||0 : 0; var header_h = document.getElementById("header-bar").clientHeight || document.getElementById("header-bar").offsetHeight||0; var searchtools_h = document.getElementById("content-left-tag").offsetTop; var suggestheight = window_h - header_h - logo_h - searchtools_h - document.getElementById("moreIconTag").offsetTop - 40; document.getElementById("moreIconTag").style.maxHeight = suggestheight+"px"; } function resizeRoutingResult(tab_content_area) { if(!tab_content_area) tab_content_area = jQuery(window).height() - jQuery("#header").height() - jQuery("#content-left-menu").height() - 3; var routing_result_height = tab_content_area - jQuery("#routing-tools-area").height() - 21 - 6; var minimum_height = 130; if(routing_result_height < minimum_height) routing_result_height = minimum_height; // jQuery("#routing-result").height(routing_result_height); }function Longdomap(obj) { this.constructor = function (obj) { document.longdomap_map = this; this._supportLocale = ['en', 'th']; this._map = obj.map; this._lang = (this._supportLocale.include(obj.lang)) ? obj.lang : this._supportLocale[0]; this._lib = new LongdoLib(); if (Longdopano && this._map && getSelectedMapdata() == 'numap') { this.longdomap_pano = new Longdopano({map: this._map, lang: this._lang}); this.longdomap_pano.constructor({map: this._map, lang: this._lang}); // support IE, remove when use es6 } } this.initFullscreenButton = function () { //$(".ldmap_button.ldmap_fullscreen").hide(); $(".ldmap_fullscreen").click(function (){ document.longdomap_map._map.Ui.Fullscreen.toggle(!document.longdomap_map._map.Ui.Fullscreen.visible()); }); } this.onResize = function () { let window_size = this._lib.getElementSize(window); let ldtop_fit = this._lib.getElementSize('#header').h + 10; let searchbox_h_space = 273; this._lib.setElementStyle('#longdomap-tab, #longdomap-tabs, #longdomap-area', {height: window_size.h + 'px'}); this._lib.setElementStyle('.ldmap_navigation', {left: (window_size.w - 70) + 'px', top: ldtop_fit + 'px'}); this._lib.setElementStyle('.ldmap_topright', {right: "80px", top: ldtop_fit + 'px'}); this._lib.setElementStyle('ul.ui-tabs-nav', {display: "none"}); let content_left_height = searchbox_h_space; if (currentactive_tab == "pois") { // fixme : reduce use global variable var searchbox_h = searchbox_h_space - 85; this._lib.setElementStyle('.content-left-content-area', {height: searchbox_h+'px'}); this._lib.setElementStyle('#content-left-result', {height: (window_size.h-searchbox_h_space) + 'px'}); } else { this._lib.setElementStyle('.content-left-content-area', {height: '50%'}); this._lib.setElementStyle('#content-left-result', {height: (window_size.h-(content_left_height+75)) + 'px'}); this._lib.setElementStyle('#recent-location-content', {height: (this._lib.getElementSize('#content-left-result').h - 40) + 'px'}); } this._lib.setElementStyle('#content-menu-routing-area', {height: 'auto'}); this._lib.setElementStyle('#content-left-result', {maxHeight: (window_size.h-(content_left_height+100)) + 'px'}); this._lib.setElementStyle('#recent-location-content, #routing-result', {height: (this._lib.getElementSize('#content-left-result').h - 40) + 'px'}); ///this._lib.setElementStyle('#content-left-result', {display: "block"}); this._lib.setElementStyle('#map-shadow-left', {height: (this._lib.getElementSize('#longdomap-area').h - this._lib.getElementSize('#map-shadow-corner').h) + 'px'}); this._lib.setElementStyle('#map-shadow-top', {width: (this._lib.getElementSize('#longdomap-area').w - this._lib.getElementSize('#map-shadow-corner').w) + 'px'}); if (document.getElementById('content-left-result') && document.getElementById('content-left-result').classList.contains("minimize")) { this._lib.setElementStyle('#content-left-result', {top: (window_size.h - (this._lib.getElementSize('#recent-location-header').h + 5)) + 'px'}); } // if (this._map.Ui.Fullscreen.visible()) { // this.hideElement('#content-left, #content-left-result, #content-left-suggest, #search-tools'); // hide search result // } } this.toggleMapFullscreen = function (state) { let ele = '#content-left, .ldmap_topleft, .ldmap_navigation, #header, #content-left-result, #content-left-suggest, #search-tools, .ldmap_topright'; if (state) { this._lib.hideElement(ele); if (this.longdomap_pano && this.longdomap_pano.isShowPanorama) { this.longdomap_pano.hidePano(); } minimize_maximize_result_content('hide'); // fixme } else { this._lib.showElement(ele); minimize_maximize_result_content('minimize'); // fixme } } }function Longdopano() { this.constructor = function (obj) { document.longdopano = this; this._lang = obj.lang; this._map = obj.map; this._mmmap_lib = new LongdomapLib(obj.map); this._mmmap_lib.constructor(obj.map); // support IE, remove when use es6 this._lib = new LongdoLib(); this._splitBarColor = '#0074E5'; this._splitBarWidthPixel = 4; this._minimapSize = 250; this._minimapPadding = 20; this._minimumMapSize = 300; this._minimumMapZoomLevel = 17; this._copyrightCustomId = 'longdomap-pano-copyright-inner'; this._initPanoElement(); this._textImageCapture = {th : 'ภาพถ่ายเมื่อ ', en: 'Captured on: '} this._mapPano = new longdo.PanoramaViewer({ placeholder: this.pano_div, map: this._map, showPath: true, getLength : false, lang: (this._lang == 'th' ? longdo.PanoramaViewer.LANGUAGE.TH : longdo.PanoramaViewer.LANGUAGE.EN), server : 'https://pano.longdo.com', sphere: true, loadingUi: true, panoControlUi: true, panoWidgetUi: true, panoRenderUi: true, isHD: false, autoStart: false, callBack: { onPositionChange: function(lat, lon, head, frameTime, frameName) { let loc = {lat:lat, lon:lon}; if (document.longdopano._mmmap_lib.isOutOfBoundary(loc)) { document.longdopano._map.location(loc); } let date = new Date(frameTime); let capturedTime = document.longdopano._textImageCapture[document.longdopano._lang] + date.toLocaleDateString(document.longdopano._lang == 'th' ? 'th-TH' : 'en-US', { day: "numeric", year: "numeric", month: "short" }); let longdomap_copyright_div = document.getElementById(document.longdopano._copyrightCustomId); if(!longdomap_copyright_div) { let copyright_div = document.getElementById('ldpano-copyright-inner'); copyright_div.innerHTML = '' + capturedTime + '' + (copyright_div.innerHTML ? " | " + copyright_div.innerHTML : ''); } else { longdomap_copyright_div.innerHTML = capturedTime; } }, onOverlayClick: function(e){ document.longdopano.showPano(e.location()); }, onDropPoint: function(loc){ document.longdopano.showPano(loc); }, onFullscreen: function(state){ document.longdopano.toggleFullscreen(state); }, } }); this._mapPano.continueSeek(true); } this._initPanoElement = function () { this.map_div = document.getElementById(this._map.placeholder().parentNode.id); if (this.map_div) { this.split_div = document.createElement("div"); this.split_div.id = 'longdopano-area-split'; this.map_div.parentNode.insertBefore(this.split_div, this.map_div.nextSibling); this.split_div.style.cursor = 'row-resize'; this.split_div.style.zIndex = 3; this.split_div.style.backgroundColor = this._splitBarColor; //this.split_div.addEventListener("mouseover", (e) => { e.target.style.backgroundColor = '1'; }); //this.split_div.addEventListener("mouseout", (e) => { e.target.style.backgroundColor = ''; }); this.split_div.addEventListener("mouseover", function(e) { e.target.style.backgroundColor = '#6699ff'; }); this.split_div.addEventListener("mouseout", function(e) { e.target.style.backgroundColor = document.longdopano._splitBarColor; }); this.pano_div = document.createElement("div"); this.pano_div.id = 'longdopano-area'; this.split_div.parentNode.insertBefore(this.pano_div, this.split_div.nextSibling); this.pano_close_button = document.createElement("div"); this.pano_close_button.id = 'longdopano-close-button'; this.split_div.parentNode.insertBefore(this.pano_close_button, this.split_div.nextSibling); this.pano_close_button.style.background = 'url("//api.longdo.com/map/images/close.png") center center #fff no-repeat'; this.pano_close_button.style.borderRadius = '20px'; //this.pano_close_button.style.border = '1px solid '+this._splitBarColor; this.pano_close_button.style.cursor = 'pointer'; this.pano_close_button.style.width = '32px'; this.pano_close_button.style.height = '32px'; this.pano_close_button.style.position = 'absolute'; this.pano_close_button.style.zIndex = 99999; this.pano_close_button.style.marginTop = '3px'; this.pano_close_button.style.marginLeft = '3px'; this.pano_close_button.style.opacity = '0.6'; this.pano_close_button.alt = 'Close'; this.pano_close_button.title = 'Close'; //this.pano_close_button.addEventListener("click", () => { this.hidePano(); }); //this.pano_close_button.addEventListener("mouseover", (e) => { e.target.style.opacity = '1'; }); //this.pano_close_button.addEventListener("mouseout", (e) => { e.target.style.opacity = '0.6'; }); this.pano_close_button.addEventListener("click", function() { document.longdopano.hidePano(); }); this.pano_close_button.addEventListener("mouseover", function(e) { e.target.style.opacity = '1'; }); this.pano_close_button.addEventListener("mouseout", function(e) { e.target.style.opacity = '0.6'; }); this.pano_minimap_fullscreen_div = document.createElement("div"); this.pano_minimap_fullscreen_div.id = 'longdopano-minimap-fullscreen-button'; this.split_div.parentNode.insertBefore(this.pano_minimap_fullscreen_div, this.split_div.nextSibling); this.pano_minimap_fullscreen_div.style.display = 'none'; this.pano_minimap_fullscreen_div.style.position = 'absolute'; this.pano_minimap_fullscreen_div.style.width = '32px'; this.pano_minimap_fullscreen_div.style.height = '32px'; this.pano_minimap_fullscreen_div.style.zIndex = 99999; this.pano_minimap_fullscreen_div.style.zIndex = 99999; this.pano_minimap_fullscreen_div.style.opacity = '0.6'; this.pano_minimap_fullscreen_div.style.cursor = 'pointer'; this.pano_minimap_fullscreen_div.style.bottom = (this._minimapPadding + this._minimapSize - this._lib.getElementSize(this.pano_minimap_fullscreen_div).h_size) + 'px'; this.pano_minimap_fullscreen_div.style.left = (this._minimapPadding + this._minimapSize - this._lib.getElementSize(this.pano_minimap_fullscreen_div).w_size) + 'px'; this.pano_minimap_fullscreen_div.style.background = 'url("//api.longdo.com/map/images/ui/fullscreen-up.png") center center no-repeat'; //this.pano_minimap_fullscreen_div.addEventListener("click", () => { this._mapPano.fullscreen(false); }); //this.pano_minimap_fullscreen_div.addEventListener("mouseover", (e) => { e.target.style.opacity = '1'; }); //this.pano_minimap_fullscreen_div.addEventListener("mouseout", (e) => { e.target.style.opacity = '0.6'; }); this.pano_minimap_fullscreen_div.addEventListener("click", function() { document.longdopano._mapPano.fullscreen(false); }); this.pano_minimap_fullscreen_div.addEventListener("mouseover", function(e) { e.target.style.opacity = '1'; }); this.pano_minimap_fullscreen_div.addEventListener("mouseout", function(e) { e.target.style.opacity = '0.6'; }); if ($ && $('#'+this.split_div.id).length > 0 && $('#'+this.split_div.id).draggable) { $('#'+this.split_div.id).draggable({ axis: "y", containment: '#longdomap-tabs', drag: function( event, ui ) { document.longdopano.onResize(event.pageY); } }); } } } this.showPath = function () { this._mapPano.showPath(); if (this.isShowPanorama) { this._mapPano.location(this._mapPano.location()); } } this.toggleFullscreen = function (state) { let ele = '.ldmap_fullscreen, #content-left, #header, #content-left-result, #content-left-suggest, #search-tools, #content-left'; if (state) { this._lib.hideElement(ele); this.map_div.classList.add('minimap-with-pano'); this._map.Ui.Scale.visible(false); this._map.Ui.Toolbar.visible(false); this._map.location(this._mapPano.location()); this._map.resize(); this._lib.hideElement('.ldmap_topright'); this._lib.showElement('#longdopano-minimap-fullscreen-button'); } else { this._lib.showElement(ele); this.map_div.classList.remove('minimap-with-pano'); this._map.Ui.Scale.visible(true); this._map.Ui.Toolbar.visible(true); this._map.resize(); this._lib.showElement('.ldmap_topright'); this._lib.hideElement('#longdopano-minimap-fullscreen-button'); } } this.showPano = function (loc) { if (this.map_div) { if (!this.isShowPanorama) { if (this._map.Ui.Fullscreen.visible()) { this._map.Ui.Fullscreen.toggle(false); } if (this._map.zoom() < this._minimumMapZoomLevel) { this._map.zoom(this._minimumMapZoomLevel); } minimize_maximize_result_content('hide'); // fixme this.pano_div.style.display = 'block'; this.split_div.style.display = 'block'; this.split_div.style.height = this._splitBarWidthPixel + 'px'; this.pano_div.style.width = '100%'; this.split_div.style.width = '100%'; this.map_div.style.position = 'static'; this.isShowPanorama = true; if(loc){ if(!this._mapPano.isStarted()) { this._mapPano.start(loc); } else { this._mapPano.location(loc); } } this.onResize(); if (!this.isInitPanorama) { window.onresize = function() { document.longdopano.onResize(); }; this.isInitPanorama = true; } } else { this._mapPano.location(loc); } } } this.onResize = function (pano_spit_offsettop) { if (this.isShowPanorama) { let isPanoFullscreen = this._mapPano.fullscreen(); if (!this.customResizeMapPanoPffsetTop && typeof(pano_spit_offsettop) == 'undefined') { this.map_div.style.height = (this._lib.getElementSize(window).h/2 - (this._splitBarWidthPixel/2)) + 'px'; if(!isPanoFullscreen) { this.pano_div.style.height = (this._lib.getElementSize(window).h/2 - (this._splitBarWidthPixel/2)) + 'px'; // 'calc(50vh - '+(this._splitBarWidthPixel/2)+'px)'; } } else { if (typeof(pano_spit_offsettop) == 'undefined') { pano_spit_offsettop = this.customResizeMapPanoPffsetTop; } else { this.customResizeMapPanoPffsetTop = pano_spit_offsettop; } if (pano_spit_offsettop < this._minimumMapSize) { pano_spit_offsettop = this._minimumMapSize; } else if (pano_spit_offsettop > this._lib.getElementSize(window).h - this._minimumMapSize) { pano_spit_offsettop = this._lib.getElementSize(window).h - this._minimumMapSize; } if (pano_spit_offsettop > this._lib.getElementSize(window).h - 100 || pano_spit_offsettop < 100) { pano_spit_offsettop = this._lib.getElementSize(window).h/2; } this.map_div.style.height = pano_spit_offsettop + 'px'; if(!isPanoFullscreen) { this.pano_div.style.height = (this._lib.getElementSize(window).h - (pano_spit_offsettop + this._splitBarWidthPixel)) + 'px'; } } } else { if(!this.mapDivHeightOriginal) { this.mapDivHeightOriginal = this._lib.getElementSize(window).h + 'px'; // this.map_div.style.height; } this.map_div.style.height = this._lib.getElementSize(window).h + 'px'; // this.mapDivHeightOriginal; } this._map.resize(); this._mapPano.resize(); } this.hidePano = function () { if (this._mapPano.play()) { this._mapPano.play(false); } if (this._mapPano.fullscreen()) { this._mapPano.fullscreen(false); } if (this.pano_div) { this.pano_div.style.display = 'none'; this.split_div.style.display = 'none'; minimize_maximize_result_content('minimize'); // fixme this._map.Overlays.remove(this._mapPano.currentLocationMarker()); this.isShowPanorama = false; } this.onResize(); } } function LongdomapLib() { this.constructor = function (map) { this._map = map; } this.mapBoundary = function (bound) { if(bound) this._map.bound(bound); else return this._map.bound(); } this.isOutOfBoundary = function (loc) { if(isNumber(loc.lat) && isNumber(loc.lon)) { let bound = this.mapBoundary(); if ( loc.lat < bound.minLat || loc.lat > bound.maxLat || loc.lon < bound.minLon || loc.lon > bound.maxLon ) { return true; } } return false; } }