/** * * 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; markpoijs += 'markPOI(' + '\''+id+'\'' + ",'" + usename + "'," + lat +',' + mylong + ", " + zoom + " , '');"; markpoiandzoomjs += 'markPOIandZoom(' + '\''+id+'\'' + ",'" + usename + "'," + lat +',' + mylong + "," + showlevel + ", '', 1);"; } else { //if(type == "foursquare-poi") { 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") { ds_type = "XID"; } else if(type == "water-area") { ds_type = "WID"; } else if(type == "building") { ds_type = "BID"; } 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(); } var sumlat = 0; var sumlong = 0; var all_points_on_screen = true; var some_point_on_screen = false; var points = new Array(); search_results_poi.sort(function(a,b) {return a[2]==b[2] ? 0 : (a[2] < b[2] ? -1 : 1)}) var num_poi = search_results_poi.length; var marker_op = {'longdomap': {'markertype': 'search-result'}}; for (var i=num_poi-1; 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') { 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); //} } } } 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. /*** longdo-jquery ***/ $(document).ready(function(){ if($('.customselector').length > 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(); // }); // } // }); 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'); } }); $('.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; function initMMMapOptions() { var label_default = mylang == 'th' ? 'เลือกชั้นข้อมูล' : 'Other layers'; var label_rain_forecast = mylang == 'th' ? 'คาดการณ์ฝนตก' : 'Rain Forecast'; 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_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); } if (floodTagLayer) { mmmap2.Tags.remove(floodTagLayer); if (floodTagLayer == 'future_masstransit') { mmmap2.Tags.remove('future_masstransit_station'); } } 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'); } 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); } 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(); } 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', ''); } 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! } /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */ /*** 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); } } 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 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) { if(!mmmap2) return false; if(bound) mmmap2.bound(bound); else return mmmap2.bound(); } function moveLocation(lat, lon, zoom) { if(!mmmap2) return false; if(isNumber(lat) && isNumber(lon)) { var rs = mmmap2.location({lat: lat, lon: lon}); } if(isNumber(zoom)) { mmmap2.zoom(zoom); } if(rs == 'Invalid location') return false; 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 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|P)/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 clearAllSearchLocationPin() { if(!mmmap2) return false; var all_overlay = mmmap2.Overlays.list(); var num_overlay = all_overlay.length; var obj; 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) { if (window.selectMapTab) { selectMapTab()}; 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; 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 legend = document.getElementById(legend_div_id); if ( legend.forcehide && op != 'hide' ) { legend.className = ""; document.getElementById(collapse_text_id).innerHTML = 'ซ่อน'; resizeMapLegend(map_div); legend.forcehide = false; } else { legend.className = "longdomap-legend-hidden"; document.getElementById(collapse_text_id).innerHTML = 'คำอธิบายความหมายของสี'; 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#{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); jQuery("#longdomap-tab, #longdomap-area").height(right_content_h + (_longdomap_fullscreen ? 0 : 30)); jQuery("#longdomap-tab, #longdomap-area").height("100%"); jQuery("#longdomap-tabs").height(right_content_h + (_longdomap_fullscreen ? 0 : (jQuery("#longdomap-tabs ul.ui-tabs-nav").height() + 30))); 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; } var map_height = jQuery("#longdomap-tabs .ui-tabs-panel").height(); $("#longdomap-area").width("100%"); $("#longdomap-area").height(map_height); var shadow_corner_height = $("#map-shadow-corner").height(); var shadow_corner_width = $("#map-shadow-corner").width(); $("#map-shadow-left").height(map_height-shadow_corner_height); $("#map-shadow-top").width(right_content_w-shadow_corner_width); 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"); if(window.rebuild_mapui) rebuild_mapui(); if(window.content_result_binding) content_result_binding(); 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); } } 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 suggestheight = window_h - header_h - logo_h - document.getElementById("moreIconTag").offsetTop - 10; 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); }