code
stringlengths
1
2.08M
language
stringclasses
1 value
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','en',{uicolor:{title:'UI Color Picker',preview:'Live preview',config:'Paste this string into your config.js file',predefined:'Predefined color sets'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.plugins.setLang('uicolor','he',{uicolor:{title:'בחירת צבע ממשק משתמש',preview:'תצוגה מקדימה',config:'הדבק את הטקסט הבא לתוך הקובץ config.js',predefined:'קבוצות צבעים מוגדרות מראש'}});
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */
JavaScript
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ // Compressed version of core/ckeditor_base.js. See original for instructions. /*jsl:ignore*/ if(!window.CKEDITOR)window.CKEDITOR=(function(){var a={timestamp:'',version:'3.5.2',revision:'6450',_:{},status:'unloaded',basePath:(function(){var d=window.CKEDITOR_BASEPATH||'';if(!d){var e=document.getElementsByTagName('script');for(var f=0;f<e.length;f++){var g=e[f].src.match(/(^|.*[\\\/])ckeditor(?:_basic)?(?:_source)?.js(?:\?.*)?$/i);if(g){d=g[1];break;}}}if(d.indexOf(':/')==-1)if(d.indexOf('/')===0)d=location.href.match(/^.*?:\/\/[^\/]*/)[0]+d;else d=location.href.match(/^[^\?]*\/(?:)/)[0]+d;return d;})(),getUrl:function(d){if(d.indexOf(':/')==-1&&d.indexOf('/')!==0)d=this.basePath+d;if(this.timestamp&&d.charAt(d.length-1)!='/')d+=(d.indexOf('?')>=0?'&':'?')+('t=')+this.timestamp;return d;}},b=window.CKEDITOR_GETURL;if(b){var c=a.getUrl;a.getUrl=function(d){return b.call(a,d)||c.call(a,d);};}return a;})(); /*jsl:end*/ // Uncomment the following line to have a new timestamp generated for each // request, having clear cache load of the editor code. // CKEDITOR.timestamp = ( new Date() ).valueOf(); // Set the script name to be loaded by the loader. CKEDITOR._autoLoad = 'core/ckeditor_basic'; // Include the loader script. document.write( '<script type="text/javascript" src="' + CKEDITOR.getUrl( '_source/core/loader.js' ) + '"></script>' );
JavaScript
$.fn.addfeed = function(options){ options = options || {}; //绑定每个按钮 return this.each(function() { if (!$(this).attr("class").match(/(^|\s)feed($|\s)/)) $(this).addClass("feed"); $$addfeed.initBtn(this); }); }; var $$addfeed = { timeDelayout:420, feeds:{ "rss":{id:0, name:"Rss订阅"}, "google":{id:1, name:"谷歌阅览器"}, "zhuaxia":{id:2, name:"抓虾"}, "xianguo":{id:3, name:"鲜果"}, //"qq":{id:4, name:"QQ邮箱"}, "yahoo":{id:5, name:"雅虎"}, "inezha":{id:7, name:"哪吒"}, "Email":{id:8, name:"邮天下"}, "youdao":{id:9, name:"有道"}, "feige":{id:10, name:"飞鸽"}, "bloglines":{id:12, name:"Bloglines"}, }, e:encodeURIComponent, gotourl:function(url,argStr){ open(url + argStr, 'addthis'); return false; }, windowOffset:function(){ var info={width:0,height:0,left:0,top:0,right:0,bottom:0}; if(window.innerWidth&&window.innerWidth.constructor==Number){ info.width=window.innerWidth; //窗口可见宽度 info.height=window.innerHeight; info.left=window.pageXOffset; //页面滚动的宽度 info.top=window.pageYOffset; }else if(document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight)){ info.width=document.documentElement.clientWidth; info.height=document.documentElement.clientHeight; info.left=document.documentElement.scrollLeft; info.top=document.documentElement.scrollTop; }else if(document.body&&(document.body.clientWidth||document.body.clientHeight)){ info.width=document.body.clientWidth; info.height=document.body.clientHeight; info.left=document.body.scrollLeft; info.top=document.body.scrollTop; } info.right=info.left+info.width; info.bottom=info.top+info.height; return info; }, showposition:function(dropdown,fgdiv,bgfrm,btn){//参数为jQuery对象 if(!$.boxModel){ fgdiv.css("width", (fgdiv.get(0).clientWidth+parseInt(fgdiv.css("padding-left"))+parseInt(fgdiv.css("padding-right"))+(parseInt(fgdiv.css("border-left-width"))?parseInt(fgdiv.css("border-left-width")):0)+(parseInt(fgdiv.css("border-right-width"))?parseInt(fgdiv.css("border-right-width")):0))+"px"); } dropdown.css("width", fgdiv.get(0).offsetWidth+"px"); bgfrm.css("width", fgdiv.get(0).offsetWidth+"px"); dropdown.css("height", fgdiv.get(0).offsetHeight+"px"); bgfrm.css("height", fgdiv.get(0).offsetHeight+"px"); var info_btn=btn.offset(); var info_window=$$addfeed.windowOffset(); var info_dropdown=dropdown.offset(); var left=0,top=0; if(info_window.right-info_btn.left<=dropdown.width()){ left=info_btn.left+btn.width() - dropdown.width(); //left=btn.width() - dropdown.width(); }else{ left=info_btn.left; //left=0; } if(info_window.bottom-info_btn.top-(btn.find("*").height()||16)<=dropdown.height()){ top= info_btn.top-dropdown.height(); //top= -dropdown.height(); }else{ top=info_btn.top+btn.height(); //top=btn.height(); } dropdown.css("left", left+"px"); dropdown.css("top", top+"px"); info_btn = info_window = info_dropdown = left = top = null; }, showThisItem:function(thisItem){ $(".feed .addbox").hide(); $(thisItem).find(".addbox").show(); }, initBtn:function(btn){ //btn{locked, argStr, mouse_over, boxmouseover, boxmouseout, timeOut, addthis, addbox, u , t, e} //btn为dom对象 btn.mouse_over=function(jbtn, e){ if(btn.locked){$$addfeed.showThisItem(btn.addthis); return false;} // btn.locked=true; //btn mouseover首次事件 //if ($$addfeed.isMouseLeaveOrEnter(e||event, btn)) { //$$addfeed.timeOnOver = setTimeout(function(){ //获取配置 var btn_i = $(btn).attr("i")? "|"+$(btn).attr("i")+"|" : "";//alert(btn_i); if ($(btn).attr("href")&&$(btn).attr("href")!=document.location+"#"&&$(btn).attr("href")!=document.location&&$(btn).attr("href")!="#") { btn.u = $(btn).attr("href"); } else { btn.u = $("link[type='application/rss+xml'], link[type='application/atom+xml']").attr("href"); //alert(btn.u); } btn.e = $(btn).attr("e") ? $(btn).attr("e") : "mouseover"; btn.argStr = $$addfeed.e(btn.u); btn.addthis = btn; $(".addbox").hide(); $$addfeed.showThisItem(btn.addthis); //生成.addbox html $(btn).append('<div class="addbox"></div>'); var addbox=$(btn).find("div.addbox").get(0); btn.addbox = addbox; var html= ""; html += '<iframe class="bgfrm" frameborder="0" tabindex="-1" src="javascript:;" style="display:block;position:absolute;z-index:-1;"></iframe>'; html += '<div class="addshow"><div class="addh"><div class="addt">订阅到:</div></div><div class="addbody"><div class="flist" style="position:inherit; margin:0 0 3px 0; padding:6px; width:172px;">'; for(var key in $$addfeed.feeds){ if (!btn_i || (btn_i && btn_i.indexOf("|"+$$addfeed.feeds[key].id+"|")>=0)) { html+='<div class="li" style=" float:left; display:inline; position:inherit; margin:0 0 0 3px; padding:0; line-height:16px; height:22px; border:none; background:none; font-size:12px;"><a class="feed_'+ $$addfeed.feeds[key].id +'" item="'+ $$addfeed.feeds[key].id +'" href="#">&nbsp;</a></div>'; } } html += '</div><div style="clear:both;line-height:0"></div></div>'; html += '<div class="addbottom">by GNG</a></div>'; html += '</div>'; $(addbox).html(html); //alert($(addbox).html()); $$addfeed.showposition($(addbox), $(addbox).find(".addshow"), $(addbox).find(".bgfrm"), $(btn)); //addbox.style.display="block"; $(addbox).find(".flist .li a").click(function(evt){ if (Number($(this).attr("item"))==0) { open(btn.u, 'addfeed'); } else { a = $.attr(this,"item") switch(a){ case "1": $$addfeed.gotourl("http://www.google.com/reader/view/feed/",btn.argStr); break; case "2": $$addfeed.gotourl("http://www.zhuaxia.com/add_channel.php?url=",btn.argStr); break; case "3": $$addfeed.gotourl("http://xianguo.com/subscribe?url=",btn.argStr); break; //case "4": // $$addfeed.gotourl("http://mail.qq.com/cgi-bin/feed?u=",btn.argStr); // break; case "5": $$addfeed.gotourl("http://add.my.yahoo.com/rss?url=",btn.argStr); break; case "7": $$addfeed.gotourl("http://inezha.com/add?url=",btn.argStr); break; case "8": $$addfeed.gotourl("http://www.emailrss.cn/?rss=",btn.argStr); break; case "9": $$addfeed.gotourl("http://reader.youdao.com/b.do?url=",btn.argStr); break; case "10": $$addfeed.gotourl("http://www.pageflakes.com/subscribe.aspx?url=",btn.argStr); break; case "12": $$addfeed.gotourl("http://www.bloglines.com/sub/",btn.argStr); break; case "15": $$addfeed.gotourl("http://rss.hexun.com/sub/",btn.argStr); break; case "16": $$addfeed.gotourl("http://9.douban.com/reader/subscribe?url=",btn.argStr); break; } } //$.cancelEvent(evt||event); //隐藏addbox $(btn.addbox).hide(); return false; }); //绑定事件 $(btn.addthis).mouseover(function(evt){ if ($$addfeed.isMouseLeaveOrEnter(evt||event, btn.addthis)) { if (btn.e=="click") { clearTimeout(btn.timeOut); } else if (btn.e=="mouseover"){ btn.boxmouseover(evt); clearTimeout(btn.timeOut); } } }); $(btn.addthis).mouseout(function(evt){ if ($$addfeed.isMouseLeaveOrEnter(evt||event, btn.addthis)) { btn.timeOut = setTimeout(btn.boxmouseout, $$addfeed.timeDelayout); } }); btn_i = btn_t = btn_u = btn_d = addbox = html = null; //},$$addfeed.timeDelayOver); //} //end else //} }; btn.boxmouseover=function(evt){ $$addfeed.showposition($(btn.addbox), $(btn.addbox).find(".addshow"), $(btn.addbox).find(".bgfrm"), $(btn)); $(btn.addbox).show(); }; btn.boxmouseout=function(evt){ $(btn.addbox).fadeOut(); }; if ($(btn).attr("e")=="click") { $(btn).click(function(evt){ btn.mouse_over(btn, evt); return false; }); } else { $(btn).click(function(evt){ return false; }).mouseover(function(evt){ btn.mouse_over(btn, evt); }); } }, isMouseLeaveOrEnter: function(e, handler) { if (e.type != 'mouseout' && e.type != 'mouseover') return false; var reltg = e.relatedTarget ? e.relatedTarget : e.type == 'mouseout' ? e.toElement : e.fromElement; while (reltg && reltg != handler) reltg = reltg.parentNode; return (reltg != handler); } };
JavaScript
jQuery(document).ready(function($){ var $form_modal = $('.cd-user-modal'), $form_login = $form_modal.find('#cd-login'), $form_signup = $form_modal.find('#cd-signup'), $form_forgot_password = $form_modal.find('#cd-reset-password'), $form_modal_tab = $('.cd-switcher'), $tab_login = $form_modal_tab.children('li').eq(0).children('a'), $tab_signup = $form_modal_tab.children('li').eq(1).children('a'), $forgot_password_link = $form_login.find('.cd-form-bottom-message a'), $back_to_login_link = $form_forgot_password.find('.cd-form-bottom-message a'), $main_nav = $('.top_right'); //open modal $main_nav.on('click', function(event){ if( $(event.target).is($main_nav) ) { // on mobile open the submenu $(this).children('ul').toggleClass('is-visible'); } else { // on mobile close submenu $main_nav.children('ul').removeClass('is-visible'); //show modal layer $form_modal.addClass('is-visible'); //show the selected form ( $(event.target).is('.cd-signup') ) ? signup_selected() : login_selected(); } }); //close modal $('.cd-user-modal').on('click', function(event){ if( $(event.target).is($form_modal) || $(event.target).is('.cd-close-form') ) { $form_modal.removeClass('is-visible'); } }); //close modal when clicking the esc keyboard button $(document).keyup(function(event){ if(event.which=='27'){ $form_modal.removeClass('is-visible'); } }); //switch from a tab to another $form_modal_tab.on('click', function(event) { event.preventDefault(); ( $(event.target).is( $tab_login ) ) ? login_selected() : signup_selected(); }); //hide or show password $('.hide-password').on('click', function(){ var $this= $(this), $password_field = $this.prev('input'); ( 'password' == $password_field.prop('type') ) ? $password_field.prop('type', 'text') : $password_field.prop('type', 'password'); ( 'Hide' == $this.text() ) ? $this.text('Show') : $this.text('Hide'); //focus and move cursor to the end of input field $password_field.putCursorAtEnd(); }); //show forgot-password form $forgot_password_link.on('click', function(event){ event.preventDefault(); forgot_password_selected(); }); //back to login from the forgot-password form $back_to_login_link.on('click', function(event){ event.preventDefault(); login_selected(); }); function login_selected(){ $form_login.addClass('is-selected'); $form_signup.removeClass('is-selected'); $form_forgot_password.removeClass('is-selected'); $tab_login.addClass('selected'); $tab_signup.removeClass('selected'); } function signup_selected(){ $form_login.removeClass('is-selected'); $form_signup.addClass('is-selected'); $form_forgot_password.removeClass('is-selected'); $tab_login.removeClass('selected'); $tab_signup.addClass('selected'); } function forgot_password_selected(){ $form_login.removeClass('is-selected'); $form_signup.removeClass('is-selected'); $form_forgot_password.addClass('is-selected'); } //REMOVE THIS - it's just to show error messages // $form_login.find('input[type="submit"]').on('click', function(event){ // event.preventDefault(); // $form_login.find('input[type="email"]').toggleClass('has-error').next('span').toggleClass('is-visible'); // }); // $form_signup.find('input[type="submit"]').on('click', function(event){ // event.preventDefault(); // $form_signup.find('input[type="email"]').toggleClass('has-error').next('span').toggleClass('is-visible'); // }); //IE9 placeholder fallback //credits http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html if(!Modernizr.input.placeholder){ $('[placeholder]').focus(function() { var input = $(this); if (input.val() == input.attr('placeholder')) { input.val(''); } }).blur(function() { var input = $(this); if (input.val() == '' || input.val() == input.attr('placeholder')) { input.val(input.attr('placeholder')); } }).blur(); $('[placeholder]').parents('form').submit(function() { $(this).find('[placeholder]').each(function() { var input = $(this); if (input.val() == input.attr('placeholder')) { input.val(''); } }) }); } }); //credits http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/ jQuery.fn.putCursorAtEnd = function() { return this.each(function() { // If this function exists... if (this.setSelectionRange) { // ... then use it (Doesn't work in IE) // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh. var len = $(this).val().length * 2; this.setSelectionRange(len, len); } else { // ... otherwise replace the contents with itself // (Doesn't work in Google Chrome) $(this).val($(this).val()); } }); };
JavaScript
$(document).ready(function() { //select all the a tag with name equal to name=loginFieldClick $('a[name=loginFieldClick]').click(function(e) { //Cancel the link behavior e.preventDefault(); //Get the A tag var id = $(this).attr('href'); //Get the screen height and width var maskHeight = $(document).height(); var maskWidth = $(window).width(); //Set heigth and width to mask to fill up the whole screen $('#mask').css({'width':maskWidth,'height':maskHeight}); //transition effect $('#mask').fadeIn(1000); $('#mask').fadeTo("slow",0.8); //Get the window height and width var winH = $(window).height(); var winW = $(window).width(); //Set the popup window to center $(id).css('top', winH/2-$(id).height()/2); $(id).css('left', winW/2-$(id).width()/2); //transition effect $(id).fadeIn(2000); }); //if close button is clicked $('.window .close').click(function (e) { //Cancel the link behavior e.preventDefault(); $('#mask').hide(); $('.window').hide(); }); //if mask is clicked $('#mask').click(function () { $(this).hide(); $('.window').hide(); }); $(window).resize(function () { var box = $('.window'); //Get the screen height and width var maskHeight = $(document).height(); var maskWidth = $(window).width(); //Set height and width to mask to fill up the whole screen $('#mask').css({'width':maskWidth,'height':maskHeight}); //Get the window height and width var winH = $(window).height(); var winW = $(window).width(); //Set the popup window to center box.css('top', winH/2 - box.height()/2); box.css('left', winW/2 - box.width()/2); }); });
JavaScript
// <![CDATA[ $(function() { // Slider $('#coin-slider').coinslider({width:960,height:360,opacity:1}); // Radius Box $('.content .mainbar img.fl, .content .sidebar .gadget').css({"border-radius":"10px", "-moz-border-radius":"10px", "-webkit-border-radius":"10px"}); $('.content p.pages span, .content p.pages a').css({"border-radius":"6px", "-moz-border-radius":"6px", "-webkit-border-radius":"6px"}); //$('.content p.pages span, .content p.pages a').css({"border-radius":"16px", "-moz-border-radius":"16px", "-webkit-border-radius":"16px"}); //$('.menu_nav').css({"border-bottom-left-radius":"16px", "border-bottom-right-radius":"16px", "-moz-border-radius-bottomleft":"16px", "-moz-border-radius-bottomright":"16px", "-webkit-border-bottom-left-radius":"16px", "-webkit-border-bottom-right-radius":"16px"}); }); // Cufon Cufon.replace('h1, h2, h3, h4, h5, h6, .menu_nav ul li a, .content .mainbar .post_content a.rm', { hover: true }); //Cufon.replace('h1', { color: '-linear-gradient(#fff, #ffaf02)'}); //Cufon.replace('h1 small', { color: '#8a98a5'}); // ]]>
JavaScript
BLANK_IMAGE = 'images/b.gif'; var a=screen.width; var z=a*0.95; var x; function reload() { if(a<1024) return x=8; else if(a<1280) return x=(a-1000)/2-8; else return x=(a-1000)/2-12; var y=z*0.2; var s=screen.height-10; var t=screen.height; var f=t-128-50; } setTimeout("reload()" ,1); var STYLE = { border:1, // item's border width, pixels; zero means "none" shadow:2, // item's shadow size, pixels; zero means "none" color:{ border:"#666666", // color of the item border, if any shadow:"#DBD8D1", // color of the item shadow, if any bgON:"#6699FF", // background color for the items bgOVER:"#B6BDD2" // background color for the item which is under mouse right now }, css:{ ON:"clsCMOn", // CSS class for items OVER:"clsCMOver" // CSS class for item which is under mouse } }; var STYLE1 = { border:1, // item's border width, pixels; zero means "none" shadow:2, // item's shadow size, pixels; zero means "none" color:{ border:"#666666", // color of the item border, if any shadow:"#DBD8D1", // color of the item shadow, if any bgON:"#0066FF", // background color for the items bgOVER:"#B6BDD2" // background color for the item which is under mouse right now }, css:{ ON:"clsCMOn1", // CSS class for items OVER:"clsCMOver1" // CSS class for item which is under mouse } }; var STYLE2 = { border:1, // item's border width, pixels; zero means "none" shadow:2, // item's shadow size, pixels; zero means "none" color:{ border:"#666666", // color of the item border, if any shadow:"#DBD8D1", // color of the item shadow, if any bgON:"#0099FF", // background color for the items bgOVER:"#B6BDD2" // background color for the item which is under mouse right now }, css:{ ON:"clsCMOn1", // CSS class for items OVER:"clsCMOver1" // CSS class for item which is under mouse } }; var STYLE3 = { border:1, // item's border width, pixels; zero means "none" shadow:2, // item's shadow size, pixels; zero means "none" color:{ border:"#666666", // color of the item border, if any shadow:"#DBD8D1", // color of the item shadow, if any bgON:"#0066FF", // background color for the items bgOVER:"#B6BDD2" // background color for the item which is under mouse right now }, css:{ ON:"clsCMOver1", // CSS class for items OVER:"clsCMOver1" // CSS class for item which is under mouse } }; var MENU_ITEMS = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS1 = [ {pos:[x,243],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html",style:STYLE3}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html",style:STYLE2}, {code:"Bo mạch chủ", url:"bo_mach_chu.html",style:STYLE2}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html",style:STYLE2}, {code:"Ổ cứng", url:"o_cung.html",style:STYLE2}, {code:"Màn hình", url:"man_hinh.html",style:STYLE2}, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh" }, {code:"Bộ lưu điện", url:"mbo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS2 = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html",style:STYLE3}, {code:"Acer", url:"acer.html",style:STYLE2}, {code:"Toshiba", url:"toshiba.html",style:STYLE2}, {code:"Dell", url:"dell.html",style:STYLE2}, {code:"Asus", url:"asus.html",style:STYLE2}, {code:"Sony", url:"sony.html",style:STYLE2}, {code:"HP-Compad", url:"hp_compad.html",style:STYLE2}, {code:"Lenovo", url:"Lenovo.html",style:STYLE2}, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS3 = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html",style:STYLE3}, {code:"HP server", url:"HP_server.html",style:STYLE2}, {code:"IBM server", url:"ibm_server.html",style:STYLE2}, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS4 = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html",style:STYLE3}, {code:"MP3-MP4", url:"mp3_mp4.html",style:STYLE2}, {code:"IPOD", url:"ipod.html",style:STYLE2}, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS5 = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html",style:STYLE3}, {code:"Máy Fax", url:"may_fax.html",style:STYLE2}, {code:"Máy chiếu", url:"may_chieu.html",style:STYLE2}, {code:"Máy photocopy", url:"may_photocopy.html",style:STYLE2}, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS6= [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html",style:STYLE3}, {code:"Moden", url:"moden.html",style:STYLE2}, {code:"Switch", url:"switch.html",style:STYLE2}, {code:"wireless", url:"wireless.html",style:STYLE2}, ]; var MENU_ITEMS7 = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html",style:STYLE3}, {code:"Sun power", url:"sun_power.html",style:STYLE2}, {code:"HP", url:"may_bo_hp.html",style:STYLE2}, {code:"IBM", url:"may_bo_ibm.html",style:STYLE2}, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ];
JavaScript
 function calendar(){ var day=""; var month=""; var ampm=""; var ampmhour=""; var myweekday=""; var year=""; mydate = new Date(); myday = mydate.getDay(); mymonth = mydate.getMonth(); myweekday= mydate.getDate(); weekday= myweekday; myhours = mydate.getHours(); year=mydate.getYear(); if(year < 2000){ year = year + 1900 } ampmhour = (myhours > 12) ? myhours - 12 : myhours; ampm = (myhours >= 12) ? ' PM' : ' AM'; mytime = mydate.getMinutes(); myminutes = ((mytime < 10) ? ':0' : ':') + mytime; if(myday == 0) day = " Ch&#7911; nh&#7853;t, "; else if(myday == 1) day = " Th&#7913; hai, "; else if(myday == 2) day = " Th&#7913; ba, "; else if(myday == 3) day = " Th&#7913; t&#432;, "; else if(myday == 4) day = " Th&#7913; n&#259;m, "; else if(myday == 5) day = " Th&#7913; s&#225;u, "; else if(myday == 6) day = " Th&#7913; b&#7843;y, "; if(mymonth == 0) { month = " th&#225;ng 1 ";} else if(mymonth ==1) month = " th&#225;ng 2 "; else if(mymonth ==2) month = " th&#225;ng 3 "; else if(mymonth ==3) month = " th&#225;ng 4 "; else if(mymonth ==4) month = " th&#225;ng 5 "; else if(mymonth ==5) month = " th&#225;ng 6 "; else if(mymonth ==6) month = " th&#225;ng 7 "; else if(mymonth ==7) month = " th&#225;ng 8 "; else if(mymonth ==8) month = " th&#225;ng 9 "; else if(mymonth ==9) month = " th&#225;ng 10 "; else if(mymonth ==10) month = " th&#225;ng 11 "; else if(mymonth ==11) month = " th&#225;ng 12 "; document.write("<div align='center'>") //document.write(day + "ng&#224;y "+ myweekday + month + " n&#259;m " + year); document.write(day + myweekday + "/" + (mymonth+1) + "/" + year); document.write("</div>"); } function kiemtra() { var hoten=document.frmykien.txthoten.value; var dienthoai=document.frmykien.txtdienthoai.value; var email=document.frmykien.txtemail.value; var diachi=document.frmykien.txtdiachi.value; var ykien=document.frmykien.txtykien.value; var emailFilter=/^.+@.+\..{2,3}$/; if(hoten=="") { alert("Họ tên không được để trống"); document.frmykien.txthoten.focus(); } else if(dienthoai="") { alert("Số điện thoại không được đẻ trống"); document.frmykien.txtdienthoai.focus(); } else if(email=="") { alert("Email không được để trống"); document.frmykien.txtemail.focus(); } else if (!(emailFilter.test(document.frmykien.txtemail.value))) { alert( "Địa chỉ email không đúng!.\n" ); document.frmykien.txtemail.focus(); } else if(diachi=="") { alert("Địa chỉ không được để trống"); document.frmykien.txtdiachi.focus(); } else if(ykien=="") { alert("Phần ý kiến không được đê trống"); document.frmykien.txtykien.focus(); } else { alert("ý kiến của bạn đã được gửi tới ban quản trị.Rất cảm ơn bạn đã đóng góp ý kiến"); window.history.back(1); } } function trove() { window.history.back(1); } function themgiohang() { alert("Đã thêm thành công"); window.history.back(1); } function tracuu() { var tracuu=document.frmtimkiem.txttimkiem.value; if(tracuu=="") { alert("Bạn cần nhập thông tin tìm kiếm"); document.frmtimkiem.txttimkiem.focus(); } else { window.location="ket_qua_tim_kiem.html"; } }
JavaScript
// <![CDATA[ $(function() { // Slider $('#coin-slider').coinslider({width:960,height:360,opacity:1}); // Radius Box $('.content .mainbar img.fl, .content .sidebar .gadget').css({"border-radius":"10px", "-moz-border-radius":"10px", "-webkit-border-radius":"10px"}); $('.content p.pages span, .content p.pages a').css({"border-radius":"6px", "-moz-border-radius":"6px", "-webkit-border-radius":"6px"}); //$('.content p.pages span, .content p.pages a').css({"border-radius":"16px", "-moz-border-radius":"16px", "-webkit-border-radius":"16px"}); //$('.menu_nav').css({"border-bottom-left-radius":"16px", "border-bottom-right-radius":"16px", "-moz-border-radius-bottomleft":"16px", "-moz-border-radius-bottomright":"16px", "-webkit-border-bottom-left-radius":"16px", "-webkit-border-bottom-right-radius":"16px"}); }); // Cufon Cufon.replace('h1, h2, h3, h4, h5, h6, .menu_nav ul li a, .content .mainbar .post_content a.rm', { hover: true }); //Cufon.replace('h1', { color: '-linear-gradient(#fff, #ffaf02)'}); //Cufon.replace('h1 small', { color: '#8a98a5'}); // ]]>
JavaScript
BLANK_IMAGE = 'images/b.gif'; var a=screen.width; var z=a*0.95; var x; function reload() { if(a<1024) return x=8; else if(a<1280) return x=(a-1000)/2-8; else return x=(a-1000)/2-12; var y=z*0.2; var s=screen.height-10; var t=screen.height; var f=t-128-50; } setTimeout("reload()" ,1); var STYLE = { border:1, // item's border width, pixels; zero means "none" shadow:2, // item's shadow size, pixels; zero means "none" color:{ border:"#666666", // color of the item border, if any shadow:"#DBD8D1", // color of the item shadow, if any bgON:"#6699FF", // background color for the items bgOVER:"#B6BDD2" // background color for the item which is under mouse right now }, css:{ ON:"clsCMOn", // CSS class for items OVER:"clsCMOver" // CSS class for item which is under mouse } }; var STYLE1 = { border:1, // item's border width, pixels; zero means "none" shadow:2, // item's shadow size, pixels; zero means "none" color:{ border:"#666666", // color of the item border, if any shadow:"#DBD8D1", // color of the item shadow, if any bgON:"#0066FF", // background color for the items bgOVER:"#B6BDD2" // background color for the item which is under mouse right now }, css:{ ON:"clsCMOn1", // CSS class for items OVER:"clsCMOver1" // CSS class for item which is under mouse } }; var STYLE2 = { border:1, // item's border width, pixels; zero means "none" shadow:2, // item's shadow size, pixels; zero means "none" color:{ border:"#666666", // color of the item border, if any shadow:"#DBD8D1", // color of the item shadow, if any bgON:"#0099FF", // background color for the items bgOVER:"#B6BDD2" // background color for the item which is under mouse right now }, css:{ ON:"clsCMOn1", // CSS class for items OVER:"clsCMOver1" // CSS class for item which is under mouse } }; var STYLE3 = { border:1, // item's border width, pixels; zero means "none" shadow:2, // item's shadow size, pixels; zero means "none" color:{ border:"#666666", // color of the item border, if any shadow:"#DBD8D1", // color of the item shadow, if any bgON:"#0066FF", // background color for the items bgOVER:"#B6BDD2" // background color for the item which is under mouse right now }, css:{ ON:"clsCMOver1", // CSS class for items OVER:"clsCMOver1" // CSS class for item which is under mouse } }; var MENU_ITEMS = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS1 = [ {pos:[x,243],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html",style:STYLE3}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html",style:STYLE2}, {code:"Bo mạch chủ", url:"bo_mach_chu.html",style:STYLE2}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html",style:STYLE2}, {code:"Ổ cứng", url:"o_cung.html",style:STYLE2}, {code:"Màn hình", url:"man_hinh.html",style:STYLE2}, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh" }, {code:"Bộ lưu điện", url:"mbo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS2 = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html",style:STYLE3}, {code:"Acer", url:"acer.html",style:STYLE2}, {code:"Toshiba", url:"toshiba.html",style:STYLE2}, {code:"Dell", url:"dell.html",style:STYLE2}, {code:"Asus", url:"asus.html",style:STYLE2}, {code:"Sony", url:"sony.html",style:STYLE2}, {code:"HP-Compad", url:"hp_compad.html",style:STYLE2}, {code:"Lenovo", url:"Lenovo.html",style:STYLE2}, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS3 = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html",style:STYLE3}, {code:"HP server", url:"HP_server.html",style:STYLE2}, {code:"IBM server", url:"ibm_server.html",style:STYLE2}, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS4 = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html",style:STYLE3}, {code:"MP3-MP4", url:"mp3_mp4.html",style:STYLE2}, {code:"IPOD", url:"ipod.html",style:STYLE2}, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS5 = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html",style:STYLE3}, {code:"Máy Fax", url:"may_fax.html",style:STYLE2}, {code:"Máy chiếu", url:"may_chieu.html",style:STYLE2}, {code:"Máy photocopy", url:"may_photocopy.html",style:STYLE2}, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ]; var MENU_ITEMS6= [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html", sub:[ {style:STYLE}, {code:"Sun power", url:"sun_power.html"}, {code:"HP", url:"may_bo_hp.html"}, {code:"IBM", url:"may_bo_ibm.html"} ] }, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html",style:STYLE3}, {code:"Moden", url:"moden.html",style:STYLE2}, {code:"Switch", url:"switch.html",style:STYLE2}, {code:"wireless", url:"wireless.html",style:STYLE2}, ]; var MENU_ITEMS7 = [ {pos:[x,245],itemoff:[21,0], leveloff:[0,150], style:STYLE1, size:[22,150]}, {code:"Linh kiện máy tính",url:"bo_vi_xu_li.html", sub:[ {style:STYLE}, {code:"Bộ vi xử lí", url:"bo_vi_xu_li.html"}, {code:"Bo mạch chủ", url:"bo_mach_chu.html"}, {code:"Bộ nhớ trong", url:"bo_nho_trong.html"}, {code:"Ổ cứng", url:"o_cung.html"}, {code:"Màn hình", url:"man_hinh.html"}, ] }, {code:"Máy tính xách tay",url:"acer.html", sub:[ {style:STYLE}, {code:"Acer", url:"acer.html"}, {code:"Toshiba", url:"toshiba.html"}, {code:"Dell", url:"dell.html"}, {code:"Asus", url:"asus.html"}, {code:"Sony", url:"sony.html"}, {code:"HP-Compad", url:"hp_compad.html"}, {code:"Lenovo", url:"Lenovo.html"}, ] }, {code:"Máy bộ", url:"sun_power.html",style:STYLE3}, {code:"Sun power", url:"sun_power.html",style:STYLE2}, {code:"HP", url:"may_bo_hp.html",style:STYLE2}, {code:"IBM", url:"may_bo_ibm.html",style:STYLE2}, {code:"Máy chủ",url:"HP_server.html", sub:[ {style:STYLE}, {code:"HP server", url:"HP_server.html"}, {code:"IBM server", url:"ibm_server.html"} ] }, {code:"Phần mềm máy tính", url:"phan_mem.html" }, {code:"USB Flash", url:"usb_flah.html" }, {code:"Máy ảnh", url:"may_anh.html" }, {code:"Bộ lưu điện", url:"bo_luu_dien.html" }, {code:"Phụ kiện", url:"phu_kien.html" }, {code:"Máy nghe nhạc",url:"mp3_mp4.html", sub:[ {style:STYLE}, {code:"MP3-MP4", url:"mp3_mp4.html"}, {code:"IPOD", url:"ipod.html"}, ] }, {code:"Máy văn phòng",url:"may_fax.html", sub:[ {style:STYLE}, {code:"Máy Fax", url:"may_fax.html"}, {code:"Máy chiếu", url:"may_chieu.html"}, {code:"Máy photocopy", url:"may_photocopy.html"}, ] }, {code:"Thiết bị mạng",url:"moden.html", sub:[ {style:STYLE}, {code:"Moden", url:"moden.html"}, {code:"Switch", url:"switch.html"}, {code:"wireless", url:"wireless.html"}, ] }, ];
JavaScript
 function calendar(){ var day=""; var month=""; var ampm=""; var ampmhour=""; var myweekday=""; var year=""; mydate = new Date(); myday = mydate.getDay(); mymonth = mydate.getMonth(); myweekday= mydate.getDate(); weekday= myweekday; myhours = mydate.getHours(); year=mydate.getYear(); if(year < 2000){ year = year + 1900 } ampmhour = (myhours > 12) ? myhours - 12 : myhours; ampm = (myhours >= 12) ? ' PM' : ' AM'; mytime = mydate.getMinutes(); myminutes = ((mytime < 10) ? ':0' : ':') + mytime; if(myday == 0) day = " Ch&#7911; nh&#7853;t, "; else if(myday == 1) day = " Th&#7913; hai, "; else if(myday == 2) day = " Th&#7913; ba, "; else if(myday == 3) day = " Th&#7913; t&#432;, "; else if(myday == 4) day = " Th&#7913; n&#259;m, "; else if(myday == 5) day = " Th&#7913; s&#225;u, "; else if(myday == 6) day = " Th&#7913; b&#7843;y, "; if(mymonth == 0) { month = " th&#225;ng 1 ";} else if(mymonth ==1) month = " th&#225;ng 2 "; else if(mymonth ==2) month = " th&#225;ng 3 "; else if(mymonth ==3) month = " th&#225;ng 4 "; else if(mymonth ==4) month = " th&#225;ng 5 "; else if(mymonth ==5) month = " th&#225;ng 6 "; else if(mymonth ==6) month = " th&#225;ng 7 "; else if(mymonth ==7) month = " th&#225;ng 8 "; else if(mymonth ==8) month = " th&#225;ng 9 "; else if(mymonth ==9) month = " th&#225;ng 10 "; else if(mymonth ==10) month = " th&#225;ng 11 "; else if(mymonth ==11) month = " th&#225;ng 12 "; document.write("<div align='center'>") //document.write(day + "ng&#224;y "+ myweekday + month + " n&#259;m " + year); document.write(day + myweekday + "/" + (mymonth+1) + "/" + year); document.write("</div>"); } function kiemtra() { var hoten=document.frmykien.txthoten.value; var dienthoai=document.frmykien.txtdienthoai.value; var email=document.frmykien.txtemail.value; var diachi=document.frmykien.txtdiachi.value; var ykien=document.frmykien.txtykien.value; var emailFilter=/^.+@.+\..{2,3}$/; if(hoten=="") { alert("Họ tên không được để trống"); document.frmykien.txthoten.focus(); } else if(dienthoai="") { alert("Số điện thoại không được đẻ trống"); document.frmykien.txtdienthoai.focus(); } else if(email=="") { alert("Email không được để trống"); document.frmykien.txtemail.focus(); } else if (!(emailFilter.test(document.frmykien.txtemail.value))) { alert( "Địa chỉ email không đúng!.\n" ); document.frmykien.txtemail.focus(); } else if(diachi=="") { alert("Địa chỉ không được để trống"); document.frmykien.txtdiachi.focus(); } else if(ykien=="") { alert("Phần ý kiến không được đê trống"); document.frmykien.txtykien.focus(); } else { alert("ý kiến của bạn đã được gửi tới ban quản trị.Rất cảm ơn bạn đã đóng góp ý kiến"); window.history.back(1); } } function trove() { window.history.back(1); } function themgiohang() { alert("Đã thêm thành công"); window.history.back(1); } function tracuu() { var tracuu=document.frmtimkiem.txttimkiem.value; if(tracuu=="") { alert("Bạn cần nhập thông tin tìm kiếm"); document.frmtimkiem.txttimkiem.focus(); } else { window.location="ket_qua_tim_kiem.html"; } }
JavaScript
(function($) { $('#clickme').live('click', function() { $(this).append(' Click!'); }); })(jQuery);
JavaScript
// Define the overlay, derived from google.maps.OverlayView function Label(opt_options){ // Initialization this.setValues(opt_options); // Label specific var span = this.span_ = document.createElement('span'); span.style.cssText = 'position: relative; left: 0%; top: -50px; ' + 'white-space: nowrap; border: 1px solid black; ' + 'padding: 5px; background-color: white'; var div = this.div_ = document.createElement('div'); div.appendChild(span); div.style.cssText = 'position: absolute; display: none'; }; Label.prototype = new google.maps.OverlayView; // Implement onAdd Label.prototype.onAdd = function(){ var pane = this.getPanes().overlayLayer; pane.appendChild(this.div_); // Ensures the label is redrawn if the text or position is changed. var me = this; this.listeners_ = [google.maps.event.addListener(this, 'position_changed', function(){ me.draw(); }), google.maps.event.addListener(this, 'text_changed', function(){ me.draw(); })]; }; // Implement onRemove Label.prototype.onRemove = function(){ this.div_.parentNode.removeChild(this.div_); // Label is removed from the map, stop updating its position/text. for (var i = 0, I = this.listeners_.length; i < I; ++i) { maps.google.event.removeListener(this.listeners_[i]); } }; // Implement draw Label.prototype.draw = function(){ var projection = this.getProjection(); var position = projection.fromLatLngToDivPixel(this.get('position')); var div = this.div_; div.style.left = position.x + 'px'; div.style.top = position.y + 'px'; div.style.display = 'block'; this.span_.innerHTML = this.get('text'); };
JavaScript
(function($) { /* Fix fadeIn and fadeOut cleartype bug in IE. */ $.fn.originalFadeIn = $.fn.fadeIn $.fn.fadeIn = function(speed, callback) { $(this).originalFadeIn(speed, function() { if(jQuery.browser.msie) $(this).get(0).style.removeAttribute('filter'); if(callback != undefined) callback(); }); }; $.fn.originalFadeOut = $.fn.fadeOut $.fn.fadeOut = function(speed, callback) { $(this).originalFadeOut(speed, function() { if(jQuery.browser.msie) $(this).get(0).style.removeAttribute('filter'); if(callback != undefined) callback(); }); }; /* Set better default values that work the same with every browser. */ $.ajaxSetup({cache: false, timeout: 10000}); /* If a POST request doesn't contain any data we have to add at least an * empty string, so content-length gets set. Some servers refuse to accept * the request, otherwise. */ $(document).ajaxSend(function(evt, request, options) { if (options['type'] == 'POST' && options['data'] == null) options['data'] = ''; }); })(jQuery);
JavaScript
/*! * Ajax Queue Plugin * * Homepage: http://jquery.com/plugins/project/ajaxqueue * Documentation: http://docs.jquery.com/AjaxQueue */ /** <script> $(function(){ jQuery.ajaxQueue({ url: "test.php", success: function(html){ jQuery("ul").append(html); } }); jQuery.ajaxQueue({ url: "test.php", success: function(html){ jQuery("ul").append(html); } }); jQuery.ajaxSync({ url: "test.php", success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); } }); jQuery.ajaxSync({ url: "test.php", success: function(html){ jQuery("ul").append("<b>"+html+"</b>"); } }); }); </script> <ul style="position: absolute; top: 5px; right: 5px;"></ul> */ /* * Queued Ajax requests. * A new Ajax request won't be started until the previous queued * request has finished. */ jQuery.ajaxQueue = function(o){ var _old = o.complete; o.complete = function(){ if ( _old ) _old.apply( this, arguments ); jQuery.dequeue( jQuery.ajaxQueue, "ajax" ); }; jQuery([ jQuery.ajaxQueue ]).queue("ajax", function(){ jQuery.ajax( o ); }); }; /* * Synced Ajax requests. * The Ajax request will happen as soon as you call this method, but * the callbacks (success/error/complete) won't fire until all previous * synced requests have been completed. */ jQuery.ajaxSync = function(o){ var fn = jQuery.ajaxSync.fn, data = jQuery.ajaxSync.data, pos = fn.length; fn[ pos ] = { error: o.error, success: o.success, complete: o.complete, done: false }; data[ pos ] = { error: [], success: [], complete: [] }; o.error = function(){ data[ pos ].error = arguments; }; o.success = function(){ data[ pos ].success = arguments; }; o.complete = function(){ data[ pos ].complete = arguments; fn[ pos ].done = true; if ( pos == 0 || !fn[ pos-1 ] ) for ( var i = pos; i < fn.length && fn[i].done; i++ ) { if ( fn[i].error ) fn[i].error.apply( jQuery, data[i].error ); if ( fn[i].success ) fn[i].success.apply( jQuery, data[i].success ); if ( fn[i].complete ) fn[i].complete.apply( jQuery, data[i].complete ); fn[i] = null; data[i] = null; } }; return jQuery.ajax(o); }; jQuery.ajaxSync.fn = []; jQuery.ajaxSync.data = [];
JavaScript
/*! * jquery.bgiframe * Copyright (c) 2006 Brandon Aaron (http://brandonaaron.net) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * $LastChangedDate$ * $Rev$ * * Version 2.1.1 */ (function($){ /** * The bgiframe is chainable and applies the iframe hack to get * around zIndex issues in IE6. It will only apply itself in IE6 * and adds a class to the iframe called 'bgiframe'. The iframe * is appeneded as the first child of the matched element(s) * with a tabIndex and zIndex of -1. * * By default the plugin will take borders, sized with pixel units, * into account. If a different unit is used for the border's width, * then you will need to use the top and left settings as explained below. * * NOTICE: This plugin has been reported to cause perfromance problems * when used on elements that change properties (like width, height and * opacity) a lot in IE6. Most of these problems have been caused by * the expressions used to calculate the elements width, height and * borders. Some have reported it is due to the opacity filter. All * these settings can be changed if needed as explained below. * * @example $('div').bgiframe(); * @before <div><p>Paragraph</p></div> * @result <div><iframe class="bgiframe".../><p>Paragraph</p></div> * * @param Map settings Optional settings to configure the iframe. * @option String|Number top The iframe must be offset to the top * by the width of the top border. This should be a negative * number representing the border-top-width. If a number is * is used here, pixels will be assumed. Otherwise, be sure * to specify a unit. An expression could also be used. * By default the value is "auto" which will use an expression * to get the border-top-width if it is in pixels. * @option String|Number left The iframe must be offset to the left * by the width of the left border. This should be a negative * number representing the border-left-width. If a number is * is used here, pixels will be assumed. Otherwise, be sure * to specify a unit. An expression could also be used. * By default the value is "auto" which will use an expression * to get the border-left-width if it is in pixels. * @option String|Number width This is the width of the iframe. If * a number is used here, pixels will be assume. Otherwise, be sure * to specify a unit. An experssion could also be used. * By default the value is "auto" which will use an experssion * to get the offsetWidth. * @option String|Number height This is the height of the iframe. If * a number is used here, pixels will be assume. Otherwise, be sure * to specify a unit. An experssion could also be used. * By default the value is "auto" which will use an experssion * to get the offsetHeight. * @option Boolean opacity This is a boolean representing whether or not * to use opacity. If set to true, the opacity of 0 is applied. If * set to false, the opacity filter is not applied. Default: true. * @option String src This setting is provided so that one could change * the src of the iframe to whatever they need. * Default: "javascript:false;" * * @name bgiframe * @type jQuery * @cat Plugins/bgiframe * @author Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net) */ $.fn.bgIframe = $.fn.bgiframe = function(s) { // This is only for IE6 if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) { s = $.extend({ top : 'auto', // auto == .currentStyle.borderTopWidth left : 'auto', // auto == .currentStyle.borderLeftWidth width : 'auto', // auto == offsetWidth height : 'auto', // auto == offsetHeight opacity : true, src : 'javascript:false;' }, s || {}); var prop = function(n){return n&&n.constructor==Number?n+'px':n;}, html = '<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+ 'style="display:block;position:absolute;z-index:-1;'+ (s.opacity !== false?'filter:Alpha(Opacity=\'0\');':'')+ 'top:'+(s.top=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')':prop(s.top))+';'+ 'left:'+(s.left=='auto'?'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')':prop(s.left))+';'+ 'width:'+(s.width=='auto'?'expression(this.parentNode.offsetWidth+\'px\')':prop(s.width))+';'+ 'height:'+(s.height=='auto'?'expression(this.parentNode.offsetHeight+\'px\')':prop(s.height))+';'+ '"/>'; return this.each(function() { if ( $('> iframe.bgiframe', this).length == 0 ) this.insertBefore( document.createElement(html), this.firstChild ); }); } return this; }; })(jQuery);
JavaScript
/*! Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * Version: 1.0.3 * Requires jQuery 1.1.3+ * Docs: http://docs.jquery.com/Plugins/livequery */ (function($) { $.extend($.fn, { livequery: function(type, fn, fn2) { var self = this, q; // Handle different call patterns if ($.isFunction(type)) fn2 = fn, fn = type, type = undefined; // See if Live Query already exists $.each( $.livequery.queries, function(i, query) { if ( self.selector == query.selector && self.context == query.context && type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) ) // Found the query, exit the each loop return (q = query) && false; }); // Create new Live Query if it wasn't found q = q || new $.livequery(this.selector, this.context, type, fn, fn2); // Make sure it is running q.stopped = false; // Run it immediately for the first time q.run(); // Contnue the chain return this; }, expire: function(type, fn, fn2) { var self = this; // Handle different call patterns if ($.isFunction(type)) fn2 = fn, fn = type, type = undefined; // Find the Live Query based on arguments and stop it $.each( $.livequery.queries, function(i, query) { if ( self.selector == query.selector && self.context == query.context && (!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped ) $.livequery.stop(query.id); }); // Continue the chain return this; } }); $.livequery = function(selector, context, type, fn, fn2) { this.selector = selector; this.context = context || document; this.type = type; this.fn = fn; this.fn2 = fn2; this.elements = []; this.stopped = false; // The id is the index of the Live Query in $.livequery.queries this.id = $.livequery.queries.push(this)-1; // Mark the functions for matching later on fn.$lqguid = fn.$lqguid || $.livequery.guid++; if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++; // Return the Live Query return this; }; $.livequery.prototype = { stop: function() { var query = this; if ( this.type ) // Unbind all bound events this.elements.unbind(this.type, this.fn); else if (this.fn2) // Call the second function for all matched elements this.elements.each(function(i, el) { query.fn2.apply(el); }); // Clear out matched elements this.elements = []; // Stop the Live Query from running until restarted this.stopped = true; }, run: function() { // Short-circuit if stopped if ( this.stopped ) return; var query = this; var oEls = this.elements, els = $(this.selector, this.context), nEls = els.not(oEls); // Set elements to the latest set of matched elements this.elements = els; if (this.type) { // Bind events to newly matched elements nEls.bind(this.type, this.fn); // Unbind events to elements no longer matched if (oEls.length > 0) $.each(oEls, function(i, el) { if ( $.inArray(el, els) < 0 ) $.event.remove(el, query.type, query.fn); }); } else { // Call the first function for newly matched elements nEls.each(function() { query.fn.apply(this); }); // Call the second function for elements no longer matched if ( this.fn2 && oEls.length > 0 ) $.each(oEls, function(i, el) { if ( $.inArray(el, els) < 0 ) query.fn2.apply(el); }); } } }; $.extend($.livequery, { guid: 0, queries: [], queue: [], running: false, timeout: null, checkQueue: function() { if ( $.livequery.running && $.livequery.queue.length ) { var length = $.livequery.queue.length; // Run each Live Query currently in the queue while ( length-- ) $.livequery.queries[ $.livequery.queue.shift() ].run(); } }, pause: function() { // Don't run anymore Live Queries until restarted $.livequery.running = false; }, play: function() { // Restart Live Queries $.livequery.running = true; // Request a run of the Live Queries $.livequery.run(); }, registerPlugin: function() { $.each( arguments, function(i,n) { // Short-circuit if the method doesn't exist if (!$.fn[n]) return; // Save a reference to the original method var old = $.fn[n]; // Create a new method $.fn[n] = function() { // Call the original method var r = old.apply(this, arguments); // Request a run of the Live Queries $.livequery.run(); // Return the original methods result return r; } }); }, run: function(id) { if (id != undefined) { // Put the particular Live Query in the queue if it doesn't already exist if ( $.inArray(id, $.livequery.queue) < 0 ) $.livequery.queue.push( id ); } else // Put each Live Query in the queue if it doesn't already exist $.each( $.livequery.queries, function(id) { if ( $.inArray(id, $.livequery.queue) < 0 ) $.livequery.queue.push( id ); }); // Clear timeout if it already exists if ($.livequery.timeout) clearTimeout($.livequery.timeout); // Create a timeout to check the queue and actually run the Live Queries $.livequery.timeout = setTimeout($.livequery.checkQueue, 20); }, stop: function(id) { if (id != undefined) // Stop are particular Live Query $.livequery.queries[ id ].stop(); else // Stop all Live Queries $.each( $.livequery.queries, function(id) { $.livequery.queries[ id ].stop(); }); } }); // Register core DOM manipulation methods $.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove'); // Run Live Queries when the Document is ready $(function() { $.livequery.play(); }); // Save a reference to the original init method var init = $.prototype.init; // Create a new init method that exposes two new properties: selector and context $.prototype.init = function(a,c) { // Call the original init and save the result var r = init.apply(this, arguments); // Copy over properties if they exist already if (a && a.selector) r.context = a.context, r.selector = a.selector; // Set properties if ( typeof a == 'string' ) r.context = c || document, r.selector = a; // Return the result return r; }; // Give the init function the jQuery prototype for later instantiation (needed after Rev 4091) $.prototype.init.prototype = $.prototype; })(jQuery);
JavaScript
/* * jQuery Form Plugin * version: 2.24 (10-MAR-2009) * @requires jQuery v1.2.2 or later * * Examples and documentation at: http://malsup.com/jquery/form/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html */ ;(function($) { /* Usage Note: ----------- Do not use both ajaxSubmit and ajaxForm on the same form. These functions are intended to be exclusive. Use ajaxSubmit if you want to bind your own submit handler to the form. For example, $(document).ready(function() { $('#myForm').bind('submit', function() { $(this).ajaxSubmit({ target: '#output' }); return false; // <-- important! }); }); Use ajaxForm when you want the plugin to manage all the event binding for you. For example, $(document).ready(function() { $('#myForm').ajaxForm({ target: '#output' }); }); When using ajaxForm, the ajaxSubmit function will be invoked for you at the appropriate time. */ /** * ajaxSubmit() provides a mechanism for immediately submitting * an HTML form using AJAX. */ $.fn.ajaxSubmit = function(options) { // fast fail if nothing selected (http://dev.jquery.com/ticket/2752) if (!this.length) { log('ajaxSubmit: skipping submit process - no element selected'); return this; } if (typeof options == 'function') options = { success: options }; // clean url (don't include hash vaue) var url = this.attr('action') || window.location.href; url = (url.match(/^([^#]+)/)||[])[1]; url = url || ''; options = $.extend({ url: url, type: this.attr('method') || 'GET' }, options || {}); // hook for manipulating the form data before it is extracted; // convenient for use with rich editors like tinyMCE or FCKEditor var veto = {}; this.trigger('form-pre-serialize', [this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-pre-serialize trigger'); return this; } // provide opportunity to alter form data before it is serialized if (options.beforeSerialize && options.beforeSerialize(this, options) === false) { log('ajaxSubmit: submit aborted via beforeSerialize callback'); return this; } var a = this.formToArray(options.semantic); if (options.data) { options.extraData = options.data; for (var n in options.data) { if(options.data[n] instanceof Array) { for (var k in options.data[n]) a.push( { name: n, value: options.data[n][k] } ); } else a.push( { name: n, value: options.data[n] } ); } } // give pre-submit callback an opportunity to abort the submit if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) { log('ajaxSubmit: submit aborted via beforeSubmit callback'); return this; } // fire vetoable 'validate' event this.trigger('form-submit-validate', [a, this, options, veto]); if (veto.veto) { log('ajaxSubmit: submit vetoed via form-submit-validate trigger'); return this; } var q = $.param(a); if (options.type.toUpperCase() == 'GET') { options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q; options.data = null; // data is null for 'get' } else options.data = q; // data is the query string for 'post' var $form = this, callbacks = []; if (options.resetForm) callbacks.push(function() { $form.resetForm(); }); if (options.clearForm) callbacks.push(function() { $form.clearForm(); }); // perform a load on the target only if dataType is not provided if (!options.dataType && options.target) { var oldSuccess = options.success || function(){}; callbacks.push(function(data) { $(options.target).html(data).each(oldSuccess, arguments); }); } else if (options.success) callbacks.push(options.success); options.success = function(data, status) { for (var i=0, max=callbacks.length; i < max; i++) callbacks[i].apply(options, [data, status, $form]); }; // are there files to upload? var files = $('input:file', this).fieldValue(); var found = false; for (var j=0; j < files.length; j++) if (files[j]) found = true; // options.iframe allows user to force iframe mode if (options.iframe || found) { // hack to fix Safari hang (thanks to Tim Molendijk for this) // see: http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d if (options.closeKeepAlive) $.get(options.closeKeepAlive, fileUpload); else fileUpload(); } else $.ajax(options); // fire 'notify' event this.trigger('form-submit-notify', [this, options]); return this; // private function for handling file uploads (hat tip to YAHOO!) function fileUpload() { var form = $form[0]; if ($(':input[name=submit]', form).length) { alert('Error: Form elements must not be named "submit".'); return; } var opts = $.extend({}, $.ajaxSettings, options); var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts); var id = 'jqFormIO' + (new Date().getTime()); var $io = $('<iframe id="' + id + '" name="' + id + '" src="about:blank" />'); var io = $io[0]; $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' }); var xhr = { // mock object aborted: 0, responseText: null, responseXML: null, status: 0, statusText: 'n/a', getAllResponseHeaders: function() {}, getResponseHeader: function() {}, setRequestHeader: function() {}, abort: function() { this.aborted = 1; $io.attr('src','about:blank'); // abort op in progress } }; var g = opts.global; // trigger ajax global events so that activity/block indicators work like normal if (g && ! $.active++) $.event.trigger("ajaxStart"); if (g) $.event.trigger("ajaxSend", [xhr, opts]); if (s.beforeSend && s.beforeSend(xhr, s) === false) { s.global && jQuery.active--; return; } if (xhr.aborted) return; var cbInvoked = 0; var timedOut = 0; // add submitting element to data if we know it var sub = form.clk; if (sub) { var n = sub.name; if (n && !sub.disabled) { options.extraData = options.extraData || {}; options.extraData[n] = sub.value; if (sub.type == "image") { options.extraData[name+'.x'] = form.clk_x; options.extraData[name+'.y'] = form.clk_y; } } } // take a breath so that pending repaints get some cpu time before the upload starts setTimeout(function() { // make sure form attrs are set var t = $form.attr('target'), a = $form.attr('action'); // update form attrs in IE friendly way form.setAttribute('target',id); if (form.getAttribute('method') != 'POST') form.setAttribute('method', 'POST'); if (form.getAttribute('action') != opts.url) form.setAttribute('action', opts.url); // ie borks in some cases when setting encoding if (! options.skipEncodingOverride) { $form.attr({ encoding: 'multipart/form-data', enctype: 'multipart/form-data' }); } // support timout if (opts.timeout) setTimeout(function() { timedOut = true; cb(); }, opts.timeout); // add "extra" data to form if provided in options var extraInputs = []; try { if (options.extraData) for (var n in options.extraData) extraInputs.push( $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />') .appendTo(form)[0]); // add iframe to doc and submit the form $io.appendTo('body'); io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false); form.submit(); } finally { // reset attrs and remove "extra" input elements form.setAttribute('action',a); t ? form.setAttribute('target', t) : $form.removeAttr('target'); $(extraInputs).remove(); } }, 10); var nullCheckFlag = 0; function cb() { if (cbInvoked++) return; io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false); var ok = true; try { if (timedOut) throw 'timeout'; // extract the server response from the iframe var data, doc; doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document; if ((doc.body == null || doc.body.innerHTML == '') && !nullCheckFlag) { // in some browsers (cough, Opera 9.2.x) the iframe DOM is not always traversable when // the onload callback fires, so we give them a 2nd chance nullCheckFlag = 1; cbInvoked--; setTimeout(cb, 100); return; } xhr.responseText = doc.body ? doc.body.innerHTML : null; xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc; xhr.getResponseHeader = function(header){ var headers = {'content-type': opts.dataType}; return headers[header]; }; if (opts.dataType == 'json' || opts.dataType == 'script') { var ta = doc.getElementsByTagName('textarea')[0]; xhr.responseText = ta ? ta.value : xhr.responseText; } else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) { xhr.responseXML = toXml(xhr.responseText); } data = $.httpData(xhr, opts.dataType); } catch(e){ ok = false; $.handleError(opts, xhr, 'error', e); } // ordering of these callbacks/triggers is odd, but that's how $.ajax does it if (ok) { opts.success(data, 'success'); if (g) $.event.trigger("ajaxSuccess", [xhr, opts]); } if (g) $.event.trigger("ajaxComplete", [xhr, opts]); if (g && ! --$.active) $.event.trigger("ajaxStop"); if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error'); // clean up setTimeout(function() { $io.remove(); xhr.responseXML = null; }, 100); }; function toXml(s, doc) { if (window.ActiveXObject) { doc = new ActiveXObject('Microsoft.XMLDOM'); doc.async = 'false'; doc.loadXML(s); } else doc = (new DOMParser()).parseFromString(s, 'text/xml'); return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null; }; }; }; /** * ajaxForm() provides a mechanism for fully automating form submission. * * The advantages of using this method instead of ajaxSubmit() are: * * 1: This method will include coordinates for <input type="image" /> elements (if the element * is used to submit the form). * 2. This method will include the submit element's name/value data (for the element that was * used to submit the form). * 3. This method binds the submit() method to the form for you. * * The options argument for ajaxForm works exactly as it does for ajaxSubmit. ajaxForm merely * passes the options argument along after properly binding events for submit elements and * the form itself. */ $.fn.ajaxForm = function(options) { return this.ajaxFormUnbind().bind('submit.form-plugin',function() { $(this).ajaxSubmit(options); return false; }).each(function() { // store options in hash $(":submit,input:image", this).bind('click.form-plugin',function(e) { var form = this.form; form.clk = this; if (this.type == 'image') { if (e.offsetX != undefined) { form.clk_x = e.offsetX; form.clk_y = e.offsetY; } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin var offset = $(this).offset(); form.clk_x = e.pageX - offset.left; form.clk_y = e.pageY - offset.top; } else { form.clk_x = e.pageX - this.offsetLeft; form.clk_y = e.pageY - this.offsetTop; } } // clear form vars setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10); }); }); }; // ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm $.fn.ajaxFormUnbind = function() { this.unbind('submit.form-plugin'); return this.each(function() { $(":submit,input:image", this).unbind('click.form-plugin'); }); }; /** * formToArray() gathers form element data into an array of objects that can * be passed to any of the following ajax functions: $.get, $.post, or load. * Each object in the array has both a 'name' and 'value' property. An example of * an array for a simple login form might be: * * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ] * * It is this array that is passed to pre-submit callback functions provided to the * ajaxSubmit() and ajaxForm() methods. */ $.fn.formToArray = function(semantic) { var a = []; if (this.length == 0) return a; var form = this[0]; var els = semantic ? form.getElementsByTagName('*') : form.elements; if (!els) return a; for(var i=0, max=els.length; i < max; i++) { var el = els[i]; var n = el.name; if (!n) continue; if (semantic && form.clk && el.type == "image") { // handle image inputs on the fly when semantic == true if(!el.disabled && form.clk == el) a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); continue; } var v = $.fieldValue(el, true); if (v && v.constructor == Array) { for(var j=0, jmax=v.length; j < jmax; j++) a.push({name: n, value: v[j]}); } else if (v !== null && typeof v != 'undefined') a.push({name: n, value: v}); } if (!semantic && form.clk) { // input type=='image' are not found in elements array! handle them here var inputs = form.getElementsByTagName("input"); for(var i=0, max=inputs.length; i < max; i++) { var input = inputs[i]; var n = input.name; if(n && !input.disabled && input.type == "image" && form.clk == input) a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y}); } } return a; }; /** * Serializes form data into a 'submittable' string. This method will return a string * in the format: name1=value1&amp;name2=value2 */ $.fn.formSerialize = function(semantic) { //hand off to jQuery.param for proper encoding return $.param(this.formToArray(semantic)); }; /** * Serializes all field elements in the jQuery object into a query string. * This method will return a string in the format: name1=value1&amp;name2=value2 */ $.fn.fieldSerialize = function(successful) { var a = []; this.each(function() { var n = this.name; if (!n) return; var v = $.fieldValue(this, successful); if (v && v.constructor == Array) { for (var i=0,max=v.length; i < max; i++) a.push({name: n, value: v[i]}); } else if (v !== null && typeof v != 'undefined') a.push({name: this.name, value: v}); }); //hand off to jQuery.param for proper encoding return $.param(a); }; /** * Returns the value(s) of the element in the matched set. For example, consider the following form: * * <form><fieldset> * <input name="A" type="text" /> * <input name="A" type="text" /> * <input name="B" type="checkbox" value="B1" /> * <input name="B" type="checkbox" value="B2"/> * <input name="C" type="radio" value="C1" /> * <input name="C" type="radio" value="C2" /> * </fieldset></form> * * var v = $(':text').fieldValue(); * // if no values are entered into the text inputs * v == ['',''] * // if values entered into the text inputs are 'foo' and 'bar' * v == ['foo','bar'] * * var v = $(':checkbox').fieldValue(); * // if neither checkbox is checked * v === undefined * // if both checkboxes are checked * v == ['B1', 'B2'] * * var v = $(':radio').fieldValue(); * // if neither radio is checked * v === undefined * // if first radio is checked * v == ['C1'] * * The successful argument controls whether or not the field element must be 'successful' * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls). * The default value of the successful argument is true. If this value is false the value(s) * for each element is returned. * * Note: This method *always* returns an array. If no valid value can be determined the * array will be empty, otherwise it will contain one or more values. */ $.fn.fieldValue = function(successful) { for (var val=[], i=0, max=this.length; i < max; i++) { var el = this[i]; var v = $.fieldValue(el, successful); if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length)) continue; v.constructor == Array ? $.merge(val, v) : val.push(v); } return val; }; /** * Returns the value of the field element. */ $.fieldValue = function(el, successful) { var n = el.name, t = el.type, tag = el.tagName.toLowerCase(); if (typeof successful == 'undefined') successful = true; if (successful && (!n || el.disabled || t == 'reset' || t == 'button' || (t == 'checkbox' || t == 'radio') && !el.checked || (t == 'submit' || t == 'image') && el.form && el.form.clk != el || tag == 'select' && el.selectedIndex == -1)) return null; if (tag == 'select') { var index = el.selectedIndex; if (index < 0) return null; var a = [], ops = el.options; var one = (t == 'select-one'); var max = (one ? index+1 : ops.length); for(var i=(one ? index : 0); i < max; i++) { var op = ops[i]; if (op.selected) { var v = op.value; if (!v) // extra pain for IE... v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value; if (one) return v; a.push(v); } } return a; } return el.value; }; /** * Clears the form data. Takes the following actions on the form's input fields: * - input text fields will have their 'value' property set to the empty string * - select elements will have their 'selectedIndex' property set to -1 * - checkbox and radio inputs will have their 'checked' property set to false * - inputs of type submit, button, reset, and hidden will *not* be effected * - button elements will *not* be effected */ $.fn.clearForm = function() { return this.each(function() { $('input,select,textarea', this).clearFields(); }); }; /** * Clears the selected form elements. */ $.fn.clearFields = $.fn.clearInputs = function() { return this.each(function() { var t = this.type, tag = this.tagName.toLowerCase(); if (t == 'text' || t == 'password' || tag == 'textarea') this.value = ''; else if (t == 'checkbox' || t == 'radio') this.checked = false; else if (tag == 'select') this.selectedIndex = -1; }); }; /** * Resets the form data. Causes all form elements to be reset to their original value. */ $.fn.resetForm = function() { return this.each(function() { // guard against an input with the name of 'reset' // note that IE reports the reset function as an 'object' if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType)) this.reset(); }); }; /** * Enables or disables any matching elements. */ $.fn.enable = function(b) { if (b == undefined) b = true; return this.each(function() { this.disabled = !b; }); }; /** * Checks/unchecks any matching checkboxes or radio buttons and * selects/deselects and matching option elements. */ $.fn.selected = function(select) { if (select == undefined) select = true; return this.each(function() { var t = this.type; if (t == 'checkbox' || t == 'radio') this.checked = select; else if (this.tagName.toLowerCase() == 'option') { var $sel = $(this).parent('select'); if (select && $sel[0] && $sel[0].type == 'select-one') { // deselect all other options $sel.find('option').selected(false); } this.selected = select; } }); }; // helper fn for console logging // set $.fn.ajaxSubmit.debug to true to enable debug logging function log() { if ($.fn.ajaxSubmit.debug && window.console && window.console.log) window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,'')); }; })(jQuery);
JavaScript
{% autoescape off %}{% block vars %}var map;{% endblock %} {% block functions %}{% endblock %} {% block load %}function {{ load_func }}(){ if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById("{{ dom_id }}")); map.setCenter(new GLatLng({{ center.1 }}, {{ center.0 }}), {{ zoom }}); {% block controls %}map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl());{% endblock %} {% if calc_zoom %}var bounds = new GLatLngBounds(); var tmp_bounds = new GLatLngBounds();{% endif %} {% for kml_url in kml_urls %}var kml{{ forloop.counter }} = new GGeoXml("{{ kml_url }}"); map.addOverlay(kml{{ forloop.counter }});{% endfor %} {% for polygon in polygons %}var poly{{ forloop.counter }} = new {{ polygon }}; map.addOverlay(poly{{ forloop.counter }}); {% for event in polygon.events %}GEvent.addListener(poly{{ forloop.parentloop.counter }}, {{ event }});{% endfor %} {% if calc_zoom %}tmp_bounds = poly{{ forloop.counter }}.getBounds(); bounds.extend(tmp_bounds.getSouthWest()); bounds.extend(tmp_bounds.getNorthEast());{% endif %}{% endfor %} {% for polyline in polylines %}var polyline{{ forloop.counter }} = new {{ polyline }}; map.addOverlay(polyline{{ forloop.counter }}); {% for event in polyline.events %}GEvent.addListener(polyline{{ forloop.parentloop.counter }}, {{ event }}); {% endfor %} {% if calc_zoom %}tmp_bounds = polyline{{ forloop.counter }}.getBounds(); bounds.extend(tmp_bounds.getSouthWest()); bounds.extend(tmp_bounds.getNorthEast());{% endif %}{% endfor %} {% for marker in markers %}var marker{{ forloop.counter }} = new {{ marker }}; map.addOverlay(marker{{ forloop.counter }}); {% for event in marker.events %}GEvent.addListener(marker{{ forloop.parentloop.counter }}, {{ event }}); {% endfor %} {% if calc_zoom %}bounds.extend(marker{{ forloop.counter }}.getLatLng()); {% endif %}{% endfor %} {% if calc_zoom %}map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));{% endif %} {% block load_extra %}{% endblock %} }else { alert("Sorry, the Google Maps API is not compatible with this browser."); } } {% endblock %}{% endautoescape %}
JavaScript
{% extends "gis/admin/openlayers.js" %} {% block base_layer %}new OpenLayers.Layer.OSM.Mapnik("OpenStreetMap (Mapnik)");{% endblock %}
JavaScript
{# Author: Justin Bronn, Travis Pinney & Dane Springmeyer #} {% block vars %}var {{ module }} = {}; {{ module }}.map = null; {{ module }}.controls = null; {{ module }}.panel = null; {{ module }}.re = new RegExp("^SRID=\d+;(.+)", "i"); {{ module }}.layers = {}; {{ module }}.wkt_f = new OpenLayers.Format.WKT(); {{ module }}.is_collection = {{ is_collection|yesno:"true,false" }}; {{ module }}.collection_type = '{{ collection_type }}'; {{ module }}.is_linestring = {{ is_linestring|yesno:"true,false" }}; {{ module }}.is_polygon = {{ is_polygon|yesno:"true,false" }}; {{ module }}.is_point = {{ is_point|yesno:"true,false" }}; {% endblock %} {{ module }}.get_ewkt = function(feat){return 'SRID={{ srid }};' + {{ module }}.wkt_f.write(feat);} {{ module }}.read_wkt = function(wkt){ // OpenLayers cannot handle EWKT -- we make sure to strip it out. // EWKT is only exposed to OL if there's a validation error in the admin. var match = {{ module }}.re.exec(wkt); if (match){wkt = match[1];} return {{ module }}.wkt_f.read(wkt); } {{ module }}.write_wkt = function(feat){ if ({{ module }}.is_collection){ {{ module }}.num_geom = feat.geometry.components.length;} else { {{ module }}.num_geom = 1;} document.getElementById('{{ id }}').value = {{ module }}.get_ewkt(feat); } {{ module }}.add_wkt = function(event){ // This function will sync the contents of the `vector` layer with the // WKT in the text field. if ({{ module }}.is_collection){ var feat = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.{{ geom_type }}()); for (var i = 0; i < {{ module }}.layers.vector.features.length; i++){ feat.geometry.addComponents([{{ module }}.layers.vector.features[i].geometry]); } {{ module }}.write_wkt(feat); } else { // Make sure to remove any previously added features. if ({{ module }}.layers.vector.features.length > 1){ old_feats = [{{ module }}.layers.vector.features[0]]; {{ module }}.layers.vector.removeFeatures(old_feats); {{ module }}.layers.vector.destroyFeatures(old_feats); } {{ module }}.write_wkt(event.feature); } } {{ module }}.modify_wkt = function(event){ if ({{ module }}.is_collection){ if ({{ module }}.is_point){ {{ module }}.add_wkt(event); return; } else { // When modifying the selected components are added to the // vector layer so we only increment to the `num_geom` value. var feat = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.{{ geom_type }}()); for (var i = 0; i < {{ module }}.num_geom; i++){ feat.geometry.addComponents([{{ module }}.layers.vector.features[i].geometry]); } {{ module }}.write_wkt(feat); } } else { {{ module }}.write_wkt(event.feature); } } // Function to clear vector features and purge wkt from div {{ module }}.deleteFeatures = function(){ {{ module }}.layers.vector.removeFeatures({{ module }}.layers.vector.features); {{ module }}.layers.vector.destroyFeatures(); } {{ module }}.clearFeatures = function (){ {{ module }}.deleteFeatures(); document.getElementById('{{ id }}').value = ''; {{ module }}.map.setCenter(new OpenLayers.LonLat({{ default_lon }}, {{ default_lat }}), {{ default_zoom }}); } // Add Select control {{ module }}.addSelectControl = function(){ var select = new OpenLayers.Control.SelectFeature({{ module }}.layers.vector, {'toggle' : true, 'clickout' : true}); {{ module }}.map.addControl(select); select.activate(); } {{ module }}.enableDrawing = function(){ {{ module }}.map.getControlsByClass('OpenLayers.Control.DrawFeature')[0].activate();} {{ module }}.enableEditing = function(){ {{ module }}.map.getControlsByClass('OpenLayers.Control.ModifyFeature')[0].activate();} // Create an array of controls based on geometry type {{ module }}.getControls = function(lyr){ {{ module }}.panel = new OpenLayers.Control.Panel({'displayClass': 'olControlEditingToolbar'}); var nav = new OpenLayers.Control.Navigation(); var draw_ctl; if ({{ module }}.is_linestring){ draw_ctl = new OpenLayers.Control.DrawFeature(lyr, OpenLayers.Handler.Path, {'displayClass': 'olControlDrawFeaturePath'}); } else if ({{ module }}.is_polygon){ draw_ctl = new OpenLayers.Control.DrawFeature(lyr, OpenLayers.Handler.Polygon, {'displayClass': 'olControlDrawFeaturePolygon'}); } else if ({{ module }}.is_point){ draw_ctl = new OpenLayers.Control.DrawFeature(lyr, OpenLayers.Handler.Point, {'displayClass': 'olControlDrawFeaturePoint'}); } {% if modifiable %} var mod = new OpenLayers.Control.ModifyFeature(lyr, {'displayClass': 'olControlModifyFeature'}); {{ module }}.controls = [nav, draw_ctl, mod]; {% else %} {{ module }}.controls = [nav, darw_ctl]; {% endif %} } {{ module }}.init = function(){ {% block map_options %}// The options hash, w/ zoom, resolution, and projection settings. var options = { {% autoescape off %}{% for item in map_options.items %} '{{ item.0 }}' : {{ item.1 }}{% if not forloop.last %},{% endif %} {% endfor %}{% endautoescape %} };{% endblock %} // The admin map for this geometry field. {{ module }}.map = new OpenLayers.Map('{{ id }}_map', options); // Base Layer {{ module }}.layers.base = {% block base_layer %}new OpenLayers.Layer.WMS( "{{ wms_name }}", "{{ wms_url }}", {layers: '{{ wms_layer }}'} );{% endblock %} {{ module }}.map.addLayer({{ module }}.layers.base); {% block extra_layers %}{% endblock %} {% if is_linestring %}OpenLayers.Feature.Vector.style["default"]["strokeWidth"] = 3; // Default too thin for linestrings. {% endif %} {{ module }}.layers.vector = new OpenLayers.Layer.Vector(" {{ field_name }}"); {{ module }}.map.addLayer({{ module }}.layers.vector); // Read WKT from the text field. var wkt = document.getElementById('{{ id }}').value; if (wkt){ // After reading into geometry, immediately write back to // WKT <textarea> as EWKT (so that SRID is included). var admin_geom = {{ module }}.read_wkt(wkt); {{ module }}.write_wkt(admin_geom); if ({{ module }}.is_collection){ // If geometry collection, add each component individually so they may be // edited individually. for (var i = 0; i < {{ module }}.num_geom; i++){ {{ module }}.layers.vector.addFeatures([new OpenLayers.Feature.Vector(admin_geom.geometry.components[i].clone())]); } } else { {{ module }}.layers.vector.addFeatures([admin_geom]); } // Zooming to the bounds. {{ module }}.map.zoomToExtent(admin_geom.geometry.getBounds()); } else { {{ module }}.map.setCenter(new OpenLayers.LonLat({{ default_lon }}, {{ default_lat }}), {{ default_zoom }}); } // This allows editing of the geographic fields -- the modified WKT is // written back to the content field (as EWKT, so that the ORM will know // to transform back to original SRID). {{ module }}.layers.vector.events.on({"featuremodified" : {{ module }}.modify_wkt}); {{ module }}.layers.vector.events.on({"featureadded" : {{ module }}.add_wkt}); {% block controls %} // Map controls: // Add geometry specific panel of toolbar controls {{ module }}.getControls({{ module }}.layers.vector); {{ module }}.panel.addControls({{ module }}.controls); {{ module }}.map.addControl({{ module }}.panel); {{ module }}.addSelectControl(); // Then add optional visual controls {% if mouse_position %}{{ module }}.map.addControl(new OpenLayers.Control.MousePosition());{% endif %} {% if scale_text %}{{ module }}.map.addControl(new OpenLayers.Control.Scale());{% endif %} {% if layerswitcher %}{{ module }}.map.addControl(new OpenLayers.Control.LayerSwitcher());{% endif %} // Then add optional behavior controls {% if not scrollable %}{{ module }}.map.getControlsByClass('OpenLayers.Control.Navigation')[0].disableZoomWheel();{% endif %} {% endblock %} if (wkt){ {{ module }}.enableEditing(); } else { {{ module }}.enableDrawing(); } }
JavaScript
window.site_data = {};window.site_data.settings = {"MEDIA_URL": "/media/1/"};
JavaScript
var LANGUAGE_CODE = "de"; var LANGUAGE_BIDI = false; /* gettext library */ var catalog = new Array(); function pluralidx(count) { return (count == 1) ? 0 : 1; } function gettext(msgid) { var value = catalog[msgid]; if (typeof(value) == 'undefined') { return msgid; } else { return (typeof(value) == 'string') ? value : value[0]; } } function ngettext(singular, plural, count) { value = catalog[singular]; if (typeof(value) == 'undefined') { return (count == 1) ? singular : plural; } else { return value[pluralidx(count)]; } } function gettext_noop(msgid) { return msgid; } function interpolate(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])}); } else { return fmt.replace(/%s/g, function(match){return String(obj.shift())}); } } window.hgettext = function(text) { return gettext(text); }; window.hngettext = function(singular, plural, count) { return ngettext(singular, plural, count); };
JavaScript
var LANGUAGE_CODE = "en"; var LANGUAGE_BIDI = false; /* gettext library */ var catalog = new Array(); function pluralidx(count) { return (count == 1) ? 0 : 1; } function gettext(msgid) { var value = catalog[msgid]; if (typeof(value) == 'undefined') { return msgid; } else { return (typeof(value) == 'string') ? value : value[0]; } } function ngettext(singular, plural, count) { value = catalog[singular]; if (typeof(value) == 'undefined') { return (count == 1) ? singular : plural; } else { return value[pluralidx(count)]; } } function gettext_noop(msgid) { return msgid; } function interpolate(fmt, obj, named) { if (named) { return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])}); } else { return fmt.replace(/%s/g, function(match){return String(obj.shift())}); } } window.hgettext = function(text) { return gettext(text); }; window.hngettext = function(singular, plural, count) { return ngettext(singular, plural, count); };
JavaScript
$(document).one('ready', function(){ // Append stylesheets addLinks([ 'http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css', 'examples.css', '../dist/kmltree.css' ]); $.ajaxSetup({ dataType: 'script' }); $.when( $.ajax({url: 'http://geojs.googlecode.com/svn/trunk/dist/geo.pack.js'}), $.ajax({url: 'http://earth-api-utility-library.googlecode.com/svn/trunk/extensions/dist/extensions.pack.js'}), $.ajax({url: '../dist/kmltree.min.js'}) ) .then(function(){ var t = $('#sample').html(); jQuery.globalEval(t); $(document).trigger('ready'); setTimeout(function(){ resizeMap3d(); }, 100); setTimeout(function(){ if(tree){ $('a.src').attr('href', tree.url); } }, 2000); }) .fail(function(){ alert('error loading scripts'); }) $('.description').before($('<a class="src" href="#">source kml</a><h1><a href="http://code.google.com/p/kmltree/">kmltree</a> > <a href="http://code.google.com/p/kmltree/wiki/ExampleUses">examples</a> > <span class="breadcrumb-end"></span></h1><div id="tree"></div><div id="tree2"></div><div id="map3d"></div><br style="clear:both;">')); $('span.breadcrumb-end').text($('title').text()); $('.content').append('<pre class="prettyprint" id="codeSample"></pre>'); $('#codeSample').text($('#sample').html()); jQuery.getScript('http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js', function(){ prettyPrint(); }); $(window).resize(function(){ resizeMap3d(); }); }); function resizeMap3d(){ var cw = $('.content').width(); var tw = $('#tree').width(); var mw = $('#map3d').width(); $('#map3d').width(cw - tw - 23); } function addLink(href){ var link = $("<link/>").appendTo($("head")); link.attr({ rel: "stylesheet", href: href }); } function addLinks(hrefs){ for(var i=0;i<hrefs.length;i++){ addLink(hrefs[i]); } }
JavaScript
// src/kmltree.js // I don't like documentation being in more than one place, and I couldn't // find any javascript documentation tools that I found satisfactory. So, // docs can be found on the project page and should be kept up to date there: // http://code.google.com/p/kmltree/wiki/ApiReference var kmltree = (function(){ // can be removed when the following ticket is resolved: // http://code.google.com/p/earth-api-samples/issues/detail?id=290 function qualifyURL(url) { var a = document.createElement('a'); a.href = url; return a.href; } var NetworkLinkQueue = function(opts){ if(opts['success'] && opts['error'] && opts['tree']){ this.queue = []; this.opts = opts; }else{ throw('missing required option'); } }; NetworkLinkQueue.prototype.add = function(node, callback){ this.queue.push({ node: node, callback: callback, loaded: false, errors: false }); }; NetworkLinkQueue.prototype.execute = function(){ if(this.queue.length === 0){ this.opts['success']([]); }else{ for(var i=0;i<this.queue.length;i++){ var item = this.queue[i]; item.node.data('queueItem', item); if(!item.loaded && !item.loading){ var self = this; $(item.node).bind('loaded', function(e, node, kmlObject){ self.nodeLoadedCallback(e, node, kmlObject) }); // This handler could be a bit smarter? $(item.node).bind('error', function(e, node, kmlObject){ self.nodeLoadedCallback(e, node, kmlObject) }); this.opts['tree'].openNetworkLink(item.node); item.loading = true; } } } }; NetworkLinkQueue.prototype.nodeLoadedCallback = function(e, node, kmlObj){ var item = node.data('queueItem'); if(item.loaded === true){ throw('event listener fired twice for ' + node.find('>span.name').text()); } item.loaded = true; item.loading = false; $(node).unbind('loaded'); item.callback(node); this.execute(); this.finish(item); }; NetworkLinkQueue.prototype.finish = function(item){ var done = true; var noerrors = true; for(var i=0;i<this.queue.length;i++){ done = (done && this.queue[i].loaded); noerrors = (noerrors && !this.queue[i].errors); } if(done){ if(noerrors){ this.opts['success'](this.queue); this.destroy(); }else{ this.opts['error'](this.queue); this.destroy(); } } }; NetworkLinkQueue.prototype.destroy = function(){ for(var i=0;i<this.queue.length;i++){ var item = this.queue[i]; item.node.unbind('load'); } this.queue = []; }; // Returns a jquery object representing a kml file var template = tmpl([ '<li UNSELECTABLE="on" id="<%= id %>" class="kmltree-item ', '<%= listItemType %> ', '<%= type %> ', '<%= classname %> ', '<%= (visible ? "visible " : "") %>', '<%= (customIcon ? "hasIcon " : "") %>', '<%= (alwaysRenderNodes ? "alwaysRenderNodes " : "") %>', '<%= (select ? "select " : "") %>', '<%= (open ? "open " : "") %>', '<%= (description ? "hasDescription " : "") %>', '<%= (snippet ? "hasSnippet " : "") %>', '<%= (customIcon ? "customIcon " : "") %>', '<% if(kmlId){ %>', '<%= kmlId %> ', '<% } %>', '<% if(geoType){ %>', '<%= geoType %>', '<% } %>', '"', '<% if(kmlId){ %>', ' data-id="<%= kmlId %>"', '<% } %>', '>', '<div UNSELECTABLE="on" class="expander">&nbsp;</div>', '<div UNSELECTABLE="on" class="toggler">&nbsp;</div>', '<div ', '<% if(customIcon){ %>', 'style="background:url(<%= customIcon %>); -moz-background-size:16px 16px; -webkit-background-size:16px 16px;"', '<% } %>', 'class="icon">', '<% if(type === "KmlNetworkLink"){ %>', '<div class="nlSpinner">&nbsp;</div>', '<% } %>', '&nbsp;', '</div>', '<span UNSELECTABLE="on" class="name"><%= name %></span>', '<% if(snippet){ %>', '<p UNSELECTABLE="on" class="snippet"><%= snippet %></p>', '<% } %>', '<% if(children.length) { %>', '<ul><%= renderOptions(children) %></ul>', '<% } %>', '</li>' ].join('')); var constructor_defaults = { refreshWithState: true, bustCache: false, restoreState: false, whitelist: [], supportItemIcon: false, loadingMsg: 'Loading data', setExtent: false, displayDocumentRoot: 'auto', displayEnhancedContent: false, iframeSandbox: 'http://kmltree.googlecode.com/hg/src/iframe.html', unknownIframeDimensionsDefault: {height: 450, width:530}, sandboxedBalloonCallback: function(){}, selectable: function(kmlObject){return false;}, multipleSelect: false, classname: function(kmlObject){return ''} }; return function(opts){ var that = {}; var errorCount = 0; var lookupTable = {}; that.lookupTable = lookupTable; that.kmlObject = null; var docs = []; var opts = jQuery.extend({}, constructor_defaults, opts); var ge = opts.gex.pluginInstance; var destroyed = false; var internalState = {}; var selectData = []; that.url = opts.url; function clearSelectData(){ selectData = []; } function indexOfSelectData(node, kmlObject){ for(var i=0;i<selectData.length;i++){ if($(selectData[i]['node'])[0] === $(node)[0]){ return i; } } return -1; }; function addSelectData(node, kmlObject){ var index = indexOfSelectData(node, kmlObject); if(index === -1){ selectData.push({'node': node, 'kmlObject': kmlObject}); } } function removeSelectData(node, kmlObject){ var index = indexOfSelectData(node, kmlObject); if(index === -1){ throw('removeSelectData error'); }else{ selectData.splice(index, 1); } } if(parseFloat(ge.getApiVersion()) < 1.005){ alert('kmltree requires a google earth plugin version >= 1.005'); } if(!opts.url || !opts.gex || !opts.element || !opts.mapElement){ throw('kmltree requires options url, gex, mapElement & element'); } opts.element = $(opts.element); if(!opts.element.attr('id')){ opts.element.attr('id', 'kml-tree'+(new Date()).getTime()); opts.element.attr('UNSELECTABLE', "on"); } if(opts.restoreState){ $(window).unload(function(){ that.destroy(); }); } if(opts.element.css('position') !== 'absolute'){ $(opts.element).css({position: 'relative'}); } // check for background-size support var div = $(['<div class="kmltree" style="', 'background-size: 16px 16px; ', '-moz-background-size: 16px 16px; ', '-o-background-size: 16px 16px; ', '-webkit-background-size: 16px 16px; ', '-khtml-background-size: 16px 16px;"></div>'].join('')); var supportsBgSize = (div[0].style.backgroundSize !== undefined || div[0].style.MozBackgroundSize !== undefined || div[0].style.oBackgroundSize !== undefined || div[0].style.khtmlBackgroundSize !== undefined || div[0].style.webkitBackgroundSize !== undefined); var buildOptions = function(kmlObject, docUrl, extra_scope){ var options = {name: kmlObject.getName(), id: 'kml' + (extra_scope ? extra_scope.replace(/\W/g, '-') : '') + docUrl.replace(/\W/g, '-')}; google.earth.executeBatch(ge, function(){ opts.gex.dom.walk({ visitCallback: function(context){ var parent = context.current; if(!parent.children){ parent.children = []; } var name = this.getName(); var id = addLookup(this, parent.id, docUrl, name); var snippet = this.getSnippet(); // To support generated output from certain software // (Arc2Earth, etc) if(!snippet || snippet === 'empty'){ snippet = false; } var type = this.getType(); var geotype = false; if(type === 'KmlPlacemark'){ var geo = this.getGeometry(); if(geo){ geotype = geo.getType(); } } var style = this.getComputedStyle(); var selectable = opts.selectable; if(typeof selectable === 'function'){ selectable = selectable(this); } selectable = selectable && this.getId(); var child = { renderOptions: renderOptions, name: name || '&nbsp;', visible: !!this.getVisibility(), type: type, open: this.getOpen(), id: id, description: this.getDescription(), snippet: snippet, select: selectable, listItemType: getListItemType(style), customIcon: customIcon(this), classname: opts.classname(this), children: [], alwaysRenderNodes: false, kmlId: this.getId().replace(/\W/g, '-'), geoType: geotype } parent.children.push(child); if(child.listItemType !== 'checkHideChildren'){ context.child = child; }else{ context.walkChildren = false; } }, rootObject: kmlObject, rootContext: options }); }); return options; }; var load = function(cachebust){ if(that.kmlObject){ throw('KML already loaded'); } showLoading(); var url = qualifyURL(opts.url); if(cachebust || opts.bustCache){ var buster = (new Date()).getTime(); if(url.indexOf('?') === -1){ url = url + '?cachebuster=' + buster; }else{ url = url + '&cachebuster=' + buster; } } google.earth.fetchKml(ge, url, function(kmlObject){ if(!destroyed){ processKmlObject(kmlObject, url, opts.url); } }); }; that.load = load; var refresh = function(){ if(opts.refreshWithState){ that.previousState = getState(); } clearKmlObjects(); clearLookups(); // opts.element.html(''); ge.setBalloon(null); load(true); }; that.refresh = refresh; // returns all nodes that represent a kmlObject with a matching ID var getNodesById = function(id){ return opts.element.find('.'+id.replace(/\W/g, '-')); }; that.getNodesById = getNodesById; var expandParentsOf = function(node){ node = $(node); var parent = node.parent().parent(); while(!parent.hasClass('kmltree') && !parent.find('>ul:visible').length){ parent.addClass('open'); var parent = parent.parent().parent(); } }; that.expandParentsOf = expandParentsOf; // Selects the first node found matching the ID var selectById = function(id, kmlObject, silent){ var nodes = getNodesById(id); if(nodes.length){ var node = $(nodes[0]); clearSelection(true, true); selectNode(node, kmlObject || lookup(node), silent); return true; }else{ // couldn't find feature in list. Might be in unexpanded // networklink // highlight parent networklink if feature isn't shown in // the tree yet var node = getFirstRenderedParentNetworkLink(kmlObject); if(node){ node = $(node); if(node.is(':visible')){ clearSelection(true, true); node.addClass('kmltree-breadcrumb'); if(!silent){ triggerSelect(node, kmlObject); } return true; }else{ setExpanderBreadcrumbs(node); // var parent = firstVisibleParentOf(node); node.addClass('kmltree-breadcrumb'); // setModified maybe someday if(!silent){ triggerSelect(parent, kmlObject); } } }else{ clearSelection(); return false; } } }; that.selectById = selectById; var getParentNetworkLink = function(kmlObject){ var parent = kmlObject.getParentNode(); switch(parent.getType()){ case 'KmlNetworkLink': return parent; break; case 'GEGlobe': return false; break; default: return getParentNetworkLink(parent); } }; var getFirstRenderedParentNetworkLink = function(kmlObject, loadedNl){ var treeid = opts.element.attr('id'); if(!loadedNl){ var loadedNl = []; $('#'+treeid+' li.KmlNetworkLink').each(function(){ if(!$(this).hasClass('loaded')){ loadedNl.push([this, lookup(this)]); } }); } var nL = getParentNetworkLink(kmlObject); if(nL === false){ // walked all the way up to GEGlobe, couldn't find it. return false; }else{ // if nL has an ID, look for that // look at all networklinks in tree that aren't expanded var url = nL.getLink().getHref(); for(var i=0;i<loadedNl.length;i++){ var loadedHref = loadedNl[i][1].getLink().getHref(); var nLHref = nL.getLink().getHref() if(nLHref === loadedHref){ return loadedNl[i][0]; } } // if none match, keep moving up until hitting ge globe return getFirstRenderedParentNetworkLink(nL, loadedNl); } }; var selectNode = function(node, kmlObject, silent){ if(!kmlObject){ kmlObject = lookup(node); } node = $(node); var visible = $(node).is(':visible'); // need to make this actually work toggleVisibility(node, true); node.addClass('kmltree-selected'); setModified(node, 'selected', true); if(!visible){ setExpanderBreadcrumbs(node); } if(!silent){ kmltreeManager._clearEverythingButMe(that); triggerSelect(node, kmlObject); }else{ addSelectData(node, kmlObject); } }; that.selectNode = selectNode; var selectNodes = function(nodes, silent){ var last = nodes.length - 1; nodes.each(function(i){ selectNode(this, null, !!silent || (!silent && i !== nodes.length - 1)); }); }; that.selectNodes = selectNodes; var deselectNodes = function(nodes, silent){ nodes.each(function(i){ deselectNode(this, null, !!silent || (!silent && i !== nodes.length - 1)); }); }; that.deselectNodes = deselectNodes; var deselectNode = function(node, kmlObject, silent){ if(!kmlObject){ kmlObject = lookup(node); } node = $(node); // var visible = $(node).is(':visible'); node.removeClass('kmltree-selected'); setModified(node, 'selected', false); // if(!visible){ // setExpanderBreadcrumbs(node); // } if(!silent){ removeAndTrigger(node, kmlObject); }else{ removeSelectData(node, kmlObject); } }; var triggerSelect = function(node, kmlObject){ if(node && kmlObject){ addSelectData(node, kmlObject); }else{ clearSelectData(); } setTimeout(function(){ $(that).trigger('select', [selectData]); }, 1); }; var removeAndTrigger = function(node, kmlObject){ removeSelectData(node, kmlObject); setTimeout(function(){ $(that).trigger('select', [selectData]); }, 1); } var setExpanderBreadcrumbs = function(node){ var node = $(node); var parent = node.parent().parent(); parent.addClass('kmltree-breadcrumb'); if(!parent.is(':visible')){ return setExpanderBreadcrumbs(parent); }else{ return parent; } }; var clearSelection = function(keepBalloons, dontTriggerEvent){ clearSelectData(); var treeEl = $('#'+opts.element.attr('id')); var prev = treeEl .find('.kmltree-selected').removeClass('kmltree-selected'); treeEl.find('.kmltree-breadcrumb') .removeClass('kmltree-breadcrumb'); treeEl.find('.kmltree-cursor-1').removeClass('kmltree-cursor-1'); treeEl.find('.kmltree-cursor-2').removeClass('kmltree-cursor-2'); if(prev.length){ prev.each(function(){ setModified($(this), 'selected', false); }); } if(!dontTriggerEvent){ triggerSelect(null, null); } var balloon = ge.getBalloon(); if(balloon && !keepBalloons){ ge.setBalloon(null); } } // Don't give external callers access to the keepBalloons and // dontTriggerEvent arguments that.clearSelection = function(){ return clearSelection(); }; var showLoading = function(msg){ hideLoading(); var msg = msg || opts.loadingMsg; var h = $('<div class="kmltree-loading"><span>' + msg + '</span></div>'); var height = opts.element.height(); if(height !== 0){ h.height(height); }else{ // h.height(200); } opts.element.append(h); }; that.showLoading = showLoading; var hideLoading = function(){ opts.element.find('.kmltree-loading').remove(); }; that.hideLoading = hideLoading; // url has cachebusting GET vars, original_url does not var processKmlObject = function(kmlObject, url, original_url){ internalState = {}; if (!kmlObject) { if(errorCount === 0){ errorCount++; setTimeout(function(){ // Try to reset the browser cache, then try again jQuery.ajax({ url: url, success: function(){ that.load(true); }, error: function(){ processKmlObject( kmlObject, url, original_url); } }); // try to load }, 100); return; }else{ // show error setTimeout(function() { opts.element.html([ '<div class="kmltree">', '<h4 class="kmltree-title">', 'Error Loading', '</h4>', '<p class="error">', 'could not load kml file. Try clicking ', '<a target="_blank" href="', url, '">', 'this link', '</a>', ', then refreshing the application.', '<p>', '</div>' ].join('')); $(that).trigger('kmlLoadError', [kmlObject]); }, 0); return; } } errorCount = 0; that.kmlObject = kmlObject; docs.push(kmlObject); that.kmlObject.setVisibility(true); var options = buildOptions(kmlObject, original_url); var root; if(opts.displayDocumentRoot === false){ root = options.children[0].children; }else if(opts.displayDocumentRoot === true){ root = options.children[0]; }else{ // opts.displayDocumentRoot === 'auto' var children = options.children[0].children; var i = 0; var placemarks = false; while(i < children.length && placemarks === false){ placemarks = children[i].type === 'KmlPlacemark'; i++; } if(placemarks){ root = options.children[0]; }else{ root = options.children[0].children; } } var rendered = renderOptions(root); opts.element.find('div.kmltree').remove(); opts.element.find('.kmltree-loading').before([ '<div UNSELECTABLE="on" class="kmltree">', '<h4 UNSELECTABLE="on" class="kmltree-title">', options.children[0].name, '</h4>', '<ul UNSELECTABLE="on" class="kmltree">', rendered, '</ul>', '</div>' ].join('')); ge.getFeatures().appendChild(kmlObject); if(!that.previousState){ if(opts.restoreState && !!window.localStorage){ that.previousState = getStateFromLocalStorage(); } } var queue = new NetworkLinkQueue({ success: function(links){ hideLoading(); if(opts.setExtent){ var aspectRatio = null; var m = $(opts.mapElement); if(m.length){ var aspectRatio = m.width() / m.height(); } opts.gex.util.flyToObject(kmlObject, { boundsFallback: true, aspectRatio: aspectRatio }); opts.setExtent = false; } $(that).trigger('kmlLoaded', [kmlObject]); }, error: function(links){ hideLoading(); $(that).trigger('kmlLoadError', [kmlObject]); }, tree: that }); if(that.previousState){ restoreState(that.previousState, queue); }else{ queueOpenNetworkLinks(queue, $('#' + opts.element.attr('id'))); } }; var restoreState = function(state, queue){ // go thru the whole state, opening, changing visibility, // and selecting for(var id in state){ var el = $('#'+id); if(el.length === 1){ for(var key in state[id]){ el.toggleClass(key, state[id][key]['value']); setModified(el, key, state[id][key]['value']); if(key === 'visible'){ lookup(el).setVisibility(state[id][key]['value']); } } delete state[id]; } } var links = $('#' + opts.element.attr('id')).find( 'li.KmlNetworkLink.open'); links.each(function(){ var n = $(this); // no need to open if checkHideChildren is set if(!n.hasClass('checkHideChildren') && !n.hasClass('loading') && !n.hasClass('loaded') && !n.hasClass('error')){ queue.add(n, function(loadedNode){ restoreState(state, queue); }); } }); queue.execute(); } var queueOpenNetworkLinks = function(queue, topNode){ var links = topNode.find('li.KmlNetworkLink.open'); links.each(function(){ var n = $(this); // no need to open if checkHideChildren is set if(!n.hasClass('checkHideChildren') && !n.hasClass('loading') && !n.hasClass('loaded')){ n.removeClass('open'); queue.add(n, function(loadedNode){ loadedNode.addClass('open'); setModified(loadedNode, 'open', n.hasClass('open')); queueOpenNetworkLinks(queue, loadedNode); }); } }); queue.execute(); }; var customIcon = function(kmlObject){ var result = false; if(supportsBgSize && kmlObject.getType() === 'KmlPlacemark' && kmlObject.getGeometry() && kmlObject.getGeometry().getType() === 'KmlPoint'){ result = kmlObject.getComputedStyle().getIconStyle() .getIcon().getHref(); } if(!opts.supportItemIcon){ return result; } var doc = kmldom(kmlObject.getKml()); var root = doc.find('kml>Folder, kml>Document, kml>Placemark, ' + 'kml>NetworkLink'); var href = root.find('>Style>ListStyle>ItemIcon>href').text(); if(href){ return href; }else{ return false; } } // See http://code.google.com/apis/kml/documentation/kmlreference.html#listItemType var getListItemType = function(style){ var listItemType = 'check'; var lstyle = style.getListStyle(); if(lstyle){ var ltype = lstyle.getListItemType(); switch(ltype){ case 0: // 'check' break; case 5: listItemType = 'radioFolder'; break; case 2: listItemType = 'checkOffOnly'; break; case 3: listItemType = 'checkHideChildren'; break; } } return listItemType; }; var renderOptions = function(options){ if(jQuery.isArray(options)){ var strings = []; for(var i=0;i<options.length;i++){ strings.push(_render(options[i])); } return strings.join(''); }else{ var string = _render(options); return string; } }; var defaults = { renderOptions: renderOptions }; var _render = function(options){ var s = template(jQuery.extend({}, defaults, options)); return s; }; var clearLookups = function(){ // try to clear some memory lookupTable = null; lookupTable = {}; }; // Deletes references to networklink kmlObjects, removes them from the // dom. Prepares for refresh or tree destruction. var clearNetworkLinks = function(){ $('.KmlNetworkLink').each(function(){ var kmlObject = lookup($(this)); if(kmlObject && kmlObject.getParentNode()){ opts.gex.dom.removeObject(lookup($(this))); } }); }; var clearKmlObjects = function(){ clearNetworkLinks(); if(that.kmlObject && that.kmlObject.getParentNode()){ opts.gex.dom.removeObject(that.kmlObject); // that.kmlObject.release(); } that.kmlObject = null; docs = []; }; var getStateFromLocalStorage = function(){ var json = localStorage.getItem( 'kmltree-('+opts.url+')'); if(json){ return JSON.parse(json); }else{ return false; } }; var setStateInLocalStorage = function(){ var state = JSON.stringify(getState()); localStorage.setItem('kmltree-('+opts.url+')', state); }; var destroy = function(){ destroyed = true; kmltreeManager.remove(that); if(opts.restoreState && !!window.localStorage){ setStateInLocalStorage(); } clearKmlObjects(); clearLookups(); var b = ge.getBalloon(); if(b){ var f = b.getFeature(); if(f){ var owner = kmltreeManager.getOwner(f); if(owner && owner.instance === that){ ge.setBalloon(null); } } } ge.setBalloon(null); var id = opts.element.attr('id'); $('#'+id+' li > span.name').die(); $('#'+id+' li').die(); $('#'+id+' li > .expander').die(); $(that).die(); $(that).unbind(); $('#kmltree-balloon-iframe').remove(); opts.element.html(''); }; that.destroy = destroy; var lookup = function(li){ var li = $(li); if(li.length){ return lookupTable[li.attr('id')]; }else{ return false; } }; that.lookup = lookup; var addLookup = function(kmlObject, parentID, docUrl, name){ var id = getID(kmlObject, parentID, docUrl, name); // if the ID exists already, just append the position of the // repeated name to the id. var tries = 0; while(!!lookupTable[id]){ tries++; id = id + tries; } lookupTable[id] = kmlObject; return id; }; // Returns an ID that is used on the DOM element representing this // kmlObject. If the kmlObject has it's own ID, the generated ID will // be created from that ID + the kml document's url. If not, the name // of the element and the name of it's parents will be used to // generate an ID. // // Arguments: kmlObject, parentID var getID = function(kmlObject, parentID, docUrl, name, ignoreID){ if(name){ key = name.replace(/\W/g, '-'); }else{ key = "blank" } return parentID + key; }; var setLookup = function(node, kmlObject){ lookupTable[node.attr('id')] = kmlObject; }; var toggleDown = function(node, toggling){ if(toggling){ if(node.hasClass('checkOffOnly')){ return; }else{ if(node.hasClass('radioFolder')){ if(node.find('>ul>li.visible').length){ // one node already turned on, do nothing return; }else{ var children = node.find('>ul>li'); if(children.length){ toggleItem($(children[0]), true); toggleDown($(children[0]), true); }else{ return; } } }else{ node.find('>ul>li').each(function(){ var n = $(this); if(!n.hasClass('checkOffOnly')){ toggleItem(n, true); toggleDown(n, true); } }); } } }else{ node.find('li').each(function(){ toggleItem($(this), false); }); } }; var toggleUp = function(node, toggling, from){ var parent = node.parent().parent(); if(!parent.hasClass('kmltree')){ if(toggling){ var herParent = parent.parent().parent(); if(herParent.hasClass('radioFolder')){ // toggle off any siblings and toggle them down herParent.find('>ul>li.visible').each(function(){ if(this !== parent[0]){ var sib = $(this); toggleItem(sib, false); toggleDown(sib, false); }else{ } }); } if(!parent.hasClass('visible')){ toggleItem(parent, true); toggleUp(parent, true); } }else{ if(parent.find('>ul>li.visible').length === 0){ toggleItem(parent, false); toggleUp(parent, false); } } } }; var toggleVisibility = function(node, toggle){ if(node.hasClass('checkOffOnly') && toggle){ return; } var parent = node.parent().parent(); if(parent.hasClass('radioFolder')){ parent.find('>ul>li.visible').each(function(){ toggleItem($(this), false); toggleDown($(this), false); }); } toggleItem(node, toggle); if(toggle && node.find('li.visible').length){ // if children are already toggled, do nothing }else{ toggleDown(node, toggle); } toggleUp(node, toggle); }; var toggleItem = function(node, toggling){ var node = $(node); if(node.hasClass('visible') === toggling){ return; } setModified(node, 'visible', toggling); lookup(node).setVisibility(toggling); node.toggleClass('visible', toggling); }; var setModified = function(node, key, value){ var id = node.attr('id'); if(!internalState[id]){ internalState[id] = {}; } var record = internalState[id]; if(!record[key]){ record[key] = {original: !value, value: value} }else{ record[key]['value'] = value; } }; var getState = function(){ for(var id in internalState){ for(var key in internalState[id]){ if(internalState[id][key]['original'] === internalState[id][key]['value']){ delete internalState[id][key]; } } var len = 0; for(var key in internalState[id]){ if(internalState[id].hasOwnProperty(key)){ len++; } } if(len === 0){ delete internalState[id]; } } return internalState; }; that.getState = getState; var openNetworkLink = function(node){ if(node.find('> ul').length){ throw('networklink already loaded'); }else{ var NetworkLink = lookup(node); var link = NetworkLink.getLink(); if(link){ link = link.getHref(); var original_url = link; }else{ var dom = kmldom(NetworkLink.getKml()); var href = dom.find('Url>href'); if(href.length){ var link = href.text(); var original_url = link; }else{ node.addClass('error'); // setModified(node, 'visibility', false); $(node).trigger('loaded', [node, false]); node.removeClass('open'); setModified(node, 'open', false); return; } } var uri = new URI(link); if(uri.getAuthority() === null){ var doc = NetworkLink.getOwnerDocument(); if(doc && doc.getUrl()){ var base = doc.getUrl(); if(base){ var base = new URI(base); var new_url = uri.resolve(base); } } if(!new_url){ alert(['Could not resolve relative link in kml ', 'document. You may need to upgrade to the ', 'latest Google Earth Plugin.'].join()); }else{ link = new_url.toString(); } } if(opts.bustCache){ var buster = (new Date()).getTime(); if(link.indexOf('?') === -1){ link = link + '?cachebuster=' + buster; }else{ link = link + '&cachebuster=' + buster; } } node.addClass('loading'); google.earth.fetchKml(ge, link, function(kmlObject){ if(!kmlObject){ alert('Error loading ' + link); node.addClass('error'); // setModified(node, 'visibility', false); $(that).trigger('kmlLoadError', [kmlObject]); $(node).trigger('error', [node, kmlObject]); node.removeClass('loading'); node.removeClass('open'); return; } ge.getFeatures().appendChild(kmlObject); kmlObject.setVisibility(NetworkLink.getVisibility()); var extra_scope = NetworkLink.getName(); var parent = NetworkLink.getParentNode(); parent.getFeatures().removeChild(NetworkLink); var data = buildOptions(kmlObject, original_url, extra_scope); var html = renderOptions(data.children[0].children); node.append('<ul>'+html+'</ul>'); node.addClass('open'); setModified(node, 'open', node.hasClass('open')); node.removeClass('loading'); node.addClass('loaded'); setLookup(node, kmlObject); docs.push(kmlObject); rememberNetworkLink(node, NetworkLink); $(node).trigger('loaded', [node, kmlObject]); $(that).trigger('networklinkload', [node, kmlObject, NetworkLink]); }); } }; that.openNetworkLink = openNetworkLink; var rememberedLinks = []; var rememberNetworkLink = function(node, networkLink){ $(node).attr( 'data-rememberedLink', rememberedLinks.length.toString()); $(node).data('original-networklink', networkLink); rememberedLinks.push(networkLink); }; var getNetworkLink = function(node){ var id = $(node).attr('data-rememberedLink'); if(id && rememberedLinks.length >= id){ return rememberedLinks[id]; }else{ return false; } }; that.getNetworkLink = getNetworkLink; // Creates a new NetworkLinkQueue that simply opens up the given // NetworkLink and any open NetworkLinks within it. var openNetworkLinkRecursive = function(node, callback){ var queue = new NetworkLinkQueue({ success: function(links){ if(callback){ callback(node, links); }; }, error: function(links){ }, tree: that }); queue.add(node, function(loadedNode){ loadedNode.addClass('open'); setModified(loadedNode, 'open', node.hasClass('open')); queueOpenNetworkLinks(queue, loadedNode); }); queue.execute(); } var id = opts.element.attr('id'); $('#'+id+' li > span.name').live('click', function(e){ e.stopPropagation(); var dontOpen = false; var node = $(this).parent(); var kmlObject = lookup(node); if(node.hasClass('error') && node.hasClass('KmlNetworkLink')){ if(kmlObject.getLink() && kmlObject.getLink().getHref()){ alert('Could not load NetworkLink with url ' + kmlObject.getLink().getHref()) }else{ alert('Could not load NetworkLink. Link tag with href not found'); } } if(node.hasClass('select')){ if(opts.multipleSelect && e.metaKey){ if(node.hasClass('kmltree-selected')){ $('.kmltree-cursor-1').removeClass('kmltree-cursor-1'); node.removeClass('kmltree-cursor-1'); deselectNode(node, kmlObject) }else{ $('.kmltree-cursor-1').removeClass('kmltree-cursor-1'); $('.kmltree-cursor-2').removeClass('kmltree-cursor-2'); node.addClass('kmltree-cursor-1'); selectNode(node, kmlObject); } kmltreeManager.pauseListeners(function(){ ge.setBalloon(null); }); dontOpen = true; }else if(opts.multipleSelect && e.shiftKey){ // if(node.hasClass('kmltree-selected') || node.hasClass('kmltree-breadcrumbs')){ // // do nothing // }else{ // make sure not shift+selecting something in a // different part of the tree (shift select only works // with siblings) var treeEl = $('#'+opts.element.attr('id')); selected = treeEl.find('.kmltree-selected'); if(selected.length === 1){ selected.addClass('kmltree-cursor-1'); } var cursor1 = treeEl.find('.kmltree-cursor-1'); if(cursor1.length === 0){ // just do a normal selection clearSelection(true, true); selectNode(node, kmlObject); }else{ var parent = node.parent().parent(); var first_cursor = treeEl.find('.kmltree-cursor-1'); if(first_cursor.parent().parent()[0] !== parent[0]){ // do nothing. can only shift-select siblings }else{ var cursor2 = treeEl.find('.kmltree-cursor-2'); if(cursor2.length){ var cursors = treeEl.find('.kmltree-cursor-1, .kmltree-cursor-2'); var first = cursors.first(); var last = cursors.last() var siblings = first.parent().parent().find('> ul > li'); // already have a range selected. Need to deselect var range = first.nextUntil('[id="'+last.attr('id')+'"]').andSelf().add(last); cursor2.removeClass('kmltree-cursor-2'); deselectNodes(range, true) } node.addClass('kmltree-cursor-2'); var cursors = treeEl.find('.kmltree-cursor-1, .kmltree-cursor-2'); var first = cursors.first(); var last = cursors.last(); var range; if(first[0] === last[0]){ // just one is selected range = first; treeEl.find('.kmltree-cursor-1, .kmltree-cursor-2').removeClass('kmltree-cursor-2').removeClass('kmltree-cursor-1'); }else{ var siblings = first.parent().parent().find('> ul > li'); var range = first.nextUntil('[id="'+last.attr('id')+'"]').andSelf().add(last); } selectNodes(range); kmltreeManager.pauseListeners(function(){ ge.setBalloon(null); }); } // if(selected.first) // get furthest selected sibling // deselect everything quickly // select range dontOpen = true; } }else{ clearSelection(true, true); selectNode(node, kmlObject); } }else{ clearSelection(); node.addClass('kmltree-cursor-1'); if(node.hasClass('hasDescription') || kmlObject.getType() === 'KmlPlacemark'){ if(kmlObject.getType() === 'KmlPlacemark'){ toggleVisibility(node, true); } } } if(!dontOpen){ if(kmlObject.getType() === 'KmlPlacemark' || kmlObject.getDescription()){ kmltreeManager.pauseListeners(function(){ kmltreeManager._openBalloon(kmlObject, that); }); } } $(that).trigger('click', [node[0], kmlObject]); }); $('#'+id+' li').live('contextmenu', function(e){ var node = $(this); if(node.hasClass('select')){ if(!node.hasClass('kmltree-selected')){ clearSelection(true, true); selectNode(node); } setTimeout(function(){ // Set timeout so that it fires after select event if // selecting new feature $(that).trigger('context', [selectData]); }, 2); } e.preventDefault(); return false; }); // Events to handle clearing selection opts.element.click(function(e){ var el = $(e.target); var fire = false; if(e.target === this){ fire = true; }else{ if(el.hasClass('toggle') && !el.hasClass('select')){ fire = true; } } if(el.find('.kmltree-selected').length || el.find('.kmltree-breadcrumb').length){ clearSelection(); } }); // expand events $('#'+id+' li > .expander').live('click', function(e){ var el = $(this).parent(); var closing = el.hasClass('open'); if(el.hasClass('KmlNetworkLink') && !el.hasClass('loaded') && !el.hasClass('loading')){ openNetworkLinkRecursive(el, function(node, links){ if(node.hasClass('kmltree-breadcrumb')){ if(closing){ if(el.find('.kmltree-selected').length){ el.addClass('kmltree-breadcrumb'); } }else{ el.removeClass('kmltree-breadcrumb'); } var kmlObject = ge.getBalloon().getFeature(); selectById(kmlObject.getId(), kmlObject, true); } }); }else{ el.toggleClass('open'); setModified(el, 'open', el.hasClass('open')); if(closing){ if(el.find('.kmltree-selected').length){ el.addClass('kmltree-breadcrumb'); } }else{ el.removeClass('kmltree-breadcrumb'); } } }); $('#'+id+' li > .toggler').live('click', function(){ var node = $(this).parent(); var toggle = !node.hasClass('visible'); if(!toggle && node.hasClass('kmltree-selected')){ clearSelection(); } if(!toggle && ge.getBalloon()){ ge.setBalloon(null); } if(node.hasClass('checkOffOnly') && toggle){ // do nothing. Should not be able to toggle-on from this node. return; }else{ if(node.hasClass('KmlNetworkLink') && node.hasClass('alwaysRenderNodes') && !node.hasClass('open') && !node.hasClass('loading') && !node.hasClass('loaded')){ openNetworkLinkRecursive(node); $(node).bind('loaded', function(e, node, kmlObject){ toggleVisibility(node, true); node.removeClass('open'); }); }else{ toggleVisibility(node, toggle); } $(that).trigger('toggleItem', [node, toggle, lookup(node)]); } }); $('#'+id+' li').live('dblclick', function(e){ e.stopPropagation(); var target = $(e.target); var parent = target.parent(); if(target.hasClass('expander') || target.hasClass('toggler') || parent.hasClass('expander') || parent.hasClass('toggler')){ // dblclicking the expander icon or checkbox should not zoom return; } var node = $(this); var kmlObject = lookup(node); if(node.hasClass('error')){ if(kmlObject.getLink() && kmlObject.getLink().getHref()){ alert('Could not load NetworkLink with url ' + kmlObject.getLink().getHref()) }else{ alert('Could not load NetworkLink. Link tag with href not found'); } return; } toggleVisibility(node, true); if(kmlObject.getType() == 'KmlTour'){ ge.getTourPlayer().setTour(kmlObject); }else{ var aspectRatio = null; var m = $(opts.mapElement); if(m.length){ var aspectRatio = m.width() / m.height(); } opts.gex.util.flyToObject(kmlObject, { boundsFallback: parent.find('li').length < 1000, aspectRatio: aspectRatio }); } $(that).trigger('dblclick', [node, kmlObject]); }); var doubleClicking = false; google.earth.addEventListener(ge.getGlobe(),'dblclick',function(e, d){ if(e.getButton() === -1){ // related to scrolling, ignore return; } var target = e.getTarget(); if(target.getType() === 'GEGlobe'){ // do nothing }else if(target.getType() === 'KmlPlacemark'){ var id = target.getId(); var nodes = getNodesById(id); if(nodes.length >= 1){ // e.preventDefault(); if(!doubleClicking){ doubleClicking = true; setTimeout(function(){ doubleClicking = false; var n = $(nodes[0]); $(that).trigger('dblclick', [n, target]); }, 200); } }else{ // do nothin } } }); // fix for jquery 1.4.2 compatibility. See http://forum.jquery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jquery-1-4-2 that.removeEventListener = that.detachEvent = function(){}; var privilegedApi = { opts: opts, docs: docs }; kmltreeManager.register(that, privilegedApi); that.docs = docs; return that; }; })();
JavaScript
// src/kmldom.js // returns a jquery object that wraps the kml dom kmldom = (function(){ return function(kml){ if( window.ActiveXObject && window.GetObject ) { var dom = new ActiveXObject( 'Microsoft.XMLDOM' ); dom.loadXML(kml); return jQuery(dom); } if( window.DOMParser ) { return jQuery(new DOMParser().parseFromString( kml, 'text/xml' )); } throw new Error( 'No XML parser available' ); } })();
JavaScript
/* * Copyright © 2007 Dominic Mitchell * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the Dominic Mitchell nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* * An URI datatype. Based upon examples in RFC3986. * * TODO %-escaping * TODO split apart authority * TODO split apart query_string (on demand, anyway) * TODO handle parameters containing empty strings properly * TODO keyword escaping * * @(#) $Id$ */ // Globals we introduce. var URI; var URIQuery; // Introduce a new scope to define some private helper functions. (function () { //// HELPER FUNCTIONS ///// // RFC3986 §5.2.3 (Merge Paths) function merge(base, rel_path) { var dirname = /^(.*)\//; if (base.authority && !base.path) { return "/" + rel_path; } else { return base.getPath().match(dirname)[0] + rel_path; } } // Match two path segments, where the second is ".." and the first must // not be "..". var DoubleDot = /\/((?!\.\.\/)[^\/]*)\/\.\.\//; function remove_dot_segments(path) { if (!path) { return ""; } // Remove any single dots var newpath = path.replace(/\/\.\//g, '/'); // Remove any trailing single dots. newpath = newpath.replace(/\/\.$/, '/'); // Remove any double dots and the path previous. NB: We can't use // the "g", modifier because we are changing the string that we're // matching over. while (newpath.match(DoubleDot)) { newpath = newpath.replace(DoubleDot, '/'); } // Remove any trailing double dots. newpath = newpath.replace(/\/([^\/]*)\/\.\.$/, '/'); // If there are any remaining double dot bits, then they're wrong // and must be nuked. Again, we can't use the g modifier. while (newpath.match(/\/\.\.\//)) { newpath = newpath.replace(/\/\.\.\//, '/'); } return newpath; } // give me an ordered list of keys of this object function hashkeys(obj) { var list = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { list.push(key); } } return list.sort(); } // TODO: Make these do something function uriEscape(source) { return source; } function uriUnescape(source) { return source; } //// URI CLASS ///// // Constructor for the URI object. Parse a string into its components. // note that this 'exports' 'URI' to the 'global namespace' URI = function (str) { if (!str) { str = ""; } // Based on the regex in RFC2396 Appendix B. var parser = /^(?:([^:\/?\#]+):)?(?:\/\/([^\/?\#]*))?([^?\#]*)(?:\?([^\#]*))?(?:\#(.*))?/; var result = str.match(parser); // Keep the results in private variables. var scheme = result[1] || null; var authority = result[2] || null; var path = result[3] || null; var query = result[4] || null; var fragment = result[5] || null; // Set up accessors. this.getScheme = function () { return scheme; }; this.setScheme = function (newScheme) { scheme = newScheme; }; this.getAuthority = function () { return authority; }; this.setAuthority = function (newAuthority) { authority = newAuthority; }; this.getPath = function () { return path; }; this.setPath = function (newPath) { path = newPath; }; this.getQuery = function () { return query; }; this.setQuery = function (newQuery) { query = newQuery; }; this.getFragment = function () { return fragment; }; this.setFragment = function (newFragment) { fragment = newFragment; }; }; // Restore the URI to it's stringy glory. URI.prototype.toString = function () { var str = ""; if (this.getScheme()) { str += this.getScheme() + ":"; } if (this.getAuthority()) { str += "//" + this.getAuthority(); } if (this.getPath()) { str += this.getPath(); } if (this.getQuery()) { str += "?" + this.getQuery(); } if (this.getFragment()) { str += "#" + this.getFragment(); } return str; }; // RFC3986 §5.2.2. Transform References; URI.prototype.resolve = function (base) { var target = new URI(); if (this.getScheme()) { target.setScheme(this.getScheme()); target.setAuthority(this.getAuthority()); target.setPath(remove_dot_segments(this.getPath())); target.setQuery(this.getQuery()); } else { if (this.getAuthority()) { target.setAuthority(this.getAuthority()); target.setPath(remove_dot_segments(this.getPath())); target.setQuery(this.getQuery()); } else { // XXX Original spec says "if defined and empty"…; if (!this.getPath()) { target.setPath(base.getPath()); if (this.getQuery()) { target.setQuery(this.getQuery()); } else { target.setQuery(base.getQuery()); } } else { if (this.getPath().charAt(0) === '/') { target.setPath(remove_dot_segments(this.getPath())); } else { target.setPath(merge(base, this.getPath())); target.setPath(remove_dot_segments(target.getPath())); } target.setQuery(this.getQuery()); } target.setAuthority(base.getAuthority()); } target.setScheme(base.getScheme()); } target.setFragment(this.getFragment()); return target; }; URI.prototype.parseQuery = function () { return URIQuery.fromString(this.getQuery(), this.querySeparator); }; //// URIQuery CLASS ///// URIQuery = function () { this.params = {}; this.separator = "&"; }; URIQuery.fromString = function (sourceString, separator) { var result = new URIQuery(); if (separator) { result.separator = separator; } result.addStringParams(sourceString); return result; }; // From http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 // (application/x-www-form-urlencoded). // // NB: The user can get this.params and modify it directly. URIQuery.prototype.addStringParams = function (sourceString) { var kvp = sourceString.split(this.separator); var list, key, value; for (var i = 0; i < kvp.length; i++) { // var [key,value] = kvp.split("=", 2) only works on >= JS 1.7 list = kvp[i].split("=", 2); key = uriUnescape(list[0].replace(/\+/g, " ")); value = uriUnescape(list[1].replace(/\+/g, " ")); if (!this.params.hasOwnProperty(key)) { this.params[key] = []; } this.params[key].push(value); } }; URIQuery.prototype.getParam = function (key) { if (this.params.hasOwnProperty(key)) { return this.params[key][0]; } return null; }; URIQuery.prototype.toString = function () { var kvp = []; var keys = hashkeys(this.params); var ik, ip; for (ik = 0; ik < keys.length; ik++) { for (ip = 0; ip < this.params[keys[ik]].length; ip++) { kvp.push(keys[ik].replace(/ /g, "+") + "=" + this.params[keys[ik]][ip].replace(/ /g, "+")); } } return kvp.join(this.separator); }; })();
JavaScript
/** * * Base64 encode / decode * http://www.webtoolkit.info/ * **/ var Base64 = { // private property _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", // public method for encoding encode : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } return output; }, // public method for decoding decode : function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this._keyStr.indexOf(input.charAt(i++)); enc2 = this._keyStr.indexOf(input.charAt(i++)); enc3 = this._keyStr.indexOf(input.charAt(i++)); enc4 = this._keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = Base64._utf8_decode(output); return output; }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode : function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } };
JavaScript
var enableGoogleLayersControl = (function(){ var setVisibility = function(kmlObject, toggle, ge){ var id = kmlObject.getId(); if(id && id.match(/^LAYER/)){ ge.getLayerRoot().enableLayerById(ge[id], toggle); }else{ var options = ge.getOptions(); switch(id){ case 'SUN': ge.getSun().setVisibility(toggle); break; case 'NAVIGATION_CONTROLS': var vis = ge.VISIBILITY_SHOW if(!toggle){ vis = ge.VISIBILITY_HIDE } ge.getNavigationControl().setVisibility(vis); break; case 'STATUS_BAR': options.setStatusBarVisibility(toggle); break; case 'OVERVIEW_MAP': options.setOverviewMapVisibility(toggle); break; case 'SCALE_LEGEND': options.setScaleLegendVisibility(toggle); break; case 'ATMOSPHERE': options.setAtmosphereVisibility(toggle); break; case 'HISTORICAL_IMAGERY': ge.getTime().setHistoricalImageryEnabled(toggle); break; case 'GRID': options.setGridVisibility(toggle); break; case 'STREET_VIEW': ge.getNavigationControl().setStreetViewEnabled(toggle); } } }; return function(tree, ge){ if(!tree || !ge){ alert('Must call enableGoogleLayersControl with both tree'+ ' and ge options!'); } $(tree).bind('toggleItem', function(e, node, toggle, kmlObject){ setVisibility(kmlObject, toggle, ge); }); $(tree).bind('kmlLoaded', function(e, kmlObject){ var list = kmlObject.getFeatures().getChildNodes(); var length = list.getLength(); for(var i = 0; i < length; i++){ var item = list.item(i); setVisibility(item, item.getVisibility(), ge); } }); } })();
JavaScript
var kmltreeManager = (function(){ that = {}; var trees = []; var ge; var cache = {}; function init(earthInstance){ ge = earthInstance; google.earth.addEventListener(ge, 'balloonopening', balloonOpening); google.earth.addEventListener(ge, 'balloonclose', balloonClose); google.earth.addEventListener(ge.getGlobe(), 'click', function(e, d){ if(e.getButton() === -1){ // related to scrolling, ignore return; } var target = e.getTarget(); if(target.getType() === 'GEGlobe' && $('.kmltree-selected').length){ for(var i=0;i<trees.length;i++){ var treeEl = $(trees[i].api.opts.element); if(treeEl.find('.kmltree-selected').length + treeEl.find('.kmltree-breadcrumb').length > 0){ trees[i].instance.clearSelection(); } } } }); } var register = function(tree, privilegedApi){ if(trees.length === 0){ init(privilegedApi.opts.gex.pluginInstance); } trees.push({ key: 'kmltree-tree-' + trees.length.toString(), instance: tree, api: privilegedApi }); }; that.register = register; var remove = function(tree){ for(var i = 0; i<trees.length; i++){ if(trees[i].instance === tree){ trees.splice(i, 1); break; } } for(var key in cache){ if(cache[key].instance === tree){ delete cache[key]; } } return tree; }; that.remove = remove; var pauseListeners = function(callable){ google.earth.removeEventListener( ge, 'balloonopening', balloonOpening); google.earth.removeEventListener( ge, 'balloonclose', balloonClose); callable(); google.earth.addEventListener( ge, 'balloonopening', balloonOpening); google.earth.addEventListener( ge, 'balloonclose', balloonClose); }; that.pauseListeners = pauseListeners; var getApi = function(tree){ for(var i=0;i<trees.length;i++){ if(trees[i].instance === tree){ return trees[i].api; } } }; var balloonOpening = function(e){ var f = e.getFeature(); var tree = getOwner(f); if(tree){ e.preventDefault(); ge.setBalloon(null); var selectable = false; var id = f.getId(); if(id){ selectable = tree.api.opts.selectable; if(typeof selectable === 'function'){ selectable = selectable(f); } } if(selectable){ tree.instance.selectById(id, f); } openBalloon(f, tree); return false; } // otherwise feature likely loaded outside of a kmltree instance } var balloonClose = function(e){ $('#kmltree-balloon-iframe').remove(); for(var i=0;i<trees.length;i++){ var treeEl = $(trees[i].api.opts.element); if(treeEl.find('.kmltree-selected').length + treeEl.find('.KmlNetworkLink.kmltree-breadcrumb:not(.loaded)').length === 1 && treeEl.find('.kmltree-cursor-2').length === 0){ trees[i].instance.clearSelection(); }else{ // console.log('didnt find stuff', treeEl.find('.kmltree-selected'), treeEl.find('KmlNetworkLink.kmltree-breadcrumb:not(.loaded)'), treeEl.find('.kmltree-selected').length + treeEl.find('KmlNetworkLink.kmltree-breadcrumb:not(.loaded)').length); } } }; var _clearEverythingButMe = function(tree){ for(var i=0;i<trees.length;i++){ if(trees[i].instance !== tree){ if($(trees[i].api.opts.element).find('.kmltree-selected').length || $(trees[i].api.opts.element).find('.kmltree-breadcrumb').length){ trees[i].instance.clearSelection(); } } } }; that._clearEverythingButMe = _clearEverythingButMe; var ownsUrl = function(doc, url){ if(!doc){ // In case the tree failed to load return false; } if(doc.getUrl() === url){ return true; } if(trimUrl(doc.getUrl()) === trimUrl(url)){ return true; } if(doc.getElementByUrl(url)){ return true; } if(doc.getElementByUrl(trimUrl(url))){ return true; } return false; } var trimUrl = function(url){ var newUrl = url.split('#')[0]; // Remove cachebuster. If not done, selection of features within // networklinks from the map will stop working after refresh. // Took a while to notice that bug!! newUrl = newUrl.replace(/cachebuster=\d+/, ''); if(newUrl.indexOf('?') === newUrl.length - 1){ newUrl = newUrl.replace('?', ''); } return newUrl; } var getOwner = function(kmlObject){ var url = kmlObject.getUrl(); var urlWithoutId = trimUrl(url); if(cache[urlWithoutId]){ return cache[urlWithoutId]; } // First check if url matches root element for(var i=0;i<trees.length;i++){ if(ownsUrl(trees[i].instance.kmlObject, url)){ cache[urlWithoutId] = trees[i]; return trees[i]; } } // Then check each tree's expanded NetworkLinks // TODO: Test if this works for(var i=0;i<trees.length;i++){ var tree = trees[i].instance; var api = trees[i].api; var docs = tree.docs; for(var j = 0; j<docs.length;j++){ var doc = docs[j]; if(ownsUrl(doc, url)){ cache[urlWithoutId] = trees[i]; return trees[i]; } } } // Couldn't find. Could be content loaded outside kmltree. // In any case, ignore return false; }; that.getOwner = function(kmlObject){ var t = getOwner(kmlObject); if(t){ return t.instance; }else{ return false; } }; var openBalloon = function(kmlObject, tree){ $(window).unbind("message.kmlTreeIframeEvents"); var balloon; var tree = tree.instance ? tree.instance : tree; var api = tree.api ? tree.api : getApi(tree); // Compare getBalloonHtmlUnsafe to getBalloonHtml to determine whether // there is even any need to use an iframe to display unsafe content var allow = api.opts.displayEnhancedContent; if(typeof allow === 'function'){ allow = allow(kmlObject); } if(allow){ // don't bother checking if not going to display var unsafeHtml = kmlObject.getBalloonHtmlUnsafe(); var safeHtml = kmlObject.getBalloonHtml(); var safeHtml = $.trim( safeHtml.replace( /\s*<!--\s*Content-type: mhtml-die-die-die\s*-->/, '')); var hasUnsafeContent = safeHtml != $.trim(unsafeHtml); } if(allow && hasUnsafeContent){ balloon = ge.createHtmlDivBalloon(''); var iframe = document.createElement('iframe'); iframe.setAttribute('src', api.opts.iframeSandbox); iframe.setAttribute('frameBorder', '0'); iframe.setAttribute('id', 'kmltree-balloon-iframe'); var div = document.createElement('div'); $(div).append(iframe); $(iframe).one('load', function(){ $(window).bind("message.kmlTreeIframeEvents", {'window': iframe.contentWindow}, function(e){ var ev = e.originalEvent; if(ev.source === e.data.window){ resize(ev); } }); var msg = JSON.stringify({ html: Base64.encode(unsafeHtml), callback: Base64.encode( api.opts.sandboxedBalloonCallback.toString()) }); // Posting to any domain since iframe popups may have their // window.location changed by javascript code in the // description. this.contentWindow.postMessage(msg, '*'); }); balloon.setContentDiv(div); }else{ balloon = ge.createFeatureBalloon(''); // callback for normal popups. Enhanced popup balloonopen event is // triggered by resize function var boCallback = function(e){ // This has to be done within a setTimeout call. Otherwise you // can't open another balloon using an event listener and // count on that event to fire. I think this is so you can // have callbacks like balloonOpening that don't go into an // infinite loop google.earth.removeEventListener( ge, 'balloonopening', boCallback); setTimeout(function(){ $(tree).trigger('balloonopen', [ e.getBalloon(), e.getFeature()]); }, 1); }; google.earth.addEventListener(ge, 'balloonopening', boCallback); } balloon.setFeature(kmlObject); ge.setBalloon(balloon); }; that._openBalloon = openBalloon; function resize(e){ var b = ge.getBalloon(); var f = b.getFeature(); var iframe = $('#kmltree-balloon-iframe'); if( // There should at least be an iframe present !iframe.length || // Message must include a new dimension or specify that none could // be calculated !(e.data.match(/width/) || e.data.match(/unknownIframeDimensions/) ) || // Make sure the current popup is an HtmlDivBalloon b.getType() !== 'GEHtmlDivBalloon'){ // and if all those conditions aren't met... // Oooooo... A zombie Iframe!!! // don't do anything, that balloon has already closed return; } var tree = getOwner(f); var dim = JSON.parse(e.data) if(dim.unknownIframeDimensions){ var dim = tree.api.opts.unknownIframeDimensionsDefault; if(typeof dim === 'function'){ dim = dim(f); } } var el = $('#kmltree-balloon-iframe'); b.setMinWidth(dim.width); b.setMaxWidth(dim.width + (dim.width * .1)); b.setMinHeight(dim.height); b.setMaxHeight(dim.height + (dim.height * .1)); el.height(dim.height); el.width(dim.width); $(tree.instance).trigger('balloonopen', [b, f]); } // Implemented this because call window.frameElement on a cross-origin // iframe results in a security exception. function frameElement(win){ var iframes = document.getElementsByTagName('iframe'); for(var i =0;i<iframes.length;i++){ if(iframes[0].contentWindow === win){ return iframes[i]; } } } return that; })();
JavaScript
// src/tmpl.js // Simple JavaScript Templating // John Resig - http://ejohn.org/ - MIT Licensed (function(){ var cache = {}; this.tmpl = function tmpl(str, data){ // Figure out if we're getting a template, or if we need to // load the template - and be sure to cache the result. var fn = !/\W/.test(str) ? cache[str] = cache[str] || tmpl(document.getElementById(str).innerHTML) : // Generate a reusable function that will serve as a template // generator (and which will be cached). new Function("obj", "var p=[],print=function(){p.push.apply(p,arguments);};" + // Introduce the data as local variables using with(){} "with(obj){p.push('" + // Convert the template into pure JavaScript str .replace(/[\r\t\n]/g, " ") .split("<%").join("\t") .replace(/((^|%>)[^\t]*)'/g, "$1\r") .replace(/\t=(.*?)%>/g, "',$1,'") .split("\t").join("');") .split("%>").join("p.push('") .split("\r").join("\\'") + "');}return p.join('');"); // Provide some basic currying to the user return data ? fn( data ) : fn; }; })();
JavaScript
module('kmlTree'); (function(){ function triggerBalloon(ge, url){ var f = ge.getElementByUrl(url); if(!f){ throw('could not find feature with url ', url); } var balloon = ge.createHtmlStringBalloon(''); balloon.setFeature(f); ge.setBalloon(balloon); } // from http://stackoverflow.com/questions/901115/get-querystring-with-jquery function getParameterByName( name, href ) { href = href || window.location.href; name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( href ); if( results == null ){ return ""; }else{ return results[1]; } } // given the name of a file within examples/kml, creates an absolute url // to it, appending ?r=revision if necessary function example(filename){ var url = '../examples/kml/' + filename; // var url = 'http://kmltree.googlecode.com/hg/examples/kml/' + filename; var r = getParameterByName('r'); if(r !== ''){ url = url + '?r=' + r; } return url; } earthTest('create instance', 2, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var errors = false; try{ var tree = kmltree({ gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); }catch(e){ errors = true; } ok(errors); var tree = kmltree({ url: example('hello.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); ok(tree !== false, 'Tree initialized'); tree.destroy(); $('.kmltreetest').remove(); }); earthAsyncTest('load kml, fire kmlLoaded event. <a href="../examples/kmlLoaded.html">example</a>', 4, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('hello.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: true }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); ok(this === tree, '"this" refers to the instance of kmltree'); equals(kmlObject.getType(), 'KmlDocument', 'kmlObject refers to the loaded KmlDocument'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(); }); earthAsyncTest('click events <a href="../examples/clickEvents.html">example</a>', 5, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('clickEvents.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(Click Me)') .click(); }); $(tree).bind('click', function(e, node, kmlObject){ equals(kmlObject.getName(), 'Click Me'); equals(e.target, tree); equals(this, tree, '"this" refers to the instance of kmltree'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('events arent confused across multiple instances', 9, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); $(document.body).append('<div class="kmltreetest2"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); var tree2 = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest2'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ tree2.load(true); ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); equals(e.target, tree); $('.kmltreetest').find('span.name:contains(Placemark without description)') .click(); }); $(tree).bind('click', function(e, node, kmlObject){ equals(kmlObject.getName(), 'Placemark without description'); equals(e.target, tree); }); $(tree2).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); equals(e.target, tree2); $('.kmltreetest2').find('span.name:contains(Placemark without description)') .click(); }); $(tree2).bind('click', function(e, node, kmlObject){ equals(kmlObject.getName(), 'Placemark without description'); equals(e.target, tree2); tree.destroy(); tree2.destroy(); $('.kmltreetest').remove(); $('.kmltreetest2').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('dblclick events', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(Placemark without description)') .dblclick(); }); $(tree).bind('dblclick', function(e, node, kmlObject){ equals(kmlObject.getName(), 'Placemark without description'); equals(e.target, tree); equals(this, tree, '"this" refers to the instance of kmltree'); $('.kmltreetest').remove(); tree.destroy(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('setExtent option', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, setExtent: true }); $(tree).bind('kmlLoaded', function(e, kmlObject){ setTimeout(function(){ var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); ok(secondLat !== firstLat); $('.kmltreetest').remove(); tree.destroy(); start(); }, 500); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('context menu support', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); var e = jQuery.Event('click'); e.metaKey = true; $(tree).one('select', function(e, data){ equals(data.length, 2, 'Two kmlObjects selected'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); $(tree).one('context', function(e, data){ equals(data.length, 2, 'Two kmlObjects selected'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); $(tree).one('context', function(e, data){ equals(data.length, 1, 'One kmlObject selected'); ok(inSelectData(data, "Admiral's Reef"), "Admiral's Reef in selected features"); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('li.ADMRLS').trigger('contextmenu'); }); $('li.GullIsland > span.name').trigger('contextmenu'); }); $('li.GullIsland > span.name').trigger(e); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); // className option earthAsyncTest('classname option', 4, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('hello.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, classname: function(kmlObject){ var type = kmlObject.getType(); if(type === 'KmlPlacemark'){ return 'myPlacemarkClass' }else if(type === 'KmlDocument'){ return 'myDocClass'; }else{ return 'myClass'; } } }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); equals($('li.myPlacemarkClass.KmlPlacemark').length, 1, 'Placemark has custom class'); equals($('li.myDocClass.KmlDocument').length, 1, 'Doc has custom class'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('getNodesById', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(Placemark with ID)').parent(); equals(node.length, 1); var nodes = tree.getNodesById('myId'); equals(nodes.length, 1); equals(nodes[0], node[0]); equals(tree.getNodesById('non-existent').length, 0); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // earthAsyncTest('optional title support', function(ge, gex){ // $(document.body).append('<div class="kmltreetest"></div>'); // var tree = kmltree({ // url: example('kmlForestTest.kml'), // gex: gex, // mapElement: $('#map3d'), // element: $('.kmltreetest'), // title: true, // bustCache: false // }); // $(tree).bind('kmlLoaded', function(e, kmlObject){ // ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); // var title = $('.kmltreetest').find('h4:contains(kmlForestTest.kml)'); // equals(title.length, 1); // ok(title.hasClass('marinemap-kmltree-title')) // tree.destroy(); // $('.kmltreetest').remove(); // start(); // }); // ok(tree !== false, 'Tree initialized'); // tree.load(true); // }); earthAsyncTest('supports kml <a href="http://code.google.com/apis/kml/documentation/kmlreference.html#open">open tag</a>', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var closed = $('.kmltreetest').find('span.name:contains(closed folder)'); equals(closed.length, 1); ok(!closed.parent().hasClass('open')); var open = $('.kmltreetest').find('span.name:contains(Radio Folder)'); equals(open.length, 1); ok(open.parent().hasClass('open')); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('supports <a href="http://code.google.com/apis/kml/documentation/kmlreference.html#visibility">visibility tag</a>', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var nodes = tree.getNodesById('myId'); var kmlObject = tree.lookup(nodes); equals(kmlObject.getName(), 'Placemark with ID'); ok(nodes.hasClass('visible')); equals(kmlObject.getVisibility(), 1); var node = $('.kmltreetest').find('span.name:contains(Visibility set to false)').parent(); equals(node.length, 1); ok(!node.hasClass('visible')); var kmlObject = tree.lookup(node); equals(kmlObject.getName(), 'Visibility set to false'); equals(kmlObject.getVisibility(), 0); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('supports <a href="http://code.google.com/apis/kml/documentation/kmlreference.html#snippet">snippet tag</a>', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(PhotoOverlay of South Coast Study Region)').parent(); equals(node.length, 1); equals(node.find('> .snippet').length, 1); var node = $('.kmltreetest').find('span.name:contains(Visibility set to false)').parent(); equals(node.length, 1); equals(node.find('> .snippet').length, 0); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('features with descriptions appear as a link', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(Placemark without description)').parent(); ok(!node.hasClass('hasDescription')); var node = $('.kmltreetest').find('span.name:contains(Placemark with description)').parent(); ok(node.hasClass('hasDescription')); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("open folder contents visible, closed folders' content not", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(closed folder)').parent(); equals(node.find('> ul:visible').length, 0); var node = $('.kmltreetest').find('span.name:contains(Radio Folder)').parent(); equals(node.find('> ul:visible').length, 1); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('folders expand/collapse', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(closed folder)').parent(); equals(node.length, 1); node.find('> .expander').click(); equals(node.find('>ul:visible').length, 1); node.find('> .expander').click(); equals(node.find('>ul:visible').length, 0); $('.kmltreetest').remove(); tree.destroy(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('can toggle features', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(PhotoOverlay of South Coast Study Region)').parent(); var kmlObject = tree.lookup(node); equals(node.length, 1); ok(!kmlObject.getVisibility()); node.find('> .toggler').click(); ok(kmlObject.getVisibility()); ok(kmlObject.getVisibility()); node.find('> .toggler').click(); ok(!kmlObject.getVisibility()); $('.kmltreetest').remove(); tree.destroy(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('toggling folders toggles children', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(Both visible)').parent(); var kmlObject = tree.lookup(node); equals(node.length, 1); // All items on to start ok(node.find('> ul > li.visible').length > 0); ok(kmlObject.getVisibility()); // turn them off node.find('> .toggler').click(); equals(node.find('> ul > li.visible').length, 0); ok(!kmlObject.getVisibility()); var child = node.find('> ul > li')[0]; var childKml = tree.lookup(child); ok(childKml); ok(!childKml.getVisibility()); // turn back on node.find('> .toggler').click(); ok(kmlObject.getVisibility()); ok(childKml.getVisibility()); $('.kmltreetest').remove(); tree.destroy(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('toggling child toggles all parents', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(level 4)').parent(); equals(node.length, 1); // All items off to start ok(!node.hasClass('visible')); // turn on node.find('> .toggler').click(); var kmlObject = tree.lookup(node); ok(kmlObject); ok(kmlObject.getVisibility()); var level1 = $('.kmltreetest').find('span.name:contains(level 1)').parent(); ok(level1.hasClass('visible')); ok(tree.lookup(level1).getVisibility()); var level2sib = $('.kmltreetest').find('span.name:contains(level 2 sibling)').parent(); ok(!level2sib.hasClass('visible')); ok(!tree.lookup(level2sib).getVisibility()); $('.kmltreetest').remove(); tree.destroy(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('toggling all children off toggles parents off', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); $('.kmltreetest').remove(); start(); }); // // Tests for when a semi-toggled state for folders is implemented // // earthAsyncTest('toggling child with no siblings toggles folder', function(ge, gex){ // $(document.body).append('<div class="kmltreetest"></div>'); // $('.kmltreetest').remove(); // start(); // }); // // earthAsyncTest('toggling one of many children semi-toggles folder', function(ge, gex){ // $(document.body).append('<div class="kmltreetest"></div>'); // $('.kmltreetest').remove(); // start(); // }); // // earthAsyncTest('semi-toggling travels up deeply nested trees', function(ge, gex){ // $(document.body).append('<div class="kmltreetest"></div>'); // $('.kmltreetest').remove(); // start(); // }); earthAsyncTest('list items given class names matching kmlObject.getType()', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); ok($('.kmltreetest').find('li.KmlPlacemark').length > 0); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('radioFolder support', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(One at a time)').parent(); var a = node.find('span.name:contains(Radio A)').parent(); var b = node.find('span.name:contains(Radio B)').parent(); ok(node.length === 1); ok(a.length === 1); ok(b.length === 1); ok(node.hasClass('radioFolder')); var kmlObject = tree.lookup(node); // start out not visible ok(!kmlObject.getVisibility()); node.find('> .toggler').click(); ok(kmlObject.getVisibility()); ok(tree.lookup(a).getVisibility()); ok(a.hasClass('visible')); ok(!tree.lookup(b).getVisibility()); ok(!b.hasClass('visible')); b.find('> .toggler').click(); ok(!tree.lookup(a).getVisibility()); ok(tree.lookup(b).getVisibility()); b.find('> .toggler').click(); ok(!tree.lookup(a).getVisibility()); ok(!tree.lookup(b).getVisibility()) tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("toggling parent of radio folder doesn't toggle all radioFolder children.", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(One at a time)').parent(); var a = node.find('span.name:contains(Radio A)').parent(); var b = node.find('span.name:contains(Radio B)').parent(); ok(node.length === 1); ok(a.length === 1); ok(b.length === 1); ok(node.hasClass('radioFolder')); var parent = node.parent().parent(); parent.find('> .toggler').click(); parent.find('> .toggler').click(); parent.find('> .toggler').click(); ok(!tree.lookup(parent).getVisibility(), 'Startout with parent and children cleared'); ok(!tree.lookup(a).getVisibility(), 'Startout with parent and children cleared'); ok(!tree.lookup(b).getVisibility(), 'Startout with parent and children cleared'); parent.find('> .toggler').click(); ok(tree.lookup(a).getVisibility(), 'Should turn on the first child.'); ok(!tree.lookup(b).getVisibility(), 'Only one child of a radioFolder should be turned on at a time.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('<a href="http://code.google.com/apis/kml/documentation/kmlreference.html#liststyle">ListStyle</a> support: checkOffOnly', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var parent = $('.kmltreetest').find('span.name:contains(check off only)').parent(); var a = parent.find('span.name:contains(a)').parent(); var b = parent.find('span.name:contains(b)').parent(); ok(tree.lookup(parent).getVisibility()); ok(tree.lookup(a).getVisibility()); ok(tree.lookup(b).getVisibility()); parent.find('> .toggler').click(); ok(!tree.lookup(parent).getVisibility(), 'Parent visibility off after click.'); ok(!tree.lookup(a).getVisibility(), 'Both children should be turned off by click on parent.'); ok(!tree.lookup(b).getVisibility(), 'Both children should be turned off by click on parent.'); parent.find('> .toggler').click(); ok(!tree.lookup(parent).getVisibility() && !tree.lookup(a).getVisibility() && !tree.lookup(b).getVisibility(), 'Should not be able to toggle visibility with listItemType = checkOffOnly.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('<a href="http://code.google.com/apis/kml/documentation/kmlreference.html#liststyle">ListStyle</a> support: checkHideChildren', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var folder = $('.kmltreetest').find('span.name:contains(folder with contents hidden)').parent(); ok(folder.find('> .toggler:visible').length === 0, 'Toggle icon should not be visible'); ok(folder.find('> ul > li').length === 0, 'Shouldnt add children'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('ItemIcon if option specified', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('earthLayers.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, supportItemIcon: true }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var grid = $('.kmltreetest').find('span.name:contains(Grid)').parent(); var icon = grid.find('>.icon').css('background-image'); ok(icon.indexOf('http://marinemap.googlecode.com/svn/trunk/media/common/images/silk/sport_golf.png') !== -1); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('click on elements with descriptions opens balloon.', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); ok(!ge.getBalloon(), 'start out with no balloon open.'); var node = $('.kmltreetest').find('span.name:contains(Placemark with description)').parent(); $('.kmltreetest').find('span.name:contains(Placemark with description)').click(); ok(ge.getBalloon(), 'Balloon should now be open.'); ok(tree.lookup(node).getVisibility(), 'Should be visible if viewing balloon.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('Untoggling feature with balloon closes it.', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); ge.setBalloon(null); ok(!ge.getBalloon(), 'start out with no balloon open.'); var node = $('.kmltreetest').find('span.name:contains(Placemark with description)').parent(); $('.kmltreetest').find('span.name:contains(Placemark with description)').click(); ok(ge.getBalloon(), 'Balloon should now be open.'); ok(tree.lookup(node).getVisibility(), 'Should be visible if viewing balloon.'); node.find('> .toggler').click(); ok(!tree.lookup(node).getVisibility(), 'Feature should be invisible'); ok(!ge.getBalloon(), 'Balloon should be closed.'); ge.setBalloon(null); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('double click feature flys to feature', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(Visibility set to false)').parent(); node.find('span.name').dblclick(); ok(tree.lookup(node).getVisibility(), 'Feature should be visible.'); setTimeout(function(){ var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); ok(secondLat !== firstLat); tree.destroy(); $('.kmltreetest').remove(); start(); }, 400); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('double click works on icons too', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(Placemark without description)').parent().find('.icon').dblclick(); setTimeout(function(){ var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); ok(secondLat !== firstLat); tree.destroy(); $('.kmltreetest').remove(); start(); }, 400); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // Not a very good test. If the double click event was instead causing the // viewport to zoom to the camera like any other feature, the bug likely // wouldn't be detected. Should really be a ge.getTourPlayer().getTour() api. // A feature request has been submitted for that function // http://code.google.com/p/earth-api-samples/issues/detail?id=309 earthAsyncTest('tours are activated when double-clicked.', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var node = $('.kmltreetest').find('span.name:contains(Tour Example)').parent(); ok(node.length, "Tour exists"); var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); node.dblclick(); ge.getTourPlayer().play(); var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); ok(firstLat != secondLat, "Assuming the latitude changes after double-clicking the tour, it must be active."); ge.getTourPlayer().pause(); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('refresh reloads kml tree', 3, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); tree.refresh(); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); tree.destroy(); $('.kmltreetest').remove(); start(); }); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('selectNode', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("selection kmltree-breadcrumbs - one networklink deep", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'San Miguel Island', 'Correct feature selected'); ok(node.hasClass('KmlNetworkLink'), 'Node returned to event callback is actually the parent networklink'); ok(node.hasClass('kmltree-breadcrumb'), 'NetworkLink has kmltree-breadcrumb class'); $(tree).one('networklinkload', function(e){ ok(!node.hasClass('kmltree-breadcrumb'), 'NetworkLink should no longer have kmltree-breadcrumb class'); ok(node.find('.kmltree-selected:contains("San Miguel")').length === 1, 'Child feature is selected'); // roll back up var nla = $('.KmlNetworkLink > :contains("networklink a")').parent(); nla.find('.expander').click(); ok(nla.hasClass('kmltree-breadcrumb'), 'collapsing networklink back up add kmltree-breadcrumb.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); node.find('.expander').click() }); setTimeout(function(){ // wait for networklink to load up triggerBalloon(ge, 'http://underbluewaters-try-better-selection-api.googlecode.com/hg/examples/kml/selection_2.kml#SMI'); }, 1000); }); tree.load(true); }); earthAsyncTest("selection kmltree-breadcrumbs - two networklinks deep with folder in-between", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Jalama', 'Correct feature selected'); ok(node.hasClass('KmlNetworkLink'), 'Node returned to event callback is actually the parent networklink'); ok(node.hasClass('kmltree-breadcrumb'), 'NetworkLink has kmltree-breadcrumb class'); $(tree).one('networklinkload', function(e){ ok(!node.hasClass('kmltree-breadcrumb'), 'NetworkLink should no longer have kmltree-breadcrumb class'); var folder = node.find('.KmlFolder.kmltree-breadcrumb'); ok(folder, 'Folder has kmltree-breadcrumb class'); folder.find('> .expander').click(); ok(!folder.hasClass('kmltree-breadcrumb'), 'After expanding, folder kmltree-breadcrumb is removed'); var nlb = folder.find('.KmlNetworkLink.kmltree-breadcrumb'); ok(nlb, 'networklink b kmltree-breadcrumb-ed'); $(tree).one('networklinkload', function(e){ ok(!nlb.hasClass('kmltree-breadcrumb'), 'kmltree-breadcrumb class removed from expanded networklink'); ok(node.find('.kmltree-selected').length, 'Selected item found under networklink'); // rollup node.find('> .expander').click(); ok(node.hasClass('kmltree-breadcrumb'), 'collapsed networklink indicates location of nested selection.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); nlb.find('> .expander').click(); }); node.find('> .expander').click() }); setTimeout(function(){ // wait for networklink to load up triggerBalloon(ge, 'http://underbluewaters-try-better-selection-api.googlecode.com/hg/examples/kml/selection_3.kml#JAL'); }, 2000); }); tree.load(true); }); earthAsyncTest('selectable - static selectable option', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); tree.destroy(); $('.kmltreetest').remove(); start(); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); earthAsyncTest('selectable - callable selectable option', function(ge, gex){ var gulltested = 0; $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ if(kmlObject.getName() === 'Forney'){ return true; }else{ if(kmlObject.getId() === 'GullIsland'){ gulltested++; } return false; } } }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); ge.setBalloon(null); triggerBalloon(ge, tree.kmlObject.getUrl() + '#GullIsland'); equals(gulltested, 2, 'Gull Island clicked on but not selected'); tree.destroy(); $('.kmltreetest').remove(); start(); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); // multiple-select should be turned off by default earthAsyncTest('selectable - multipleSelect off by default', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multiple: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); var e = jQuery.Event('click'); e.metaKey = true; $(tree).one('select', function(e, data){ equals(data.length, 1, 'Only one kmlObject selected'); equals(data[0].kmlObject.getName(), 'Gull Island', 'Correct selected feature'); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('li.GullIsland > span.name').trigger(e); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); function inSelectData(data, name){ for(var i =0;i<data.length;i++){ var kmlObject = data[i].kmlObject; if(kmlObject.getName() === name){ return true; } } return false; }; // command-select support earthAsyncTest('selectable - multipleSelect command/ctrl+select support', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); var e = jQuery.Event('click'); e.metaKey = true; $(tree).one('select', function(e, data){ equals(data.length, 2, 'Two kmlObjects selected'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); $(tree).one('select', function(e, data){ equals(data.length, 1, 'Command+Clicking again deselects'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); var e = jQuery.Event('click'); e.metaKey = true; $(tree).one('select', function(e, data){ equals(data.length, 2, 'Two kmlObjects selected'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); $(tree).one('select', function(e, data){ equals(data.length, 1, 'Clicking without meta-key clears multiple select'); setTimeout(function(){ equals($('.selected').length, 0, 'Trying to select unselectable does nothing.'); tree.destroy(); $('.kmltreetest').remove(); start(); }, 500); var e = jQuery.Event('click'); e.metaKey = true; $('#FLD1').trigger(e); }); $('li.GullIsland > span.name').click(); }); var e = jQuery.Event('click'); e.metaKey = true; $('li.GullIsland > span.name').trigger(e); }); var e = jQuery.Event('click'); e.metaKey = true; $('li.GullIsland > span.name').trigger(e); }); $('li.GullIsland > span.name').trigger(e); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); // shift+select support earthAsyncTest('selectable - multipleSelect shift+click', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Forney', 'Correct feature selected'); $(tree).one('select', function(e, data){ equals(data.length, 3, 'Selected all 3 placemarks'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); ok(inSelectData(data, "Admiral's Reef"), "Admiral's Reef in selected features"); $(tree).one('select', function(e, data){ equals(data.length, 1, 'Switch cursor to gull'); $(tree).one('select', function(e, data){ equals(data.length, 2, 'Selected Admirals and Gull'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, "Admiral's Reef"), "Admiral's Reef in selected features"); $(tree).one('select', function(e, data){ equals(data.length, 2, 'Selected Forney and Gull'); ok(inSelectData(data, 'Gull Island'), 'Gull Island in selected features'); ok(inSelectData(data, "Forney"), "Admiral's Reef in selected features"); tree.destroy(); $('.kmltreetest').remove(); start(); }); var e = jQuery.Event('click'); e.shiftKey = true; $('li.Forney > span.name').trigger(e); }); var e = jQuery.Event('click'); e.shiftKey = true; $('li.ADMRLS > span.name').trigger(e); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#GullIsland'); }); var e = jQuery.Event('click'); e.shiftKey = true; $('li.ADMRLS > span.name').trigger(e); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree.load(true); }); // multipleSelect - two kmltrees // normal selections from map and tree // shift select on both trees earthAsyncTest('selectable - multiple trees', function(ge, gex){ var gulltested = 0; $(document.body).append('<div class="kmltreetest"></div>'); $(document.body).append('<div class="kmltreetest2"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); var tree2 = kmltree({ url: example('hello.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest2'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); $(tree).one('kmlLoaded', function(){ $(tree2).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ equals(data.length, 1, 'One feature selected from map'); ok(inSelectData(data, 'Forney'), 'Forney in selected features'); $(tree2).one('select', function(e, data){ equals(data.length, 1, 'One feature selected from map on other tree'); ok(inSelectData(data, 'Hello!'), 'Hello! in selected features'); equals($('.kmltree .kmltree-selected').length, 1, 'Only one feature from one tree selected'); tree.destroy(); tree2.destroy(); $('.kmltreetest').remove(); $('.kmltreetest2').remove(); start(); }); $('.kmltreetest2 .hello .name').click(); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Forney'); }); tree2.load(true); }); tree.load(true); }); // TODO: Test cases for all the new apis that aren't yet tested // selections on unexpanded features get kmltree-breadcrumbs indicating what items to expand to reach them in the tree earthAsyncTest("un-expanded feature's parent has kmltree-breadcrumb class, and it is removed when expanded", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('select', function(e, data){ var node = data[0].node; var kmlObject = data[0].kmlObject; ok(true, 'select event fired'); equals(kmlObject.getName(), 'Yellowbanks', 'Correct feature selected'); var folder = $('.kmltree-breadcrumb.KmlFolder > :contains(Yellowbanks)').parent(); ok(folder.hasClass('KmlFolder'), 'Parent KmlFolder has kmltree-breadcrumb class'); folder.find('.expander').click(); ok(!folder.hasClass('kmltree-breadcrumb'), 'kmltree-breadcrumb class removed now that folder is expanded'); ok(node.hasClass('kmltree-selected'), 'primary node should be selected'); tree.destroy(); $('.kmltreetest').remove(); start(); }); triggerBalloon(ge, tree.kmlObject.getUrl() + '#Yellowbanks'); }); tree.load(true); }); earthAsyncTest('Contents of NetworkLinks can be displayed. Depends on <a href="http://code.google.com/p/earth-api-samples/issues/detail?id=260&q=NetworkLink&colspec=ID%20Type%20Summary%20Component%20OpSys%20Browser%20Status%20Stars#c3">this ticket</a>, or a hack', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var nlink = $('.kmltreetest').find('span.name:contains(networklink a)').parent(); var nlinkobject = tree.lookup(nlink); $(tree).bind('networklinkload', function(e, node, kmlObject){ equals(kmlObject.getName(), 'linka.kmz'); equals(kmlObject.getType(), 'KmlDocument', 'kmlObject is a KmlDocument'); equals($('.kmltreetest').find('span.name:contains(NetworkLink Content)').length, 1, 'NetworkLink contents displayed.'); equals(nlinkobject.getVisibility(), kmlObject.getVisibility()); var pmark = $('.kmltreetest').find('li:contains(NetworkLink Content) span.name:contains(Untitled Placemark)'); equals(pmark.length, 1); // toggling-off networklink toggles off linked document nlink.find('.toggler').click(); equals(nlinkobject.getVisibility(), false, 'NetworkLink visibility off'); equals(nlinkobject.getVisibility(), kmlObject.getVisibility(), 'Parent document visibility tracks NetworkLink visibility.'); // Events still work (testing double-click on tree node) pmark.dblclick(); setTimeout(function(){ var secondLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); ok(secondLat !== firstLat, 'Events on tree nodes should still function.'); tree.destroy(); $('.kmltreetest').remove(); start(); }, 400); }); nlink.find('>.expander').click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('getNetworkLink method', function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var nlink = $('.kmltreetest').find('.name:contains(networklink a)').parent(); var doc = tree.lookup(nlink); equals(doc.getType(), 'KmlDocument'); equals(tree.getNetworkLink(nlink).getType(), 'KmlNetworkLink'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("NetworkLinks with listItemType=checkHideChildren don't expand", function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var nlink = $('.kmltreetest').find('span.name:contains(networklink checkHideChildren)').parent(); equals(nlink.find('>.expander:visible').length, 0); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("NetworkLinks with open=1 should automatically be loaded and expanded", function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('openNL.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, restoreState: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'Kmz loaded correctly'); var nlink = $('.kmltreetest').find('span.name:contains(open networklink)').parent(); ok(nlink.hasClass('loaded')); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest("NetworkLinks with open=1 but with a style of checkHideChildren should not be expanded", function(ge, gex){ var firstLat = ge.getView().copyAsCamera(ge.ALTITUDE_ABSOLUTE).getLatitude(); $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('openCheckHideChildrenNL.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, restoreState: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'Kmz loaded correctly'); var nlink = $('.kmltreetest').find('span.name:contains(nl)').parent(); ok(!nlink.hasClass('loaded'), 'Not loaded'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // Depth-first traversal of all nodes in the tree // Will start out with all the children of the root KmlDocument, but // does not include the KmlDocument itself var walk = function(callback, context, node){ var recurse_ = function(node, context){ node.find('>ul>li').each(function(){ var el = $(this); var newcontext = callback(el, context); if(newcontext === false){ // Don't follow into child nodes return true; }else{ recurse_(el, newcontext); } }); }; // if(!node){ // node = opts.element.find('div.kmltree'); // } recurse_(node, context); }; earthAsyncTest("children ignored if callback returns false", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'Document loaded correctly'); var order = ''; walk(function(node){ var name = node.find('>span.name').text(); order += name; if(name === 'B'){ return false; } }, {}, $('.kmltreetest').find('div.kmltree')); equals(order, 'FJBGIH'); var order = ''; walk(function(node){ var name = node.find('>span.name').text(); order += name; if(name === 'D'){ return false; } }, {}, $('.kmltreetest').find('div.kmltree')); equals('FJBADGIH', order); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('refresh tracks previous state', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(E)').parent().find('>.toggler').click(); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var E = $('.kmltreetest').find('span.name:contains(E)').parent(); ok(!E.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(E).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('more complex example', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(H)').parent().find('>.toggler').click(); $('.kmltreetest').find('span.name:contains(G)').parent().find('>.expander').click(); $('.kmltreetest').find('span.name:contains(A)').parent().find('>.toggler').click(); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var A = $('.kmltreetest').find('span.name:contains(A)').parent(); var H = $('.kmltreetest').find('span.name:contains(H)').parent(); var G = $('.kmltreetest').find('span.name:contains(G)').parent(); ok(!A.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(A).getVisibility(), 'Visibility set on kmlObject'); ok(!H.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(H).getVisibility(), 'Visibility set on kmlObject'); ok(!G.hasClass('visible'), 'History remembered in tree widget'); ok(!G.hasClass('open'), 'History remembered in tree widget'); ok(!tree.lookup(G).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('refreshing twice has the same affect', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(H)').parent().find('>.toggler').click(); $('.kmltreetest').find('span.name:contains(G)').parent().find('>.expander').click(); $('.kmltreetest').find('span.name:contains(A)').parent().find('>.toggler').click(); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var A = $('.kmltreetest').find('span.name:contains(A)').parent(); var H = $('.kmltreetest').find('span.name:contains(H)').parent(); var G = $('.kmltreetest').find('span.name:contains(G)').parent(); ok(!A.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(A).getVisibility(), 'Visibility set on kmlObject'); ok(!H.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(H).getVisibility(), 'Visibility set on kmlObject'); ok(!G.hasClass('visible'), 'History remembered in tree widget'); ok(!G.hasClass('open'), 'History remembered in tree widget'); ok(!tree.lookup(G).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('history with networklinks', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('NLHistory.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); L.find('>.expander').click(); $(tree).one('networklinkload', function(){ var X = $('.kmltreetest').find('span.name:contains(X)').parent(); X.find('>.toggler').click(); ok(!X.hasClass('visible')); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var X = $('.kmltreetest').find('span.name:contains(X)').parent(); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); ok(L.hasClass('open'), 'Networklink open state remembered'); ok(!X.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(X).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('more complex history with networklinks', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('NLHistory.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); L.find('>.expander').click(); $(tree).one('networklinkload', function(){ var X = $('.kmltreetest').find('span.name:contains(X)').parent(); var Z = $('.kmltreetest').find('span.name:contains(Z)').parent(); var Y = $('.kmltreetest').find('span.name:contains(Y)').parent(); X.find('>.toggler').click(); Y.find('>.toggler').click(); Z.find('>.toggler').click(); ok(!X.hasClass('visible')); ok(!Y.hasClass('visible')); ok(!Z.hasClass('visible')); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var X = $('.kmltreetest').find('span.name:contains(X)').parent(); var Y = $('.kmltreetest').find('span.name:contains(Y)').parent(); var Z = $('.kmltreetest').find('span.name:contains(Z)').parent(); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); ok(L.hasClass('open'), 'Networklink open state remembered'); ok(!L.hasClass('visible'), 'L should not be visible since children are not'); ok(!X.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(X).getVisibility(), 'Visibility set on kmlObject'); ok(!Y.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(Y).getVisibility(), 'Visibility set on kmlObject'); ok(!Z.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(Z).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('history with nested networklinks', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('NLHistory.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); $(tree).one('networklinkload', function(){ $(tree).one('networklinkload', function(){ var X = $('.kmltreetest').find('span.name:contains(X)').parent(); var Z = $('.kmltreetest').find('span.name:contains(Z)').parent(); var B = $('.kmltreetest').find('span.name:contains(B)').parent(); X.find('>.toggler').click(); B.find('>.toggler').click(); Z.find('>.toggler').click(); ok(!X.hasClass('visible')); ok(!B.hasClass('visible')); ok(!Z.hasClass('visible')); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var X = $('.kmltreetest').find('span.name:contains(X)').parent(); var Y = $('.kmltreetest').find('span.name:contains(Y)').parent(); var B = $('.kmltreetest').find('span.name:contains(B)').parent(); var Z = $('.kmltreetest').find('span.name:contains(Z)').parent(); var L = $('.kmltreetest').find('span.name:contains(L)').parent(); var A = $('.kmltreetest').find('span.name:contains(A)').parent(); ok(L.hasClass('open'), 'Networklink open state remembered'); ok(L.hasClass('visible')); ok(!X.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(X).getVisibility(), 'Visibility set on kmlObject'); ok(Y.hasClass('open'), 'History remembered in tree widget'); ok(!B.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(B).getVisibility(), 'Visibility set on kmlObject'); ok(!Z.hasClass('visible'), 'History remembered in tree widget'); ok(!tree.lookup(Z).getVisibility(), 'Visibility set on kmlObject'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); var Y = $('.kmltreetest').find('span.name:contains(Y)').parent(); Y.find('>.expander').click(); }); L.find('>.expander').click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('refreshing with 2 networklinks at root', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('2NLAtRoot.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(E)').parent().find('>.toggler').click(); var A = $('.kmltreetest').find('span.name:contains(A)').parent(); var B = $('.kmltreetest').find('span.name:contains(B)').parent(); $(tree).one('networklinkload', function(){ $(tree).one('networklinkload', function(){ $(tree).one('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var A = $('.kmltreetest').find('span.name:contains(A)').parent(); ok(A.hasClass('loaded'), 'History remembered in tree widget'); var B = $('.kmltreetest').find('span.name:contains(B)').parent(); ok(B.hasClass('loaded'), 'History remembered in tree widget'); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); B.find('>.expander').click(); }); A.find('>.expander').click(); }); window.tree = tree; ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('refreshing with 2 networklinks at root - one has old-school Url tag', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('nlOldStyle.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, restoreState: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var working = $('.kmltreetest').find('span.name:contains(Working)').parent(); var old = $('.kmltreetest').find('span.name:contains(old)').parent(); ok(working.length); ok(old.length); ok(working.hasClass('open')); ok(old.hasClass('open')); $(tree).one('kmlLoaded', function(e, kmlObject){ var working = $('.kmltreetest').find('span.name:contains(Working)').parent(); var old = $('.kmltreetest').find('span.name:contains(old)').parent(); ok(old.hasClass('open')); ok(working.hasClass('open')); ok(working.hasClass('loaded')); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); window.tree = tree; ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('supports open networklinks even when refreshing with state', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('nlOldStyle.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, restoreState: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); var working = $('.kmltreetest').find('span.name:contains(Working)').parent(); var old = $('.kmltreetest').find('span.name:contains(old)').parent(); ok(working.length); ok(old.length); ok(working.hasClass('open')); ok(old.hasClass('open')); working.find('>.toggler').click().click(); ok(working.find('>ul>li.visible').length > 1) $(tree).one('kmlLoaded', function(e, kmlObject){ var working = $('.kmltreetest').find('span.name:contains(Working)').parent(); var old = $('.kmltreetest').find('span.name:contains(old)').parent(); ok(old.hasClass('open')); ok(working.hasClass('open')); ok(working.hasClass('loaded')); ok(working.find('>ul>li.visible').length > 1) tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); window.tree = tree; ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('state tracking can be turned off', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(E)').parent().find('>.toggler').click(); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var E = $('.kmltreetest').find('span.name:contains(E)').parent(); ok(E.hasClass('visible')); ok(tree.lookup(E).getVisibility()); tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('restore state using localStorage', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(E)').parent().find('>.toggler').click(); var E = $('.kmltreetest').find('span.name:contains(E)').parent(); ok(!E.hasClass('visible')); tree.destroy(); $('.kmltreetest').remove(); $(document.body).append('<div class="kmltreetest"></div>'); var tree2 = kmltree({ url: example('TreeTraversal.kmz'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), restoreStateOnRefresh: false, restoreState: true, bustCache: false }); $(tree2).bind('kmlLoaded', function(e, kmlObject){ ok(true, 'kml refreshed'); var E = $('.kmltreetest').find('span.name:contains(E)').parent(); ok(!E.hasClass('visible')); ok(!tree2.lookup(E).getVisibility()); tree2.destroy(); $('.kmltreetest').remove(); start(); }); tree2.load(true); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('multiple items with the same name supported', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('same-name test.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var show = $('.kmltreetest').find('span.name:contains(show)'); equals(show.length, 1, 'Item after two networklinks of the same name rendered.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('support for opening networklinks with relative paths', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('same-name test.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var firstNL = $($('.kmltreetest').find('span.name:contains(same name)')[0]).parent(); $(tree).one('networklinkload', function(){ tree.destroy(); $('.kmltreetest').remove(); start(); }); firstNL.find('.expander').click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('toggle behavior', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('toggle-behavior.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var parent = $($('.kmltreetest').find('span.name:contains(untoggled)')[0]).parent(); equals(parent.hasClass('visible'), false, 'Parent not visible'); var toggled = parent.find('>ul>li>span.name:contains(toggled):first').parent(); var untoggled = parent.find('>ul>li>span.name:contains(untoggled)').parent(); equals(toggled.length, 1); equals(untoggled.length, 1); equals(toggled.hasClass('visible'), true, 'toggled visible'); equals(untoggled.hasClass('visible'), false, 'untoggled not visible'); parent.find('>.toggler').click(); equals(toggled.hasClass('visible'), true, 'toggled visible'); equals(untoggled.hasClass('visible'), false, 'untoggled not visible'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayDocumentRoot option - false', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('pmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false, displayDocumentRoot: false }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var doc = $($('.kmltreetest').find('span.name:contains(pmark.kml)')[0]).parent(); equals(doc.length, 0, 'Document root not shown'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayDocumentRoot option - auto - on', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('pmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false, displayDocumentRoot: 'auto' }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var doc = $($('.kmltreetest').find('span.name:contains(pmark.kml)')[0]).parent(); equals(doc.length, 1, 'Document root not shown'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayDocumentRoot option - auto - off', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('clickEvents.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false, displayDocumentRoot: 'auto' }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var doc = $($('.kmltreetest').find('span.name:contains(clickEvents.kml)')[0]).parent(); equals(doc.length, 0, 'Document root not shown'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayDocumentRoot option - true', function(ge, gex){ if(!!window.localStorage){ window.localStorage.clear(); } $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('clickEvents.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false, displayDocumentRoot: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); var doc = $($('.kmltreetest').find('span.name:contains(clickEvents.kml)')[0]).parent(); equals(doc.length, 1, 'Document root not shown'); tree.destroy(); $('.kmltreetest').remove(); start(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('balloonopen event', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('clickEvents.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), refreshWithState: false, restoreState: true, bustCache: false, displayDocumentRoot: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $(tree).one('balloonopen', function(e, b, kmlObject){ equals(b.getType(), 'GEFeatureBalloon'); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(Click Me)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // first test that kmltree can differenciate between popup types earthAsyncTest('displayEnhancedContent option - uses different methods for unsafe vs safe content', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals(balloon.getType(), 'GEFeatureBalloon'); equals($('#kmltree-balloon-iframe').length, 0, 'Basic popup not loaded into iframe.'); $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals(balloon.getType(), 'GEHtmlDivBalloon'); equals($('#kmltree-balloon-iframe').length, 1, 'Enhanced popup displayed in iframe sandbox.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); $('.kmltreetest').find('span.name:contains(no dynamic content)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayEnhancedContent option - is optional and turned off by default', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals(balloon.getType(), 'GEFeatureBalloon'); equals($('#kmltree-balloon-iframe').length, 0, 'No extra iframes since enhanced content is not shown.'); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); earthAsyncTest('displayEnhancedContent option - sandboxedBalloonCallback works', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, sandboxedBalloonCallback: function(){ parent.postMessage('hi there', '*'); } }); $(window).bind('message', function(e){ var e = e.originalEvent; if(e.data.match(/width/)){ // just standard message passing for kmltree return; }else{ $(window).unbind('message'); equals(e.data, 'hi there'); tree.destroy(); $('.kmltreetest').remove(); start(); } }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals(balloon.getType(), 'GEHtmlDivBalloon'); equals($('#kmltree-balloon-iframe').length, 1, 'Enhanced popup displayed in iframe sandbox.'); }); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // test that a custom iframeSandbox option can be used earthAsyncTest('displayEnhancedContent option - custom iframeSandbox url', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, iframeSandbox: 'http://underbluewaters-try-unsafe-popups.googlecode.com/hg/src/iframe.html' }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals($('#map3d iframe[src="http://underbluewaters-try-unsafe-popups.googlecode.com/hg/src/iframe.html"]').length, 1); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); tree.load(true); }); // test that the size is correct earthAsyncTest('displayEnhancedContent option - dynamic height', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ ok($('#kmltree-balloon-iframe').height() > 200); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(large)') .click(); }); tree.load(true); }); // test that window.location type balloons get a default size earthAsyncTest('displayEnhancedContent option - content that sets window.location gets default balloon dimensions', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals($('#kmltree-balloon-iframe').height(), 450); equals($('#kmltree-balloon-iframe').width(), 530); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(window.location)') .click(); }); tree.load(true); }); // test that the default size can be changed earthAsyncTest('displayEnhancedContent option - unknownIframeDimensionsDefault setting', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, unknownIframeDimensionsDefault: {height: 45, width:53} }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals($('#kmltree-balloon-iframe').height(), 45); equals($('#kmltree-balloon-iframe').width(), 53); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(window.location)') .click(); }); tree.load(true); }); // unknownIframeDimensionsDefault as callable earthAsyncTest('displayEnhancedContent option - unknownIframeDimensionsDefault can be a callable', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, unknownIframeDimensionsDefault: function(kmlObject){ if(kmlObject.getType() === 'KmlPlacemark'){ return {height: 45, width:53}; }else{ return {height: 450, width:530}; } } }); $(tree).one('kmlLoaded', function(e, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ equals($('#kmltree-balloon-iframe').height(), 45); equals($('#kmltree-balloon-iframe').width(), 53); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(window.location)') .click(); }); tree.load(true); }); // test that remote and inline css is employed earthAsyncTest('displayEnhancedContent option - remote and inline css works as expected.', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, sandboxedBalloonCallback: function(){ setTimeout(function(){ // wait for remote css to load // - it's okay that this is async var message = ''; if($('#clock').css('text-decoration') === 'underline'){ message += 'inline css okay'; }else{ message += 'inline css failed'; } if($('#clock').css('background-color') === 'rgb(255, 0, 0)' || $('#clock').css('background-color') === 'red'){ message += ', remote css okay'; }else{ message += ', remote css failed'; } parent.postMessage(message, '*'); }, 500); } }); $(window).bind('message', function(e){ var e = e.originalEvent; if(e.data.match(/width/)){ // just standard message passing for kmltree return; }else{ $(window).unbind('message'); equals(e.data, 'inline css okay, remote css okay'); tree.destroy(); $('.kmltreetest').remove(); start(); } }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // test that remote and inline javascript is employed, and in the right // order earthAsyncTest('displayEnhancedContent option - remote and inline js works as expected.', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, iframeSandbox: 'http://underbluewaters-try-unsafe-popups.googlecode.com/hg/src/iframe.html', sandboxedBalloonCallback: function(){ var message = ''; if(typeof pv === 'object'){ message += 'remote js okay'; }else{ message += 'remote js failed'; } if(typeof window.copy_of_pv === 'object'){ message += ', inline js okay'; }else{ message += ', inline js failed'; } parent.postMessage(message, '*'); } }); $(window).bind('message', function(e){ var e = e.originalEvent; if(e.data.match(/width/)){ // just standard message passing for kmltree return; }else{ $(window).unbind('message'); equals(e.data, 'remote js okay, inline js okay'); tree.destroy(); $('.kmltreetest').remove(); start(); } }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(pmark)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // test that content can't get access to parent iframe's data - need to deploy? // TODO: change path to files earthAsyncTest("displayEnhancedContent option - sandboxed content shouldn't be able to access parent cookies and session info.", function(ge, gex){ document.cookie = 'somevalue'; $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true, sandboxedBalloonCallback: function(){ if(window.stolenCookies){ var message = 'failed. cookie data stolen.'; }else{ var message = 'okay. cookie data not accessible.'; } parent.postMessage(message, '*'); } }); $(window).bind('message', function(e){ var e = e.originalEvent; if(e.data.match(/width/)){ // just standard message passing for kmltree return; }else{ $(window).unbind('message'); equals(e.data, 'okay. cookie data not accessible.'); tree.destroy(); $('.kmltreetest').remove(); start(); } }); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlDocument', 'KmlDocument loaded correctly'); $('.kmltreetest').find('span.name:contains(cookie)') .click(); }); ok(tree !== false, 'Tree initialized'); tree.load(true); }); // Make sure multiple instances of kmltree don't clobber each other's // popup window handling events earthAsyncTest("displayEnhancedContent option - multiple kmltrees can exist side-by-side.", function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); $(document.body).append('<div class="kmltreetest2"></div>'); var tree1 = kmltree({ url: example('jspmark.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true }); var tree2 = kmltree({ url: example('hi-js.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest2'), displayDocumentRoot: true, displayEnhancedContent: true, unknownIframeDimensionsDefault: {height: 330, width:330}, iframeSandbox: 'http://underbluewaters-try-unsafe-popups.googlecode.com/hg/src/iframe.html' }); var waiting = 2 var loaded = function(){ waiting--; if(waiting === 0){ $(tree1).one('balloonopen', function(e, balloon, kmlObject){ ok($('#kmltree-balloon-iframe').height() < 330); $(tree2).one('balloonopen', function(e, balloon, kmlObject){ ok($('#kmltree-balloon-iframe').height() > 200); tree1.destroy(); tree2.destroy(); $('.kmltreetest').remove(); $('.kmltreetest2').remove(); start(); }); $('.kmltreetest2').find('span.name:contains(Rotorua)') .click(); }); $('.kmltreetest').find('span.name:contains(large)') .click(); } } $(tree1).one('kmlLoaded', loaded); $(tree2).one('kmlLoaded', loaded); tree1.load(true); tree2.load(true); }); // combo example for expanded networklinks earthAsyncTest('displayEnhancedContent option - expanded networklinks can display sandboxed content too', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example('kmlForestTest.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), displayDocumentRoot: true, displayEnhancedContent: true }); $(tree).one('kmlLoaded', function(e, kmlObject){ // this example contains some other networklinks that automatically load, so wait until they are done setTimeout(function(){ $(tree).one('networklinkload', function(e, node, kmlObject){ $(tree).one('balloonopen', function(e, balloon, kmlObject){ ok($('#kmltree-balloon-iframe').length === 1); tree.destroy(); $('.kmltreetest').remove(); start(); }); $('.kmltreetest').find('span.name:contains(enhanced content)').click() }); $('.kmltreetest').find('span.name:contains(networklink off)').parent().find('>.expander').click(); }, 1000); }); tree.load(true); }); earthAsyncTest('kmltreeManager - getOwner', function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); $(document.body).append('<div class="kmltreetest2"></div>'); var tree = kmltree({ url: example('selection.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); var tree2 = kmltree({ url: example('hello.kml'), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest2'), bustCache: false, selectable: function(kmlObject){ return kmlObject.getType() === 'KmlPlacemark'; }, multipleSelect: true }); $(tree).one('kmlLoaded', function(){ $(tree2).one('kmlLoaded', function(e, kmlObject){ setTimeout(function(){ // Wait for networklink to load var hello = tree2.lookup($('.hello')); var jalama = ge.getElementByUrl('http://underbluewaters-try-better-selection-api.googlecode.com/hg/examples/kml/selection_3.kml#JAL'); equals(kmltreeManager.getOwner(jalama), tree, 'Jalama placemark belongs to tree 1. It is within an unexpanded networklink.'); equals(kmltreeManager.getOwner(hello), tree2, 'Hello placemark is within tree2'); tree.destroy(); tree2.destroy(); $('.kmltreetest').remove(); $('.kmltreetest2').remove(); start(); }, 2000); }); tree2.load(true); }); tree.load(true); }); })();
JavaScript
(function(){ google.load("earth", "1"); // earthTest and earthAsyncTest // ============================ // // Use earthTest rather than QUnit::test for testing functionality that // requires an instance of the Google Earth Plugin and/or the // earth-api-utility-library. // // Test functions will be called with two arguments, the plugin instance // and the utility library. Here is an example: // // earthTest('Test grid', 1, function(ge, gex){ // equals(ge.getOptions().getGridVisibility(), true, // 'Grid should be visible.'); // }); // // For asynchronous tests, use earthAsyncTest as a replacement for // QUnit::testAsync: // // earthAsyncTest('Test parse kml', 1, function(ge, gex){ // $.get('/path/to/kml', function(data){ // var doc = ge.parseKml(data); // equals(doc.getName(), 'My Name'); // start(); // }); // }); // // When testing using asynchronous calls and the Earth Plugin it's // important to fill in the `expected` argument. Otherwise it can be // difficult to pin down which test caused an error. // // See the following for more information on using QUnit: // http://docs.jquery.com/QUnit // window.earthTest = function(name, expected, callback, async){ if ( arguments.length === 2 ) { callback = expected; expected = 0; } var new_function = function(){ if(ge && gex){ if(!async){ start(); } callback(ge, gex); }else{ initializePlugin(function(){ if(!async){ start(); } callback(ge, gex); }); } } asyncTest(name, expected, new_function); } window.earthAsyncTest = function(name, expected, callback){ if ( arguments.length === 2 ) { callback = expected; expected = 0; } earthTest(name, expected, callback, true); } var ge; var gex; function initializePlugin(callback){ var map = $(document.body).append('<div id="map3d"></div>'); $('#map3d').css({width:'400px', height: '200px', 'position': 'absolute', 'top': '-200px', 'right': '0px'}); google.earth.createInstance('map3d', function(plugin){ ge = plugin; gex = new GEarthExtensions(ge); callback(); }, googleEarthFailureCallback); } function googleEarthFailureCallback(){ alert('failed to load google earth plugin.'); } module('Custom Earth Test Cases'); var reference_to_first_google_earth_instance; earthAsyncTest('earthAsyncTest works', 2, function(ge, gex){ ok(typeof ge === 'object' || typeof ge === 'function', 'Google Earth Plugin initialized'); reference_to_first_google_earth_instance = ge; setTimeout(function(){ start(); ok(true === true, 'Additional asynchronous events can be run'); }, 1000); }); earthTest('only loads once', 1, function(ge, gex){ ok(ge === reference_to_first_google_earth_instance, 'Google Earth Plugin should initialize only once.'); }); })();
JavaScript
module('enableGoogleLayersControl'); (function(){ // given the name of a file within examples/kml, creates an absolute url // to it, appending ?r=revision if necessary function example(filename){ var url = '../examples/kml/' + filename; // var url = 'http://kmltree.googlecode.com/hg/examples/kml/' + filename; var r = getParameterByName('r'); if(r !== ''){ url = url + '?r=' + r; } return url; } var layers = {}; function Layer(name, initialState, type, layer_name_or_test, async){ this.name = name; this.initialState = initialState; this.layerName = layer_name_or_test; if(type === 'option'){ if(layer_name_or_test){ this.optionName = layer_name_or_test; }else{ this.optionName = name.replace(' ', ''); } } this.type = type; this.test = layer_name_or_test; this.async = async; } Layer.prototype.getEarthState = function(ge, tree, element){ switch(this.type){ case 'layer': return ge.getLayerRoot().getLayerById( ge[this.layerName]).getVisibility(); break; case 'option': return ge.getOptions()['get'+this.optionName+'Visibility'](); break; default: // special return this.test(ge); } } $.expr[":"].econtains = function(obj, index, meta, stack){ return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase(); } Layer.prototype.testState = function(ge, tree, element, initial){ var node = element.find( 'span.name:econtains('+this.name+')').parent(); equals(node.length, 1, 'Found node representing layer '+this.name); var kmlObject = tree.lookup(node); var earthState = this.getEarthState(ge, tree, element); // Check the status of the layer visibility ok((!!earthState === (this.initialState === initial)), 'GE State - Layer ' + this.name + ' should have ' + (initial ? 'an initial ' : 'a') + ' state = ' + (this.initialState === initial)); // Check the status of the node representing the layer in the loaded // kml file ok((!!kmlObject.getVisibility() === (this.initialState === initial)), 'Tree Node kmlObject - Layer ' + this.name + ' should have ' + (initial ? 'an initial' : 'a') + ' state = ' + (this.initialState === initial)); // Check the toggle state of the ui ok((node.hasClass('visible') === (this.initialState === initial)), 'Toggle state of UI matches DOM. Toggle state should be = ' + (this.initialState === initial)); }; Layer.prototype.testInitialState = function(ge, tree, element){ this.testState(ge, tree, element, true); }; Layer.prototype.testOpposingState = function(ge, tree, element){ this.testState(ge, tree, element, false); }; function Runner(url){ this.url = url; this.layers = []; }; Runner.prototype.test = function(type, name, initial_state, name_or_test, async){ this.layers.push(new Layer(name, initial_state, type, name_or_test, async)); }; Runner.prototype.testOption = function(name, initial_state, name_or_test){ this.test('option', name, initial_state, name_or_test); }; Runner.prototype.testLayer = function(name, initial_state, name_or_test){ this.test('layer', name, initial_state, name_or_test); }; Runner.prototype.testSpecial = function(name, initial_state, name_or_test, async){ this.test('special', name, initial_state, name_or_test, async); }; Runner.prototype.run = function(){ var layers = this.layers; var url = this.url; for(var i = 0; i < this.layers.length; i++) (function(i){ var layer = layers[i]; earthAsyncTest(layer.name, function(ge, gex){ var layer = layers[i]; $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example(url), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: true, supportItemIcon: true }); enableGoogleLayersControl(tree, ge); $(tree).bind('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); layer.testState(ge, tree, $('.kmltreetest'), true); var node = $('.kmltreetest').find('span.name:econtains('+layer.name+')').parent(); node.find('> .toggler').click(); if(layer.async){ setTimeout(function(){ layer.testState(ge, tree, $('.kmltreetest'), false); tree.destroy(); $('.kmltreetest').remove(); start(); }, 1000); }else{ layer.testState(ge, tree, $('.kmltreetest'), false); tree.destroy(); $('.kmltreetest').remove(); start(); } }); ok(tree !== false, 'Tree initialized'); tree.load(); }); })(i); }; Runner.prototype.runRefreshTest = function(){ var that = this; earthAsyncTest('Refresh test on '+this.url, function(ge, gex){ $(document.body).append('<div class="kmltreetest"></div>'); var tree = kmltree({ url: example(that.url), gex: gex, mapElement: $('#map3d'), element: $('.kmltreetest'), bustCache: true, supportItemIcon: true, refreshWithState: true }); enableGoogleLayersControl(tree, ge); $(tree).one('kmlLoaded', function(e, kmlObject){ ok(kmlObject.getType() === 'KmlFolder', 'KmlDocument loaded correctly'); for(var i = 0; i < that.layers.length; i++){ var layer = that.layers[i]; layer.testState(ge, tree, $('.kmltreetest'), true); var node = $('.kmltreetest').find('span.name:econtains('+layer.name+')').parent(); node.find('> .toggler').click(); if(!layer.async){ layer.testState(ge, tree, $('.kmltreetest'), false); } } $(tree).one('kmlLoaded', function(e, kmlObject){ for(var i = 0; i < that.layers.length; i++){ var layer = that.layers[i]; if(!layer.async){ layer.testState(ge, tree, $('.kmltreetest'), false); } } tree.destroy(); $('.kmltreetest').remove(); start(); }); tree.refresh(); }); ok(tree !== false, 'Tree initialized'); tree.load(); }); }; var r = new Runner('displayOptions.kml'); r.testOption('Scale Legend', false); r.testOption('Status Bar', true); r.testOption('Overview Map', false); r.testOption('Atmosphere', true); r.testSpecial('Street View', true, function(ge){ return ge.getNavigationControl().getStreetViewEnabled(); }); r.testLayer('3d Terrain and Ocean Surface', true, 'LAYER_TERRAIN'); r.testSpecial('Sun', false, function(ge){ return ge.getSun().getVisibility(); }); r.testSpecial('Historical Imagery', false, function(ge){ return ge.getTime().getHistoricalImageryEnabled(); }, true); r.testSpecial('Navigation Controls', true, function(ge){ return ge.getNavigationControl().getVisibility() === ge.VISIBILITY_SHOW; }); r.run(); r.runRefreshTest(); var r = new Runner('includedLayers.kml'); r.testLayer('Roads', false, 'LAYER_ROADS'); r.testLayer('3d Trees', false, 'LAYER_TREES'); r.testLayer('Borders and Labels', false, 'LAYER_BORDERS'); r.testLayer('3d Buildings', false, 'LAYER_BUILDINGS'); r.testLayer('Low Resolution 3d Buildings', false, 'LAYER_BUILDINGS_LOW_RESOLUTION'); r.run(); r.runRefreshTest(); })()
JavaScript
module('micro-templating'); test("list template", 1, function(){ template = [ "<ul>", "<% for (var i=0; i < users.length; i++) { %>", "<li><%= users[i].name %></li>", "<% } %>", "</ul>" ]; template = template.join(""); list_users = tmpl(template); data = {users: [{name:'me'}, {name: 'myself'}]} equals(list_users(data), "<ul><li>me</li><li>myself</li></ul>"); });
JavaScript
/* JS */
JavaScript
// usage: log('inside coolFunc', this, arguments); // paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/ window.log = function f(){ log.history = log.history || []; log.history.push(arguments); if(this.console) { var args = arguments, newarr; args.callee = args.callee.caller; newarr = [].slice.call(args); if (typeof console.log === 'object') log.apply.call(console.log, console, newarr); else console.log.apply(console, newarr);}}; // make it safe to use console.log always (function(a){function b(){}for(var c="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),d;!!(d=c.pop());){a[d]=a[d]||b;}}) (function(){try{console.log();return window.console;}catch(a){return (window.console={});}}()); // place any jQuery/helper plugins in here, instead of separate, slower script files.
JavaScript
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Function from : * http://trentgardner.net/jquery/serialize-json-with-jquery/ */ (function( $ ){ $.fn.serializeJSON=function() { var json = {}; jQuery.map($(this).serializeArray(), function(n, i){ json[n['name']] = n['value']; }); return json; }; })( jQuery ); $(function(){ $("input[type='password']").focus(function(){ $(this).val(''); }) $("input[type='text']").focus(function(){ $(this).val(''); }) function checkUser(){ //lay gia tri var username = $("input[name=username]").val(); var password = $("input[name=password]").val(); if( username == "" || password == "" ){ $("#result").html("").append("<p>ID và password không hợp lệ.</p>"); $("#result p").fadeOut(3000); return false; } return true; } $("input[name='login-button']").click(function(){ //chan su kien submit event.preventDefault(); $("#result").append('<div style="width:100%; text-align:center"><img src="img/loading.gif" /></div>'); // console.log($("#result")); if(!checkUser()){ return; } data = {data : JSON.stringify($("form").serializeJSON())}; console.log(data); if(data){ $.post('ajax_login', data, function(response) { //console.log(data); console.log(response); // response = jQuery.parseJSON(response); //console.log(response); //neu chuoi tra ve la true if( response.result == true){ $("form").fadeOut(500,function(){ //$("div#login").append("<h2 style='color:#454545;text-shadow: 0px 1px 1px #f5f5f5;'>Chào bạn " + response["user"] + "</h2>"); //redirect window.location.replace(response["url"]); }); }else{ $("#result").html("").append("<p>Người dùng không tồn tại hoặc sai mật khẩu.</p>"); $("#result p").fadeOut(3000); } console.log(result); }); } }); $("input[name='register-button']").bind('click', function(){ //chan su kien submit event.preventDefault(); if(!checkUser()){ return; } $("#result").append('<div style="width:100%; text-align:center"><img src="img/loading.gif" /></div>'); data = {data : JSON.stringify($("form").serializeJSON())}; //console.log(data); if(data){ $.post('ajax_register', data, function(response) { console.log(response); //response = jQuery.parseJSON(response); console.log(response); //neu chuoi tra ve la true if( response.result == true){ $("#result").html("").append("<p>Đăng ký thành công.</p>"); $("#result p").fadeOut(3000); }else{ $("#result").html("").append("<p>Người dùng đã tồn tại.</p>"); $("#result p").fadeOut(3000); } }); } }); }); $(function(){ $('.fancybox').fancybox({ 'onComplete': function() { $(".fancybox-wrap").css({'top':'20px', 'bottom':'auto'}); } }); })
JavaScript
// XRegExp 1.5.1 // (c) 2007-2012 Steven Levithan // MIT License // <http://xregexp.com> // Provides an augmented, extensible, cross-browser implementation of regular expressions, // including support for additional syntax, flags, and methods var XRegExp; if (XRegExp) { // Avoid running twice, since that would break references to native globals throw Error("can't load XRegExp twice in the same frame"); } // Run within an anonymous function to protect variables and avoid new globals (function (undefined) { //--------------------------------- // Constructor //--------------------------------- // Accepts a pattern and flags; returns a new, extended `RegExp` object. Differs from a native // regular expression in that additional syntax and flags are supported and cross-browser // syntax inconsistencies are ameliorated. `XRegExp(/regex/)` clones an existing regex and // converts to type XRegExp XRegExp = function (pattern, flags) { var output = [], currScope = XRegExp.OUTSIDE_CLASS, pos = 0, context, tokenResult, match, chr, regex; if (XRegExp.isRegExp(pattern)) { if (flags !== undefined) throw TypeError("can't supply flags when constructing one RegExp from another"); return clone(pattern); } // Tokens become part of the regex construction process, so protect against infinite // recursion when an XRegExp is constructed within a token handler or trigger if (isInsideConstructor) throw Error("can't call the XRegExp constructor within token definition functions"); flags = flags || ""; context = { // `this` object for custom tokens hasNamedCapture: false, captureNames: [], hasFlag: function (flag) {return flags.indexOf(flag) > -1;}, setFlag: function (flag) {flags += flag;} }; while (pos < pattern.length) { // Check for custom tokens at the current position tokenResult = runTokens(pattern, pos, currScope, context); if (tokenResult) { output.push(tokenResult.output); pos += (tokenResult.match[0].length || 1); } else { // Check for native multicharacter metasequences (excluding character classes) at // the current position if (match = nativ.exec.call(nativeTokens[currScope], pattern.slice(pos))) { output.push(match[0]); pos += match[0].length; } else { chr = pattern.charAt(pos); if (chr === "[") currScope = XRegExp.INSIDE_CLASS; else if (chr === "]") currScope = XRegExp.OUTSIDE_CLASS; // Advance position one character output.push(chr); pos++; } } } regex = RegExp(output.join(""), nativ.replace.call(flags, flagClip, "")); regex._xregexp = { source: pattern, captureNames: context.hasNamedCapture ? context.captureNames : null }; return regex; }; //--------------------------------- // Public properties //--------------------------------- XRegExp.version = "1.5.1"; // Token scope bitflags XRegExp.INSIDE_CLASS = 1; XRegExp.OUTSIDE_CLASS = 2; //--------------------------------- // Private variables //--------------------------------- var replacementToken = /\$(?:(\d\d?|[$&`'])|{([$\w]+)})/g, flagClip = /[^gimy]+|([\s\S])(?=[\s\S]*\1)/g, // Nonnative and duplicate flags quantifier = /^(?:[?*+]|{\d+(?:,\d*)?})\??/, isInsideConstructor = false, tokens = [], // Copy native globals for reference ("native" is an ES3 reserved keyword) nativ = { exec: RegExp.prototype.exec, test: RegExp.prototype.test, match: String.prototype.match, replace: String.prototype.replace, split: String.prototype.split }, compliantExecNpcg = nativ.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups compliantLastIndexIncrement = function () { var x = /^/g; nativ.test.call(x, ""); return !x.lastIndex; }(), hasNativeY = RegExp.prototype.sticky !== undefined, nativeTokens = {}; // `nativeTokens` match native multicharacter metasequences only (including deprecated octals, // excluding character classes) nativeTokens[XRegExp.INSIDE_CLASS] = /^(?:\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|c[A-Za-z]|[\s\S]))/; nativeTokens[XRegExp.OUTSIDE_CLASS] = /^(?:\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\d*|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|c[A-Za-z]|[\s\S])|\(\?[:=!]|[?*+]\?|{\d+(?:,\d*)?}\??)/; //--------------------------------- // Public methods //--------------------------------- // Lets you extend or change XRegExp syntax and create custom flags. This is used internally by // the XRegExp library and can be used to create XRegExp plugins. This function is intended for // users with advanced knowledge of JavaScript's regular expression syntax and behavior. It can // be disabled by `XRegExp.freezeTokens` XRegExp.addToken = function (regex, handler, scope, trigger) { tokens.push({ pattern: clone(regex, "g" + (hasNativeY ? "y" : "")), handler: handler, scope: scope || XRegExp.OUTSIDE_CLASS, trigger: trigger || null }); }; // Accepts a pattern and flags; returns an extended `RegExp` object. If the pattern and flag // combination has previously been cached, the cached copy is returned; otherwise the newly // created regex is cached XRegExp.cache = function (pattern, flags) { var key = pattern + "/" + (flags || ""); return XRegExp.cache[key] || (XRegExp.cache[key] = XRegExp(pattern, flags)); }; // Accepts a `RegExp` instance; returns a copy with the `/g` flag set. The copy has a fresh // `lastIndex` (set to zero). If you want to copy a regex without forcing the `global` // property, use `XRegExp(regex)`. Do not use `RegExp(regex)` because it will not preserve // special properties required for named capture XRegExp.copyAsGlobal = function (regex) { return clone(regex, "g"); }; // Accepts a string; returns the string with regex metacharacters escaped. The returned string // can safely be used at any point within a regex to match the provided literal string. Escaped // characters are [ ] { } ( ) * + ? - . , \ ^ $ | # and whitespace XRegExp.escape = function (str) { return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }; // Accepts a string to search, regex to search with, position to start the search within the // string (default: 0), and an optional Boolean indicating whether matches must start at-or- // after the position or at the specified position only. This function ignores the `lastIndex` // of the provided regex in its own handling, but updates the property for compatibility XRegExp.execAt = function (str, regex, pos, anchored) { var r2 = clone(regex, "g" + ((anchored && hasNativeY) ? "y" : "")), match; r2.lastIndex = pos = pos || 0; match = r2.exec(str); // Run the altered `exec` (required for `lastIndex` fix, etc.) if (anchored && match && match.index !== pos) match = null; if (regex.global) regex.lastIndex = match ? r2.lastIndex : 0; return match; }; // Breaks the unrestorable link to XRegExp's private list of tokens, thereby preventing // syntax and flag changes. Should be run after XRegExp and any plugins are loaded XRegExp.freezeTokens = function () { XRegExp.addToken = function () { throw Error("can't run addToken after freezeTokens"); }; }; // Accepts any value; returns a Boolean indicating whether the argument is a `RegExp` object. // Note that this is also `true` for regex literals and regexes created by the `XRegExp` // constructor. This works correctly for variables created in another frame, when `instanceof` // and `constructor` checks would fail to work as intended XRegExp.isRegExp = function (o) { return Object.prototype.toString.call(o) === "[object RegExp]"; }; // Executes `callback` once per match within `str`. Provides a simpler and cleaner way to // iterate over regex matches compared to the traditional approaches of subverting // `String.prototype.replace` or repeatedly calling `exec` within a `while` loop XRegExp.iterate = function (str, regex, callback, context) { var r2 = clone(regex, "g"), i = -1, match; while (match = r2.exec(str)) { // Run the altered `exec` (required for `lastIndex` fix, etc.) if (regex.global) regex.lastIndex = r2.lastIndex; // Doing this to follow expectations if `lastIndex` is checked within `callback` callback.call(context, match, ++i, str, regex); if (r2.lastIndex === match.index) r2.lastIndex++; } if (regex.global) regex.lastIndex = 0; }; // Accepts a string and an array of regexes; returns the result of using each successive regex // to search within the matches of the previous regex. The array of regexes can also contain // objects with `regex` and `backref` properties, in which case the named or numbered back- // references specified are passed forward to the next regex or returned. E.g.: // var xregexpImgFileNames = XRegExp.matchChain(html, [ // {regex: /<img\b([^>]+)>/i, backref: 1}, // <img> tag attributes // {regex: XRegExp('(?ix) \\s src=" (?<src> [^"]+ )'), backref: "src"}, // src attribute values // {regex: XRegExp("^http://xregexp\\.com(/[^#?]+)", "i"), backref: 1}, // xregexp.com paths // /[^\/]+$/ // filenames (strip directory paths) // ]); XRegExp.matchChain = function (str, chain) { return function recurseChain (values, level) { var item = chain[level].regex ? chain[level] : {regex: chain[level]}, regex = clone(item.regex, "g"), matches = [], i; for (i = 0; i < values.length; i++) { XRegExp.iterate(values[i], regex, function (match) { matches.push(item.backref ? (match[item.backref] || "") : match[0]); }); } return ((level === chain.length - 1) || !matches.length) ? matches : recurseChain(matches, level + 1); }([str], 0); }; //--------------------------------- // New RegExp prototype methods //--------------------------------- // Accepts a context object and arguments array; returns the result of calling `exec` with the // first value in the arguments array. the context is ignored but is accepted for congruity // with `Function.prototype.apply` RegExp.prototype.apply = function (context, args) { return this.exec(args[0]); }; // Accepts a context object and string; returns the result of calling `exec` with the provided // string. the context is ignored but is accepted for congruity with `Function.prototype.call` RegExp.prototype.call = function (context, str) { return this.exec(str); }; //--------------------------------- // Overriden native methods //--------------------------------- // Adds named capture support (with backreferences returned as `result.name`), and fixes two // cross-browser issues per ES3: // - Captured values for nonparticipating capturing groups should be returned as `undefined`, // rather than the empty string. // - `lastIndex` should not be incremented after zero-length matches. RegExp.prototype.exec = function (str) { var match, name, r2, origLastIndex; if (!this.global) origLastIndex = this.lastIndex; match = nativ.exec.apply(this, arguments); if (match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { r2 = RegExp(this.source, nativ.replace.call(getNativeFlags(this), "g", "")); // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed // matching due to characters outside the match nativ.replace.call((str + "").slice(match.index), r2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undefined) match[i] = undefined; } }); } // Attach named capture properties if (this._xregexp && this._xregexp.captureNames) { for (var i = 1; i < match.length; i++) { name = this._xregexp.captureNames[i - 1]; if (name) match[name] = match[i]; } } // Fix browsers that increment `lastIndex` after zero-length matches if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; } if (!this.global) this.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows) return match; }; // Fix browser bugs in native method RegExp.prototype.test = function (str) { // Use the native `exec` to skip some processing overhead, even though the altered // `exec` would take care of the `lastIndex` fixes var match, origLastIndex; if (!this.global) origLastIndex = this.lastIndex; match = nativ.exec.call(this, str); // Fix browsers that increment `lastIndex` after zero-length matches if (match && !compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; if (!this.global) this.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows) return !!match; }; // Adds named capture support and fixes browser bugs in native method String.prototype.match = function (regex) { if (!XRegExp.isRegExp(regex)) regex = RegExp(regex); // Native `RegExp` if (regex.global) { var result = nativ.match.apply(this, arguments); regex.lastIndex = 0; // Fix IE bug return result; } return regex.exec(this); // Run the altered `exec` }; // Adds support for `${n}` tokens for named and numbered backreferences in replacement text, // and provides named backreferences to replacement functions as `arguments[0].name`. Also // fixes cross-browser differences in replacement text syntax when performing a replacement // using a nonregex search value, and the value of replacement regexes' `lastIndex` property // during replacement iterations. Note that this doesn't support SpiderMonkey's proprietary // third (`flags`) parameter String.prototype.replace = function (search, replacement) { var isRegex = XRegExp.isRegExp(search), captureNames, result, str, origLastIndex; // There are too many combinations of search/replacement types/values and browser bugs that // preclude passing to native `replace`, so don't try //if (...) // return nativ.replace.apply(this, arguments); if (isRegex) { if (search._xregexp) captureNames = search._xregexp.captureNames; // Array or `null` if (!search.global) origLastIndex = search.lastIndex; } else { search = search + ""; // Type conversion } if (Object.prototype.toString.call(replacement) === "[object Function]") { result = nativ.replace.call(this + "", search, function () { if (captureNames) { // Change the `arguments[0]` string primitive to a String object which can store properties arguments[0] = new String(arguments[0]); // Store named backreferences on `arguments[0]` for (var i = 0; i < captureNames.length; i++) { if (captureNames[i]) arguments[0][captureNames[i]] = arguments[i + 1]; } } // Update `lastIndex` before calling `replacement` (fix browsers) if (isRegex && search.global) search.lastIndex = arguments[arguments.length - 2] + arguments[0].length; return replacement.apply(null, arguments); }); } else { str = this + ""; // Type conversion, so `args[args.length - 1]` will be a string (given nonstring `this`) result = nativ.replace.call(str, search, function () { var args = arguments; // Keep this function's `arguments` available through closure return nativ.replace.call(replacement + "", replacementToken, function ($0, $1, $2) { // Numbered backreference (without delimiters) or special variable if ($1) { switch ($1) { case "$": return "$"; case "&": return args[0]; case "`": return args[args.length - 1].slice(0, args[args.length - 2]); case "'": return args[args.length - 1].slice(args[args.length - 2] + args[0].length); // Numbered backreference default: // What does "$10" mean? // - Backreference 10, if 10 or more capturing groups exist // - Backreference 1 followed by "0", if 1-9 capturing groups exist // - Otherwise, it's the string "$10" // Also note: // - Backreferences cannot be more than two digits (enforced by `replacementToken`) // - "$01" is equivalent to "$1" if a capturing group exists, otherwise it's the string "$01" // - There is no "$0" token ("$&" is the entire match) var literalNumbers = ""; $1 = +$1; // Type conversion; drop leading zero if (!$1) // `$1` was "0" or "00" return $0; while ($1 > args.length - 3) { literalNumbers = String.prototype.slice.call($1, -1) + literalNumbers; $1 = Math.floor($1 / 10); // Drop the last digit } return ($1 ? args[$1] || "" : "$") + literalNumbers; } // Named backreference or delimited numbered backreference } else { // What does "${n}" mean? // - Backreference to numbered capture n. Two differences from "$n": // - n can be more than two digits // - Backreference 0 is allowed, and is the entire match // - Backreference to named capture n, if it exists and is not a number overridden by numbered capture // - Otherwise, it's the string "${n}" var n = +$2; // Type conversion; drop leading zeros if (n <= args.length - 3) return args[n]; n = captureNames ? indexOf(captureNames, $2) : -1; return n > -1 ? args[n + 1] : $0; } }); }); } if (isRegex) { if (search.global) search.lastIndex = 0; // Fix IE, Safari bug (last tested IE 9.0.5, Safari 5.1.2 on Windows) else search.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows) } return result; }; // A consistent cross-browser, ES3 compliant `split` String.prototype.split = function (s /* separator */, limit) { // If separator `s` is not a regex, use the native `split` if (!XRegExp.isRegExp(s)) return nativ.split.apply(this, arguments); var str = this + "", // Type conversion output = [], lastLastIndex = 0, match, lastLength; // Behavior for `limit`: if it's... // - `undefined`: No limit // - `NaN` or zero: Return an empty array // - A positive number: Use `Math.floor(limit)` // - A negative number: No limit // - Other: Type-convert, then use the above rules if (limit === undefined || +limit < 0) { limit = Infinity; } else { limit = Math.floor(+limit); if (!limit) return []; } // This is required if not `s.global`, and it avoids needing to set `s.lastIndex` to zero // and restore it to its original value when we're done using the regex s = XRegExp.copyAsGlobal(s); while (match = s.exec(str)) { // Run the altered `exec` (required for `lastIndex` fix, etc.) if (s.lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); if (match.length > 1 && match.index < str.length) Array.prototype.push.apply(output, match.slice(1)); lastLength = match[0].length; lastLastIndex = s.lastIndex; if (output.length >= limit) break; } if (s.lastIndex === match.index) s.lastIndex++; } if (lastLastIndex === str.length) { if (!nativ.test.call(s, "") || lastLength) output.push(""); } else { output.push(str.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; //--------------------------------- // Private helper functions //--------------------------------- // Supporting function for `XRegExp`, `XRegExp.copyAsGlobal`, etc. Returns a copy of a `RegExp` // instance with a fresh `lastIndex` (set to zero), preserving properties required for named // capture. Also allows adding new flags in the process of copying the regex function clone (regex, additionalFlags) { if (!XRegExp.isRegExp(regex)) throw TypeError("type RegExp expected"); var x = regex._xregexp; regex = XRegExp(regex.source, getNativeFlags(regex) + (additionalFlags || "")); if (x) { regex._xregexp = { source: x.source, captureNames: x.captureNames ? x.captureNames.slice(0) : null }; } return regex; } function getNativeFlags (regex) { return (regex.global ? "g" : "") + (regex.ignoreCase ? "i" : "") + (regex.multiline ? "m" : "") + (regex.extended ? "x" : "") + // Proposed for ES4; included in AS3 (regex.sticky ? "y" : ""); } function runTokens (pattern, index, scope, context) { var i = tokens.length, result, match, t; // Protect against constructing XRegExps within token handler and trigger functions isInsideConstructor = true; // Must reset `isInsideConstructor`, even if a `trigger` or `handler` throws try { while (i--) { // Run in reverse order t = tokens[i]; if ((scope & t.scope) && (!t.trigger || t.trigger.call(context))) { t.pattern.lastIndex = index; match = t.pattern.exec(pattern); // Running the altered `exec` here allows use of named backreferences, etc. if (match && match.index === index) { result = { output: t.handler.call(context, match, scope), match: match }; break; } } } } catch (err) { throw err; } finally { isInsideConstructor = false; } return result; } function indexOf (array, item, from) { if (Array.prototype.indexOf) // Use the native array method if available return array.indexOf(item, from); for (var i = from || 0; i < array.length; i++) { if (array[i] === item) return i; } return -1; } //--------------------------------- // Built-in tokens //--------------------------------- // Augment XRegExp's regular expression syntax and flags. Note that when adding tokens, the // third (`scope`) argument defaults to `XRegExp.OUTSIDE_CLASS` // Comment pattern: (?# ) XRegExp.addToken( /\(\?#[^)]*\)/, function (match) { // Keep tokens separated unless the following token is a quantifier return nativ.test.call(quantifier, match.input.slice(match.index + match[0].length)) ? "" : "(?:)"; } ); // Capturing group (match the opening parenthesis only). // Required for support of named capturing groups XRegExp.addToken( /\((?!\?)/, function () { this.captureNames.push(null); return "("; } ); // Named capturing group (match the opening delimiter only): (?<name> XRegExp.addToken( /\(\?<([$\w]+)>/, function (match) { this.captureNames.push(match[1]); this.hasNamedCapture = true; return "("; } ); // Named backreference: \k<name> XRegExp.addToken( /\\k<([\w$]+)>/, function (match) { var index = indexOf(this.captureNames, match[1]); // Keep backreferences separate from subsequent literal numbers. Preserve back- // references to named groups that are undefined at this point as literal strings return index > -1 ? "\\" + (index + 1) + (isNaN(match.input.charAt(match.index + match[0].length)) ? "" : "(?:)") : match[0]; } ); // Empty character class: [] or [^] XRegExp.addToken( /\[\^?]/, function (match) { // For cross-browser compatibility with ES3, convert [] to \b\B and [^] to [\s\S]. // (?!) should work like \b\B, but is unreliable in Firefox return match[0] === "[]" ? "\\b\\B" : "[\\s\\S]"; } ); // Mode modifier at the start of the pattern only, with any combination of flags imsx: (?imsx) // Does not support x(?i), (?-i), (?i-m), (?i: ), (?i)(?m), etc. XRegExp.addToken( /^\(\?([imsx]+)\)/, function (match) { this.setFlag(match[1]); return ""; } ); // Whitespace and comments, in free-spacing (aka extended) mode only XRegExp.addToken( /(?:\s+|#.*)+/, function (match) { // Keep tokens separated unless the following token is a quantifier return nativ.test.call(quantifier, match.input.slice(match.index + match[0].length)) ? "" : "(?:)"; }, XRegExp.OUTSIDE_CLASS, function () {return this.hasFlag("x");} ); // Dot, in dotall (aka singleline) mode only XRegExp.addToken( /\./, function () {return "[\\s\\S]";}, XRegExp.OUTSIDE_CLASS, function () {return this.hasFlag("s");} ); //--------------------------------- // Backward compatibility //--------------------------------- // Uncomment the following block for compatibility with XRegExp 1.0-1.2: /* XRegExp.matchWithinChain = XRegExp.matchChain; RegExp.prototype.addFlags = function (s) {return clone(this, s);}; RegExp.prototype.execAll = function (s) {var r = []; XRegExp.iterate(s, this, function (m) {r.push(m);}); return r;}; RegExp.prototype.forEachExec = function (s, f, c) {return XRegExp.iterate(s, this, f, c);}; RegExp.prototype.validate = function (s) {var r = RegExp("^(?:" + this.source + ")$(?!\\s)", getNativeFlags(this)); if (this.global) this.lastIndex = 0; return s.search(r) === 0;}; */ })();
JavaScript
(function() { var sh = SyntaxHighlighter; /** * Provides functionality to dynamically load only the brushes that a needed to render the current page. * * There are two syntaxes that autoload understands. For example: * * SyntaxHighlighter.autoloader( * [ 'applescript', 'Scripts/shBrushAppleScript.js' ], * [ 'actionscript3', 'as3', 'Scripts/shBrushAS3.js' ] * ); * * or a more easily comprehendable one: * * SyntaxHighlighter.autoloader( * 'applescript Scripts/shBrushAppleScript.js', * 'actionscript3 as3 Scripts/shBrushAS3.js' * ); */ sh.autoloader = function() { var list = arguments, elements = sh.findElements(), brushes = {}, scripts = {}, all = SyntaxHighlighter.all, allCalled = false, allParams = null, i ; SyntaxHighlighter.all = function(params) { allParams = params; allCalled = true; }; function addBrush(aliases, url) { for (var i = 0; i < aliases.length; i++) brushes[aliases[i]] = url; }; function getAliases(item) { return item.pop ? item : item.split(/\s+/) ; } // create table of aliases and script urls for (i = 0; i < list.length; i++) { var aliases = getAliases(list[i]), url = aliases.pop() ; addBrush(aliases, url); } // dynamically add <script /> tags to the document body for (i = 0; i < elements.length; i++) { var url = brushes[elements[i].params.brush]; if (!url) continue; scripts[url] = false; loadScript(url); } function loadScript(url) { var script = document.createElement('script'), done = false ; script.src = url; script.type = 'text/javascript'; script.language = 'javascript'; script.onload = script.onreadystatechange = function() { if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { done = true; scripts[url] = true; checkAll(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; script.parentNode.removeChild(script); } }; // sync way of adding script tags to the page document.body.appendChild(script); }; function checkAll() { for(var url in scripts) if (scripts[url] == false) return; if (allCalled) SyntaxHighlighter.highlight(allParams); }; }; })();
JavaScript
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.6 * * Requires: 1.2.2+ */ (function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;b.axis!==void 0&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);b.wheelDeltaY!==void 0&&(g=b.wheelDeltaY/120);b.wheelDeltaX!==void 0&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]= d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,false);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,false);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
JavaScript
/* Holder - 1.6 - client side image placeholders (c) 2012 Ivan Malopinsky / http://imsky.co Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var preempted = false, fallback = false, canvas = document.createElement('canvas'); //getElementsByClassName polyfill document.getElementsByClassName||(document.getElementsByClassName=function(e){var t=document,n,r,i,s=[];if(t.querySelectorAll)return t.querySelectorAll("."+e);if(t.evaluate){r=".//*[contains(concat(' ', @class, ' '), ' "+e+" ')]",n=t.evaluate(r,t,null,0,null);while(i=n.iterateNext())s.push(i)}else{n=t.getElementsByTagName("*"),r=new RegExp("(^|\\s)"+e+"(\\s|$)");for(i=0;i<n.length;i++)r.test(n[i].className)&&s.push(n[i])}return s}) //getComputedStyle polyfill window.getComputedStyle||(window.getComputedStyle=function(e,t){return this.el=e,this.getPropertyValue=function(t){var n=/(\-([a-z]){1})/g;return t=="float"&&(t="styleFloat"),n.test(t)&&(t=t.replace(n,function(){return arguments[2].toUpperCase()})),e.currentStyle[t]?e.currentStyle[t]:null},this}) //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}; //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a){ a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]); var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret; } //shallow object property extend function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c} function text_size(width, height, template) { var dimension_arr = [height, width].sort(); var maxFactor = Math.round(dimension_arr[1] / 16), minFactor = Math.round(dimension_arr[0] / 16); var text_height = Math.max(template.size, maxFactor); return { height: text_height } } function draw(ctx, dimensions, template, ratio) { var ts = text_size(dimensions.width, dimensions.height, template); var text_height = ts.height; var width = dimensions.width * ratio, height = dimensions.height * ratio; canvas.width = width; canvas.height = height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, width, height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px sans-serif"; var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height); if (ctx.measureText(text).width / width > 1) { text_height = template.size / (ctx.measureText(text).width / width); } ctx.font = "bold " + (text_height * ratio) + "px sans-serif"; ctx.fillText(text, (width / 2), (height / 2), width); return canvas.toDataURL("image/png"); } function render(mode, el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); var ratio = 1; if(window.devicePixelRatio && window.devicePixelRatio > 1){ ratio = window.devicePixelRatio; } if (mode == "image") { el.setAttribute("data-src", src); el.setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); el.style.width = dimensions.width + "px"; el.style.height = dimensions.height + "px"; if (fallback) { el.style.backgroundColor = theme.background; } else{ el.setAttribute("src", draw(ctx, dimensions, theme, ratio)); } } else { if (!fallback) { el.style.backgroundImage = "url(" + draw(ctx, dimensions, theme, ratio) + ")"; el.style.backgroundSize = dimensions.width+"px "+dimensions.height+"px"; } } }; function fluid(el, holder, src) { var dimensions = holder.dimensions, theme = holder.theme, text = holder.text; var dimensions_caption = dimensions.width + "x" + dimensions.height; theme = (text ? extend(theme, { text: text }) : theme); var fluid = document.createElement("table"); fluid.setAttribute("cellspacing",0) fluid.setAttribute("cellpadding",0) fluid.setAttribute("border",0) var row = document.createElement("tr") .appendChild(document.createElement("td") .appendChild(document.createTextNode(theme.text))); fluid.style.backgroundColor = theme.background; fluid.style.color = theme.foreground; fluid.className = el.className + " holderjs-fluid"; fluid.style.width = holder.dimensions.width + (holder.dimensions.width.indexOf("%")>0?"":"px"); fluid.style.height = holder.dimensions.height + (holder.dimensions.height.indexOf("%")>0?"":"px"); fluid.id = el.id; var frag = document.createDocumentFragment(), tbody = document.createElement("tbody"), tr = document.createElement("tr"), td = document.createElement("td"); tr.appendChild(td); tbody.appendChild(tr); frag.appendChild(tbody); if (theme.text) { td.appendChild(document.createTextNode(theme.text)) fluid.appendChild(frag); } else { td.appendChild(document.createTextNode(dimensions_caption)) fluid.appendChild(frag); fluid_images.push(fluid); setTimeout(fluid_update, 0); } el.parentNode.replaceChild(fluid, el); } function fluid_update() { for (i in fluid_images) { var el = fluid_images[i]; var label = el.getElementsByTagName("td")[0].firstChild; label.data = el.offsetWidth + "x" + el.offsetHeight; } } function parse_flags(flags, options) { var ret = { theme: settings.themes.gray }, render = false; for (sl = flags.length, j = 0; j < sl; j++) { var flag = flags[j]; if (app.flags.dimensions.match(flag)) { render = true; ret.dimensions = app.flags.dimensions.output(flag); } else if (app.flags.fluid.match(flag)) { render = true; ret.dimensions = app.flags.fluid.output(flag); ret.fluid = true; } else if (app.flags.colors.match(flag)) { ret.theme = app.flags.colors.output(flag); } else if (options.themes[flag]) { //If a theme is specified, it will override custom colors ret.theme = options.themes[flag]; } else if (app.flags.text.match(flag)) { ret.text = app.flags.text.output(flag); } } return render ? ret : false; }; if (!canvas.getContext) { fallback = true; } else { if (canvas.toDataURL("image/png") .indexOf("data:image/png") < 0) { //Android doesn't support data URI fallback = true; } else { var ctx = canvas.getContext("2d"); } } var fluid_images = []; var settings = { domain: "holder.js", images: "img", elements: ".holderjs", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 } }, stylesheet: ".holderjs-fluid {font-size:16px;font-weight:bold;text-align:center;font-family:sans-serif;border-collapse:collapse;border:0;vertical-align:middle;margin:0}" }; app.flags = { dimensions: { regex: /(\d+)x(\d+)/, output: function (val) { var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, fluid: { regex: /([0-9%]+)x([0-9%]+)/, output: function (val) { var exec = this.regex.exec(val); return { width: exec[1], height: exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function (val) { var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function (val) { return this.regex.exec(val)[1]; } } } for (var flag in app.flags) { app.flags[flag].match = function (val) { return val.match(this.regex) } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { var options = extend(settings, o), images_nodes = selector(options.images), elements = selector(options.elements), preempted = true, images = []; for (i = 0, l = images_nodes.length; i < l; i++) images.push(images_nodes[i]); var holdercss = document.createElement("style"); holdercss.type = "text/css"; holdercss.styleSheet ? holdercss.styleSheet.cssText = options.stylesheet : holdercss.textContent = options.stylesheet; document.getElementsByTagName("head")[0].appendChild(holdercss); var cssregex = new RegExp(options.domain + "\/(.*?)\"?\\)"); for (var l = elements.length, i = 0; i < l; i++) { var src = window.getComputedStyle(elements[i], null) .getPropertyValue("background-image"); var flags = src.match(cssregex); if (flags) { var holder = parse_flags(flags[1].split("/"), options); if (holder) { render("background", elements[i], holder, src); } } } for (var l = images.length, i = 0; i < l; i++) { var src = images[i].getAttribute("src") || images[i].getAttribute("data-src"); if (src != null && src.indexOf(options.domain) >= 0) { var holder = parse_flags(src.substr(src.lastIndexOf(options.domain) + options.domain.length + 1) .split("/"), options); if (holder) { if (holder.fluid) { fluid(images[i], holder, src); } else { render("image", images[i], holder, src); } } } } return app; }; contentLoaded(win, function () { if (window.addEventListener) { window.addEventListener("resize", fluid_update, false); window.addEventListener("orientationchange", fluid_update, false); } else { window.attachEvent("onresize", fluid_update) } preempted || app.run(); }); })(Holder, window);
JavaScript
// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT // IT'S ALL JUST JUNK FOR OUR DOCS! // ++++++++++++++++++++++++++++++++++++++++++ !function ($) { $(function(){ var $window = $(window) // Disable certain links in docs $('section [href^=#]').click(function (e) { e.preventDefault() }) // side bar $('.bs-docs-sidenav').affix({ offset: { top: function () { return $window.width() <= 980 ? 290 : 210 } , bottom: 270 } }) // make code pretty window.prettyPrint && prettyPrint() // add-ons $('.add-on :checkbox').on('click', function () { var $this = $(this) , method = $this.attr('checked') ? 'addClass' : 'removeClass' $(this).parents('.add-on')[method]('active') }) // add tipsies to grid for scaffolding if ($('#gridSystem').length) { $('#gridSystem').tooltip({ selector: '.show-grid > div' , title: function () { return $(this).width() + 'px' } }) } // tooltip demo $('.tooltip-demo').tooltip({ selector: "a[rel=tooltip]" }) $('.tooltip-test').tooltip() $('.popover-test').popover() // popover demo $("a[rel=popover]") .popover() .click(function(e) { e.preventDefault() }) // button state demo $('#fat-btn') .click(function () { var btn = $(this) btn.button('loading') setTimeout(function () { btn.button('reset') }, 3000) }) // carousel demo $('#myCarousel').carousel() // javascript build logic var inputsComponent = $("#components.download input") , inputsPlugin = $("#plugins.download input") , inputsVariables = $("#variables.download input") // toggle all plugin checkboxes $('#components.download .toggle-all').on('click', function (e) { e.preventDefault() inputsComponent.attr('checked', !inputsComponent.is(':checked')) }) $('#plugins.download .toggle-all').on('click', function (e) { e.preventDefault() inputsPlugin.attr('checked', !inputsPlugin.is(':checked')) }) $('#variables.download .toggle-all').on('click', function (e) { e.preventDefault() inputsVariables.val('') }) // request built javascript $('.download-btn .btn').on('click', function () { var css = $("#components.download input:checked") .map(function () { return this.value }) .toArray() , js = $("#plugins.download input:checked") .map(function () { return this.value }) .toArray() , vars = {} , img = ['glyphicons-halflings.png', 'glyphicons-halflings-white.png'] $("#variables.download input") .each(function () { $(this).val() && (vars[ $(this).prev().text() ] = $(this).val()) }) $.ajax({ type: 'POST' , url: /\?dev/.test(window.location) ? 'http://localhost:3000' : 'http://bootstrap.herokuapp.com' , dataType: 'jsonpi' , params: { js: js , css: css , vars: vars , img: img } }) }) }) // Modified from the original jsonpi https://github.com/benvinegar/jquery-jsonpi $.ajaxTransport('jsonpi', function(opts, originalOptions, jqXHR) { var url = opts.url; return { send: function(_, completeCallback) { var name = 'jQuery_iframe_' + jQuery.now() , iframe, form iframe = $('<iframe>') .attr('name', name) .appendTo('head') form = $('<form>') .attr('method', opts.type) // GET or POST .attr('action', url) .attr('target', name) $.each(opts.params, function(k, v) { $('<input>') .attr('type', 'hidden') .attr('name', k) .attr('value', typeof v == 'string' ? v : JSON.stringify(v)) .appendTo(form) }) form.appendTo('body').submit() } } }) }(window.jQuery)
JavaScript
//<![CDATA[ // Recent Post widget for Blogger with Preloader // Author: Taufik Nurrohman // https://plus.google.com/108949996304093815163/about // Licence: Free for change, keep the original attribution, non commercial function showRecentPosts(json) { for (var i = 0; i < rp_numPosts; i++) { if (i == json.feed.entry.length) break; var entry = json.feed.entry[i], postTitle = entry.title.$t, postAuthor = entry.author[0].name.$t, postDate = entry.published.$t.substring(0, 10), postUrl, linkTarget, postContent, postImage, skeleton = ""; var dy = postDate.substring(0, 4), dm = postDate.substring(5, 7), dd = postDate.substring(8, 10); for (var j = 0; j < entry.link.length; j++) { if (entry.link[j].rel == 'alternate') { postUrl = entry.link[j].href; break; } } for (var k = 0; k < entry.link.length; k++) { if (entry.link[k].rel == 'replies' && entry.link[k].type == 'text/html') { commentNum = entry.link[k].title.split(" ")[0]; commentLabel = entry.link[k].title.split(" ")[1]; break; } } if ("content" in entry) { postContent = entry.content.$t; } else if ("summary" in entry) { postContent = entry.summary.$t; } else { postContent = ''; } if (rp_thumbWidth !== 0) { if ("media$thumbnail" in entry) { postImage = '<img style="width:' + rp_thumbWidth + 'px;height:' + rp_thumbWidth + 'px;" src="' + entry.media$thumbnail.url.replace(/\/s[0-9]+\-c/g, "\/s" + rp_thumbWidth + "-c") + '" alt="Loading..." />'; } else { postImage = '<img style="width:' + rp_thumbWidth + 'px;height:' + rp_thumbWidth + 'px;" src="' + rp_noImage + '" alt="Loading..."/>'; } } else { postImage = ""; } postContent = postContent.replace(/<br ?\/?>/ig, " "); postContent = postContent.replace(/<\S[^>]*>/g, ""); if (postContent.length > rp_numChars) { if (rp_numChars !== 0) { postContent = postContent.substring(0, rp_numChars) + '&hellip;'; } else { postContent = ''; } } linkTarget = (rp_newTabLink) ? ' target="_blank"' : ''; skeleton = '<li>'; skeleton += '<a href="' + postUrl + '"' + linkTarget + '>' + postImage + '</a>'; skeleton += '<div class="recent-right">'; skeleton += '<a class="title" href="' + postUrl + '"' + linkTarget + '>' + postTitle + '</a>'; skeleton += postContent; skeleton += '</div>'; skeleton += '<br style="clear:both;"/><span class="foot"><span class="recent-date">' + dd + ' ' + rp_monthNames[parseInt(dm, 10) - 1] + ' ' + dy + '</span></span>'; skeleton += '</li>'; document.getElementById('recent-post').innerHTML += skeleton; } } var labelName = (rp_sortByLabel !== false) ? '-/' + rp_sortByLabel : ""; var rp_script = document.createElement('script'); rp_script.src = rp_homePage + '/feeds/posts/default/' + labelName + '?alt=json-in-script&callback=showRecentPosts'; // Preloading... if (rp_loadTimer === "onload") { window.onload = function() { document.getElementsByTagName('head')[0].appendChild(rp_script); }; } else { setTimeout(function() { document.getElementsByTagName('head')[0].appendChild(rp_script); }, rp_loadTimer); } //]]>
JavaScript
var JudNav = {}; //Pengambilan judul artikel melalui feed function ambilJudNav(json) { for (var i = 0; i < json.feed.entry.length; i++) { var judul = json.feed.entry[i]; var data = ""; for (var k = 0; k < judul.link.length; k++) { if (judul.link[k].rel == 'alternate') { data = judul.link[k].href; break } } if (data != "") JudNav[data] = judul.title.$t } } //Penulisan sekumpulan judul feed dengan mengambilnya dari fungsi sebelumnya 'ambilJudNav' document.write('<script type="text/javascript" src="http://' + window.location.hostname + '/feeds/posts/summary?redirect=false&max-results=500&alt=json-in-script&callback=ambilJudNav"></' + 'script>'); //Pengambilan Anchor, Pengecekan URL dan Penggantian beberapa simbol function JudulURL(anchor) { var linkurl = anchor.match(/\/([^\/_]+)(_.*)?\.html/); if (linkurl) { linkurl = linkurl[1].replace(/-/g, " "); linkurl = linkurl[0].toUpperCase() + linkurl.slice(1); if (linkurl.length > 28) linkurl = linkurl.replace(/ [^ ]+$/, "...") } return linkurl } //Mengganti 'Posting Lama' dan 'Posting Lebih Baru' $(window).load(function () { window.setTimeout(function () { var anchor = $("a.blog-pager-newer-link").attr("href"); if (anchor) { var judul = JudNav[anchor]; if (!judul) judul = JudulURL(anchor); if (judul) $("a.blog-pager-newer-link").html(judul) } anchor = $("a.blog-pager-older-link").attr("href"); if (anchor) { var judul = JudNav[anchor]; if (!judul) judul = JudulURL(anchor); if (judul) $("a.blog-pager-older-link").html(judul) } }, 500) });
JavaScript
//<![CDATA[ var thumbnail_mode = "float" ; summary_noimg = 250; summary_img = 210; img_thumb_size = 95; var numm_rand_post=3; function removeHtmlTag(strx,chop){ if(strx.indexOf("<")!=-1){ var s = strx.split("<"); for(var i=0;i<s.length;i++){ if(s[i].indexOf(">")!=-1){ s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length); } } strx = s.join(""); } chop = (chop < strx.length-1) ? chop : strx.length-2; while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++; strx = strx.substring(0,chop-1); return strx+'...'; } function createTumbnail(thumbUrl,img_size) { var thumbnail = thumbUrl ; var patt0 = /s72-c/g; var patt1 = /s200/g; var patt2 = /s320/g; var patt3 = /s400/g; var patt4 = /s640/g; var patt5 = /s1600/g; if ( patt1.test(thumbnail) == true) { thumbnail = thumbnail.replace("s200","s"+img_size+"-c"); return thumbnail; } else if (patt2.test(thumbnail) == true) { thumbnail = thumbnail.replace("s320","s"+img_size+"-c"); return thumbnail; } else if (patt3.test(thumbnail) == true) { thumbnail = thumbnail.replace("s400","s"+img_size+"-c"); return thumbnail; } else if (patt4.test(thumbnail) == true) { thumbnail = thumbnail.replace("s640","s"+img_size+"-c"); return thumbnail; } else if (patt5.test(thumbnail) == true) { thumbnail = thumbnail.replace("s1600","s"+img_size+"-c"); return thumbnail; } else if (patt0.test(thumbnail) == true) { thumbnail = thumbnail.replace("s72-c","s"+img_size+"-c"); return thumbnail; } } function popTumbnail(Turl,Tsize) { return ('<img src="'+createTumbnail(Turl,Tsize)+'" />'); } function createSummaryAndThumb(ID,pURL,pTitle){ var pID = 'summary' + ID; var pThumb = 'thumbnail-' + ID; var div = document.getElementById(pID); var thumb = document.getElementById(pThumb); var imgtag = ""; var img = div.getElementsByTagName("img"); var summ = summary_noimg; if(img.length>=1) { imgtag = '<span style="padding:0px;"><a href="'+ pURL +'" alt="tumbnail" title="'+ pTitle +'"><img src="' + img[0].src + '" alt="thumbnails"/></a></span>'; summ = summary_img; } else { imgtag = ''; summ = summary_img; } thumb.innerHTML = imgtag ; div.innerHTML = '<div>' + removeHtmlTag(div.innerHTML,summ) + '</div>'; } //]]>
JavaScript
$(document).ready(function() { function filterPath(string) { return string .replace(/^\//,'') .replace(/(index|default).[a-zA-Z]{3,4}$/,'') .replace(/\/$/,''); } var locationPath = filterPath(location.pathname); var scrollElem = scrollableElement('html', 'body'); $('a[href*=#]').each(function() { var thisPath = filterPath(this.pathname) || locationPath; if ( locationPath == thisPath && (location.hostname == this.hostname || !this.hostname) && this.hash.replace(/#/,'') ) { var $target = $(this.hash), target = this.hash; if (target) { var targetOffset = $target.offset().top; $(this).click(function(event) { event.preventDefault(); $(scrollElem).animate({scrollTop: targetOffset}, 400, function() { location.hash = target; }); }); } } }); // use the first element that is "scrollable" function scrollableElement(els) { for (var i = 0, argLength = arguments.length; i <argLength; i++) { var el = arguments[i], $scrollElement = $(el); if ($scrollElement.scrollTop()> 0) { return el; } else { $scrollElement.scrollTop(1); var isScrollable = $scrollElement.scrollTop()> 0; $scrollElement.scrollTop(0); if (isScrollable) { return el; } } } return []; } });
JavaScript
//<![CDATA[ $(document).ready(function() { function getTargetTop(elem){ var id = elem.attr("href"); var offset = 60; return $(id).offset().top - offset; } $('a[href^="#"]').click(function(event) { var target = getTargetTop($(this)); $('html, body').animate({scrollTop:target}, 1200); event.preventDefault(); }); var sections = $('a[href^="#"]'); function checkSectionSelected(scrolledTo){ var threshold = 200; var i; for (i = 0; i < sections.length; i++) { var section = $(sections[i]); var target = getTargetTop(section); if (scrolledTo > target - threshold && scrolledTo < target + threshold) { sections.removeClass("active"); section.addClass("active"); } } ;} checkSectionSelected($(window).scrollTop()); $(window).scroll(function(e){ checkSectionSelected($(window).scrollTop()) }); }); //]]>
JavaScript
<script src="http://static.simile.mit.edu/exhibit/api-2.0/exhibit-api.js" type="text/javascript"></script> <script src="http://static.simile.mit.edu/exhibit/extensions-2.0/time/time-extension.js"></script> <link rel="exhibit/data" type="application/jsonp" href="https://spreadsheets.google.com/feeds/list/0Asy9DLkAdegIdHpQQmxxSFM5NjZaSVFEbks4bUlvcnc/od5/public/basic?alt=json-in-script" ex:converter="googleSpreadsheets" />
JavaScript
/*** credits: http://people.csail.mit.edu/dfhuynh/projects/timeline-exhibit/filtered-sources.js ***/ Timeline.FilteredEventSource = function(baseEventSource, match) { this._baseEventSource = baseEventSource; this._match = match; this._events = new SimileAjax.EventIndex(); this._listeners = []; var self = this; this._eventListener = { onAddMany: function() { console.log("here"); self._onAddMany(); }, onClear: function() { self._onClear(); } } this._baseEventSource.addListener(this._eventListener); if (this._baseEventSource.getCount() > 0) { this._onAddMany(); } }; Timeline.FilteredEventSource.prototype.addListener = function(listener) { this._listeners.push(listener); }; Timeline.FilteredEventSource.prototype.removeListener = function(listener) { for (var i = 0; i < this._listeners.length; i++) { if (this._listeners[i] == listener) { this._listeners.splice(i, 1); break; } } }; Timeline.FilteredEventSource.prototype.getEvent = function(id) { return this._events.getEvent(id); }; Timeline.FilteredEventSource.prototype.getEventIterator = function(startDate, endDate) { return this._events.getIterator(startDate, endDate); }; Timeline.FilteredEventSource.prototype.getEventReverseIterator = function(startDate, endDate) { return this._events.getReverseIterator(startDate, endDate); }; Timeline.FilteredEventSource.prototype.getAllEventIterator = function() { return this._events.getAllIterator(); }; Timeline.FilteredEventSource.prototype.getCount = function() { return this._events.getCount(); }; Timeline.FilteredEventSource.prototype.getEarliestDate = function() { return this._events.getEarliestDate(); }; Timeline.FilteredEventSource.prototype.getLatestDate = function() { return this._events.getLatestDate(); }; Timeline.FilteredEventSource.prototype._fire = function(handlerName, args) { for (var i = 0; i < this._listeners.length; i++) { var listener = this._listeners[i]; if (handlerName in listener) { try { listener[handlerName].apply(listener, args); } catch (e) { SimileAjax.Debug.exception(e); } } } }; Timeline.FilteredEventSource.prototype._onAddMany = function() { this._events.removeAll(); var i = this._baseEventSource.getAllEventIterator(); while (i.hasNext()) { var evt = i.next(); if (this._match(evt)) { this._events.add(evt); } } this._fire("onAddMany", []); }; Timeline.FilteredEventSource.prototype._onClear = function() { this._events.removeAll(); this._fire("onClear", []); };
JavaScript
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAATTj_4YkZuaihAx0kvqq_3RT5TQ_3V3oDWogljA9hi5DEPPK3KBSMksPojdd95A7CAZ1r7YjmZTs36g" type="text/javascript"></script> <script type="text/javascript" src="http://timemap.googlecode.com/svn/tags/2.0/lib/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="http://timemap.googlecode.com/svn/tags/2.0/lib/mxn/mxn.js?(google)"></script> <script type="text/javascript" src="http://timemap.googlecode.com/svn/tags/2.0/lib/timeline-1.2.js"></script> <script src="http://timemap.googlecode.com/svn/tags/2.0/src/timemap.js" type="text/javascript"></script> <script src="http://timemap.googlecode.com/svn/tags/2.0/src/param.js" type="text/javascript"></script> <script src="http://timemap.googlecode.com/svn/tags/2.0/src/loaders/json.js" type="text/javascript"></script> <script src="http://timemap.googlecode.com/svn/tags/2.0/src/loaders/google_spreadsheet.js" type="text/javascript"></script> <script type="text/javascript"> var tm; $(function() { tm = TimeMap.init({ mapId: "map", // Id of map div element (required) timelineId: "timeline", // Id of timeline div element (required) options: { eventIconPath: "http://timemap.googlecode.com/svn/tags/2.0/images/" }, datasets: [ { title: "Events", id: "events", theme: "purple", type: "gss", options: { // lon/lat->ll= key: "0Asy9DLkAdegIdGpENjRxSEU5VnItNzJMUU16R2NmT3c", // map spreadsheet column names to expected ids paramMap: { start: "start", end: "end" }, // load extra data from non-standard spreadsheet columns extraColumns: [ "time", "place", "author", "remarks" ], // let's do something with that extra data! infoTemplate: "<table style='quarrytable'>" + "<tr><th colspan='2' class='title'>Details</th></tr>" + "<tr><th>Book</th><td>{{title}}</td></tr>" + "<tr><th>Desc.</th><td>{{description}}</td></tr>" + "<tr><th>Time</th><td>{{time}}</td></tr>" + "<tr><th>Place</th><td>{{place}}</td></tr>" + "<tr><th>Author</th><td>{{author}}</td></tr>" + "<tr><th>Remarks</th><td>{{remarks}}</td></tr>" + "</table>" } } ], bandIntervals: [ Timeline.DateTime.YEAR, Timeline.DateTime.DECADE ], scrollTo: "0064" }); }); </script> <link href="http://timemap.googlecode.com/svn/tags/2.0/examples/examples.css" type="text/css" rel="stylesheet"/> <style> div#timelinecontainer{ width: 100%; height: 40%; } div#timeline{ width: 100%; height: 100%; font-size: 12px; background: #CCCCCC; } div#mapcontainer { width: 100%; height: 60%; } #timemap { height: 650px; } div#map { width: 100%; height: 100%; background: #EEEEEE; } div.infodescription { font-style: normal; width: 300px; } </style>
JavaScript
/*** add the following contect in the html header section: <http://123bible.googlecode.com/svn/trunk/src/html/tl_nt_header.html> ***/ function constructFilteredEventSource(baseEventSource, database, propertyID, matchValue) { return new Timeline.FilteredEventSource( baseEventSource, function(evt) { return database.getObject(evt.getID(), propertyID) == matchValue; } ); } function myTimelineConstructor(div, eventSource) { var theme = Timeline.ClassicTheme.create(); theme.ether.backgroundColors[2] = theme.ether.backgroundColors[0]; theme.ether.backgroundColors[3] = theme.ether.backgroundColors[1]; var d = Timeline.DateTime.parseGregorianDateTime("-0175") var bandInfos = [ Timeline.createBandInfo({ width: "20%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "a"), date: d, theme: theme }), Timeline.createBandInfo({ width: "30%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "b"), date: d, theme: theme }), Timeline.createBandInfo({ width: "30%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "c"), date: d, theme: theme }), Timeline.createBandInfo({ width: "20%", overview: true, intervalUnit: Timeline.DateTime.MILLENNIUM, intervalPixels: 200, eventSource: eventSource, date: d, theme: theme }) ]; bandInfos[1].syncWith = 0; bandInfos[2].syncWith = 0; bandInfos[3].syncWith = 1; bandInfos[3].highlight = true; div.style.height = "600px"; div.style.fontSize = "16px"; return Timeline.create(div, bandInfos, Timeline.HORIZONTAL); }
JavaScript
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAATTj_4YkZuaihAx0kvqq_3RT5TQ_3V3oDWogljA9hi5DEPPK3KBSMksPojdd95A7CAZ1r7YjmZTs36g" type="text/javascript"></script> <script type="text/javascript" src="http://timemap.googlecode.com/svn/tags/2.0/lib/jquery-1.4.4.min.js"></script> <script type="text/javascript" src="http://timemap.googlecode.com/svn/tags/2.0/lib/mxn/mxn.js?(google)"></script> <script type="text/javascript" src="http://timemap.googlecode.com/svn/tags/2.0/lib/timeline-1.2.js"></script> <script src="http://timemap.googlecode.com/svn/tags/2.0/src/timemap.js" type="text/javascript"></script> <script src="http://timemap.googlecode.com/svn/tags/2.0/src/param.js" type="text/javascript"></script> <script src="http://timemap.googlecode.com/svn/tags/2.0/src/loaders/json.js" type="text/javascript"></script> <script src="http://timemap.googlecode.com/svn/tags/2.0/src/loaders/google_spreadsheet.js" type="text/javascript"></script> <script type="text/javascript"> var tm; $(function() { tm = TimeMap.init({ mapId: "map", // Id of map div element (required) timelineId: "timeline", // Id of timeline div element (required) options: { eventIconPath: "http://timemap.googlecode.com/svn/tags/2.0/images/" }, datasets: [ { title: "Events", id: "events", theme: "purple", type: "gss", options: { // lon/lat->ll= key: "0Asy9DLkAdegIdGFmdW1oc1YyQzBPS3pONjFoQmpXWUE", // map spreadsheet column names to expected ids paramMap: { start: "start", end: "end" } } } ], bandIntervals: [ Timeline.DateTime.YEAR, Timeline.DateTime.DECADE ], scrollTo: "0044" }); }); </script> <link href="http://timemap.googlecode.com/svn/tags/2.0/examples/examples.css" type="text/css" rel="stylesheet"/> <style> div#timelinecontainer{ width: 100%; height: 40%; } div#timeline{ width: 100%; height: 100%; font-size: 12px; background: #CCCCCC; } div#mapcontainer { width: 100%; height: 60%; } #timemap { height: 650px; } div#map { width: 100%; height: 100%; background: #EEEEEE; } div.infodescription { font-style: normal; width: 300px; } </style>
JavaScript
<script type="text/javascript" src="http://static.simile.mit.edu/exhibit/api-2.0/exhibit-api.js"></script> <script type="text/javascript" src="http://static.simile.mit.edu/exhibit/extensions-2.0/time/time-extension.js"></script> <!--script type="text/javascript" src="http://people.csail.mit.edu/dfhuynh/projects/timeline-exhibit/filtered-sources.js"></script--> <link rel="exhibit/data" type="application/jsonp" href="https://spreadsheets.google.com/feeds/list/0Asy9DLkAdegIdElDU2pETlVCR0l0VFFTdFJXdEhkQVE/od6/public/basic?alt=json-in-script" ex:converter="googleSpreadsheets" /> <script> function constructFilteredEventSource(baseEventSource, database, propertyID, matchValue) { return new Timeline.FilteredEventSource( baseEventSource, function(evt) { return database.getObject(evt.getID(), propertyID) == matchValue; } ); } function myTimelineConstructor(div, eventSource) { var theme = Timeline.ClassicTheme.create(); theme.ether.backgroundColors[2] = theme.ether.backgroundColors[0]; theme.ether.backgroundColors[3] = theme.ether.backgroundColors[1]; var d = Timeline.DateTime.parseGregorianDateTime("-0175") var bandInfos = [ Timeline.createBandInfo({ width: "20%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "a"), date: d, theme: theme }), Timeline.createBandInfo({ width: "30%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "b"), date: d, theme: theme }), Timeline.createBandInfo({ width: "30%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "c"), date: d, theme: theme }), Timeline.createBandInfo({ width: "20%", overview: true, intervalUnit: Timeline.DateTime.MILLENNIUM, intervalPixels: 200, eventSource: eventSource, date: d, theme: theme }) ]; bandInfos[1].syncWith = 0; bandInfos[2].syncWith = 0; bandInfos[3].syncWith = 1; bandInfos[3].highlight = true; div.style.height = "600px"; div.style.fontSize = "16px"; return Timeline.create(div, bandInfos, Timeline.HORIZONTAL); } </script> <script> <!--http://people.csail.mit.edu/dfhuynh/projects/timeline-exhibit/filtered-sources.js--> Timeline.FilteredEventSource = function(baseEventSource, match) { this._baseEventSource = baseEventSource; this._match = match; this._events = new SimileAjax.EventIndex(); this._listeners = []; var self = this; this._eventListener = { onAddMany: function() { console.log("here"); self._onAddMany(); }, onClear: function() { self._onClear(); } } this._baseEventSource.addListener(this._eventListener); if (this._baseEventSource.getCount() > 0) { this._onAddMany(); } }; Timeline.FilteredEventSource.prototype.addListener = function(listener) { this._listeners.push(listener); }; Timeline.FilteredEventSource.prototype.removeListener = function(listener) { for (var i = 0; i < this._listeners.length; i++) { if (this._listeners[i] == listener) { this._listeners.splice(i, 1); break; } } }; Timeline.FilteredEventSource.prototype.getEvent = function(id) { return this._events.getEvent(id); }; Timeline.FilteredEventSource.prototype.getEventIterator = function(startDate, endDate) { return this._events.getIterator(startDate, endDate); }; Timeline.FilteredEventSource.prototype.getEventReverseIterator = function(startDate, endDate) { return this._events.getReverseIterator(startDate, endDate); }; Timeline.FilteredEventSource.prototype.getAllEventIterator = function() { return this._events.getAllIterator(); }; Timeline.FilteredEventSource.prototype.getCount = function() { return this._events.getCount(); }; Timeline.FilteredEventSource.prototype.getEarliestDate = function() { return this._events.getEarliestDate(); }; Timeline.FilteredEventSource.prototype.getLatestDate = function() { return this._events.getLatestDate(); }; Timeline.FilteredEventSource.prototype._fire = function(handlerName, args) { for (var i = 0; i < this._listeners.length; i++) { var listener = this._listeners[i]; if (handlerName in listener) { try { listener[handlerName].apply(listener, args); } catch (e) { SimileAjax.Debug.exception(e); } } } }; Timeline.FilteredEventSource.prototype._onAddMany = function() { this._events.removeAll(); var i = this._baseEventSource.getAllEventIterator(); while (i.hasNext()) { var evt = i.next(); if (this._match(evt)) { this._events.add(evt); } } this._fire("onAddMany", []); }; Timeline.FilteredEventSource.prototype._onClear = function() { this._events.removeAll(); this._fire("onClear", []); }; </script>
JavaScript
<script src="http://static.simile.mit.edu/exhibit/api-2.0/exhibit-api.js" type="text/javascript"></script> <script src="http://static.simile.mit.edu/exhibit/extensions-2.0/time/time-extension.js"></script> <link rel="exhibit/data" type="application/jsonp" href="https://spreadsheets.google.com/feeds/list/0Asy9DLkAdegIdHpQQmxxSFM5NjZaSVFEbks4bUlvcnc/od6/public/basic?alt=json-in-script" ex:converter="googleSpreadsheets" />
JavaScript
/*** The following is required in the html header section: <script type="text/javascript" src="http://static.simile.mit.edu/exhibit/api-2.0/exhibit-api.js"></script> <script type="text/javascript" src="http://static.simile.mit.edu/exhibit/extensions-2.0/time/time-extension.js"></script> <script type="text/javascript" src="<same url to this javascript>/filtered-sources.js"></script> <link rel="exhibit/data" type="application/jsonp" href="https://spreadsheets.google.com/feeds/list/0Asy9DLkAdegIdHpQQmxxSFM5NjZaSVFEbks4bUlvcnc/od6/public/basic?alt=json-in-script" ex:converter="googleSpreadsheets" /> ***/ function constructFilteredEventSource(baseEventSource, database, propertyID, matchValue) { return new Timeline.FilteredEventSource( baseEventSource, function(evt) { return database.getObject(evt.getID(), propertyID) == matchValue; } ); } function myTimelineConstructor(div, eventSource) { var theme = Timeline.ClassicTheme.create(); theme.ether.backgroundColors[2] = theme.ether.backgroundColors[0]; theme.ether.backgroundColors[3] = theme.ether.backgroundColors[1]; var d = Timeline.DateTime.parseGregorianDateTime("-0175") var bandInfos = [ Timeline.createBandInfo({ width: "20%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "a"), date: d, theme: theme }), Timeline.createBandInfo({ width: "30%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "b"), date: d, theme: theme }), Timeline.createBandInfo({ width: "30%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "c"), date: d, theme: theme }), Timeline.createBandInfo({ width: "20%", overview: true, intervalUnit: Timeline.DateTime.MILLENNIUM, intervalPixels: 200, eventSource: eventSource, date: d, theme: theme }) ]; bandInfos[1].syncWith = 0; bandInfos[2].syncWith = 0; bandInfos[3].syncWith = 1; bandInfos[3].highlight = true; div.style.height = "600px"; div.style.fontSize = "16px"; return Timeline.create(div, bandInfos, Timeline.HORIZONTAL); }
JavaScript
/*** <!--Add the following to html header section: --> <script type="text/javascript" src="http://static.simile.mit.edu/exhibit/api-2.0/exhibit-api.js"></script> <script type="text/javascript" src="http://static.simile.mit.edu/exhibit/extensions-2.0/time/time-extension.js"></script> <script type="text/javascript" src="<same url to this javascript>/filtered-sources.js"></script> <link rel="exhibit/data" type="application/jsonp" href="https://spreadsheets.google.com/feeds/list/0Asy9DLkAdegIdElDU2pETlVCR0l0VFFTdFJXdEhkQVE/od6/public/basic?alt=json-in-script" ex:converter="googleSpreadsheets" /> ***/ function constructFilteredEventSource(baseEventSource, database, propertyID, matchValue) { return new Timeline.FilteredEventSource( baseEventSource, function(evt) { return database.getObject(evt.getID(), propertyID) == matchValue; } ); } function myTimelineConstructor(div, eventSource) { var theme = Timeline.ClassicTheme.create(); theme.ether.backgroundColors[2] = theme.ether.backgroundColors[0]; theme.ether.backgroundColors[3] = theme.ether.backgroundColors[1]; var d = Timeline.DateTime.parseGregorianDateTime("-0175") var bandInfos = [ Timeline.createBandInfo({ width: "20%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "a"), date: d, theme: theme }), Timeline.createBandInfo({ width: "30%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "b"), date: d, theme: theme }), Timeline.createBandInfo({ width: "30%", intervalUnit: Timeline.DateTime.CENTURY, intervalPixels: 100, eventSource: constructFilteredEventSource(eventSource, window.database, "category", "c"), date: d, theme: theme }), Timeline.createBandInfo({ width: "20%", overview: true, intervalUnit: Timeline.DateTime.MILLENNIUM, intervalPixels: 200, eventSource: eventSource, date: d, theme: theme }) ]; bandInfos[1].syncWith = 0; bandInfos[2].syncWith = 0; bandInfos[3].syncWith = 1; bandInfos[3].highlight = true; div.style.height = "600px"; div.style.fontSize = "16px"; return Timeline.create(div, bandInfos, Timeline.HORIZONTAL); }
JavaScript
var _1006apparel = Utils.getAngularModule(_1006apparel); _1006apparel .controller('RouteController', function ($scope, $route, $routeParams, $location) { Utils.initGlobal($scope, $route, $routeParams, $location); $scope.$templateInited = []; $scope.$initTemplate = function (templateName) { if (!$scope.$templateInited.contains(templateName)) { $scope.$templateInited.push(templateName); } }; $scope.$scriptTagsInited = []; $scope.$scriptTagsInitedRaw = []; $scope.$initScriptTags = function (scriptTagsHtml) { if (!$scope.$scriptTagsInitedRaw.contains(scriptTagsHtml)) { $scope.$scriptTagsInited.push(new String(scriptTagsHtml)); $scope.$scriptTagsInitedRaw.push(scriptTagsHtml); } }; }) .config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) { var rootTemplateUrl = '/route'; $routeProvider.when('/menu', { templateUrl: rootTemplateUrl + '/menu' }); $routeProvider.when('/staff', { templateUrl: rootTemplateUrl + '/staff' }); $routeProvider.otherwise({ redirectTo: function () { //window.location = baseSiteUrl + "angular/page-not-found"; }, }); $locationProvider .html5Mode({ enabled: true, requireBase: false }) .hashPrefix(""); }]) .run(function ($rootScope, $templateCache) { $rootScope.$on('$viewContentLoaded', function () { $templateCache.removeAll(); }); $rootScope.$on("$routeChangeStart", function (event, next, current) { if (current && current.$$route && current.$$route.resolve) { // } }); $rootScope.$on('$routeChangeSuccess', function (event, next, current) { // }); });
JavaScript
var _1006apparel = Utils.getAngularModule(_1006apparel); _1006apparel .controller('StaffController', function ($scope, $route, $routeParams, $location) { Utils.initGlobal($scope, $route, $routeParams, $location); $scope.title = 'Staff'; });
JavaScript
var _1006apparel = Utils.getAngularModule(_1006apparel); _1006apparel .controller('MenuController', function ($scope, $route, $routeParams, $location) { Utils.initGlobal($scope, $route, $routeParams, $location); $scope.title = 'Menu'; });
JavaScript
var _1006apparel = Utils.getAngularModule(_1006apparel); _1006apparel .filter('to_trusted', ['$sce', function ($sce) { return function (text) { return $sce.trustAsHtml(text); }; }]) .filter('to_html', ['$sce', function ($sce) { return function (text) { return $sce.parseAsHtml(text); }; }]);
JavaScript
window.waitcount = 0; var Utils = { getAngularModule: function (_1006apparel) { return _1006apparel || angular.module("1006apparel", ['ngSanitize', 'ngRoute']); }, initGlobal: function ($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } };
JavaScript
var _1006apparel = Utils.getAngularModule(_1006apparel); _1006apparel .directive('dynamic', function ($compile) { return { restrict: 'A', link: function (scope, element, attrs) { scope.$watch(attrs.dynamic, function (html) { element.html(html); $compile(element.contents())(scope); }); } }; });
JavaScript
/* Uniform v2.1.2 Copyright © 2009 Josh Pyles / Pixelmatrix Design LLC http://pixelmatrixdesign.com Requires jQuery 1.3 or newer Much thanks to Thomas Reynolds and Buck Wilson for their help and advice on this. Disabling text selection is made possible by Mathias Bynens <http://mathiasbynens.be/> and his noSelect plugin. <https://github.com/mathiasbynens/jquery-noselect>, which is embedded. Also, thanks to David Kaneda and Eugene Bond for their contributions to the plugin. Tyler Akins has also rewritten chunks of the plugin, helped close many issues, and ensured version 2 got out the door. License: MIT License - http://www.opensource.org/licenses/mit-license.php Enjoy! */ /*global jQuery, document, navigator*/ (function (wind, $, undef) { "use strict"; /** * Use .prop() if jQuery supports it, otherwise fall back to .attr() * * @param jQuery $el jQuery'd element on which we're calling attr/prop * @param ... All other parameters are passed to jQuery's function * @return The result from jQuery */ function attrOrProp($el) { var args = Array.prototype.slice.call(arguments, 1); if ($el.prop) { // jQuery 1.6+ return $el.prop.apply($el, args); } // jQuery 1.5 and below return $el.attr.apply($el, args); } /** * For backwards compatibility with older jQuery libraries, only bind * one thing at a time. Also, this function adds our namespace to * events in one consistent location, shrinking the minified code. * * The properties on the events object are the names of the events * that we are supposed to add to. It can be a space separated list. * The namespace will be added automatically. * * @param jQuery $el * @param Object options Uniform options for this element * @param Object events Events to bind, properties are event names */ function bindMany($el, options, events) { var name, namespaced; for (name in events) { if (events.hasOwnProperty(name)) { namespaced = name.replace(/ |$/g, options.eventNamespace); $el.bind(namespaced, events[name]); } } } /** * Bind the hover, active, focus, and blur UI updates * * @param jQuery $el Original element * @param jQuery $target Target for the events (our div/span) * @param Object options Uniform options for the element $target */ function bindUi($el, $target, options) { bindMany($el, options, { focus: function () { $target.addClass(options.focusClass); }, blur: function () { $target.removeClass(options.focusClass); $target.removeClass(options.activeClass); }, mouseenter: function () { $target.addClass(options.hoverClass); }, mouseleave: function () { $target.removeClass(options.hoverClass); $target.removeClass(options.activeClass); }, "mousedown touchbegin": function () { if (!$el.is(":disabled")) { $target.addClass(options.activeClass); } }, "mouseup touchend": function () { $target.removeClass(options.activeClass); } }); } /** * Remove the hover, focus, active classes. * * @param jQuery $el Element with classes * @param Object options Uniform options for the element */ function classClearStandard($el, options) { $el.removeClass(options.hoverClass + " " + options.focusClass + " " + options.activeClass); } /** * Add or remove a class, depending on if it's "enabled" * * @param jQuery $el Element that has the class added/removed * @param String className Class or classes to add/remove * @param Boolean enabled True to add the class, false to remove */ function classUpdate($el, className, enabled) { if (enabled) { $el.addClass(className); } else { $el.removeClass(className); } } /** * Updating the "checked" property can be a little tricky. This * changed in jQuery 1.6 and now we can pass booleans to .prop(). * Prior to that, one either adds an attribute ("checked=checked") or * removes the attribute. * * @param jQuery $tag Our Uniform span/div * @param jQuery $el Original form element * @param Object options Uniform options for this element */ function classUpdateChecked($tag, $el, options) { var c = "checked", isChecked = $el.is(":" + c); if ($el.prop) { // jQuery 1.6+ $el.prop(c, isChecked); } else { // jQuery 1.5 and below if (isChecked) { $el.attr(c, c); } else { $el.removeAttr(c); } } classUpdate($tag, options.checkedClass, isChecked); } /** * Set or remove the "disabled" class for disabled elements, based on * if the element is detected to be disabled. * * @param jQuery $tag Our Uniform span/div * @param jQuery $el Original form element * @param Object options Uniform options for this element */ function classUpdateDisabled($tag, $el, options) { classUpdate($tag, options.disabledClass, $el.is(":disabled")); } /** * Wrap an element inside of a container or put the container next * to the element. See the code for examples of the different methods. * * Returns the container that was added to the HTML. * * @param jQuery $el Element to wrap * @param jQuery $container Add this new container around/near $el * @param String method One of "after", "before" or "wrap" * @return $container after it has been cloned for adding to $el */ function divSpanWrap($el, $container, method) { switch (method) { case "after": // Result: <element /> <container /> $el.after($container); return $el.next(); case "before": // Result: <container /> <element /> $el.before($container); return $el.prev(); case "wrap": // Result: <container> <element /> </container> $el.wrap($container); return $el.parent(); } return null; } /** * Create a div/span combo for uniforming an element * * @param jQuery $el Element to wrap * @param Object options Options for the element, set by the user * @param Object divSpanConfig Options for how we wrap the div/span * @return Object Contains the div and span as properties */ function divSpan($el, options, divSpanConfig) { var $div, $span, id; if (!divSpanConfig) { divSpanConfig = {}; } divSpanConfig = $.extend({ bind: {}, divClass: null, divWrap: "wrap", spanClass: null, spanHtml: null, spanWrap: "wrap" }, divSpanConfig); $div = $('<div />'); $span = $('<span />'); // Automatically hide this div/span if the element is hidden. // Do not hide if the element is hidden because a parent is hidden. if (options.autoHide && $el.is(':hidden') && $el.css('display') === 'none') { $div.hide(); } if (divSpanConfig.divClass) { $div.addClass(divSpanConfig.divClass); } if (options.wrapperClass) { $div.addClass(options.wrapperClass); } if (divSpanConfig.spanClass) { $span.addClass(divSpanConfig.spanClass); } id = attrOrProp($el, 'id'); if (options.useID && id) { attrOrProp($div, 'id', options.idPrefix + '-' + id); } if (divSpanConfig.spanHtml) { $span.html(divSpanConfig.spanHtml); } $div = divSpanWrap($el, $div, divSpanConfig.divWrap); $span = divSpanWrap($el, $span, divSpanConfig.spanWrap); classUpdateDisabled($div, $el, options); return { div: $div, span: $span }; } /** * Wrap an element with a span to apply a global wrapper class * * @param jQuery $el Element to wrap * @param object options * @return jQuery Wrapper element */ function wrapWithWrapperClass($el, options) { var $span; if (!options.wrapperClass) { return null; } $span = $('<span />').addClass(options.wrapperClass); $span = divSpanWrap($el, $span, "wrap"); return $span; } /** * Test if high contrast mode is enabled. * * In high contrast mode, background images can not be set and * they are always returned as 'none'. * * @return boolean True if in high contrast mode */ function highContrast() { var c, $div, el, rgb; // High contrast mode deals with white and black rgb = 'rgb(120,2,153)'; $div = $('<div style="width:0;height:0;color:' + rgb + '">'); $('body').append($div); el = $div.get(0); // $div.css() will get the style definition, not // the actually displaying style if (wind.getComputedStyle) { c = wind.getComputedStyle(el, '').color; } else { c = (el.currentStyle || el.style || {}).color; } $div.remove(); return c.replace(/ /g, '') !== rgb; } /** * Change text into safe HTML * * @param String text * @return String HTML version */ function htmlify(text) { if (!text) { return ""; } return $('<span />').text(text).html(); } /** * If not MSIE, return false. * If it is, return the version number. * * @return false|number */ function isMsie() { return navigator.cpuClass && !navigator.product; } /** * Return true if this version of IE allows styling * * @return boolean */ function isMsieSevenOrNewer() { if (wind.XMLHttpRequest !== undefined) { return true; } return false; } /** * Test if the element is a multiselect * * @param jQuery $el Element * @return boolean true/false */ function isMultiselect($el) { var elSize; if ($el[0].multiple) { return true; } elSize = attrOrProp($el, "size"); if (!elSize || elSize <= 1) { return false; } return true; } /** * Meaningless utility function. Used mostly for improving minification. * * @return false */ function returnFalse() { return false; } /** * noSelect plugin, very slightly modified * http://mths.be/noselect v1.0.3 * * @param jQuery $elem Element that we don't want to select * @param Object options Uniform options for the element */ function noSelect($elem, options) { var none = 'none'; bindMany($elem, options, { 'selectstart dragstart mousedown': returnFalse }); $elem.css({ MozUserSelect: none, msUserSelect: none, webkitUserSelect: none, userSelect: none }); } /** * Updates the filename tag based on the value of the real input * element. * * @param jQuery $el Actual form element * @param jQuery $filenameTag Span/div to update * @param Object options Uniform options for this element */ function setFilename($el, $filenameTag, options) { var filename = $el.val(); if (filename === "") { filename = options.fileDefaultHtml; } else { filename = filename.split(/[\/\\]+/); filename = filename[(filename.length - 1)]; } $filenameTag.text(filename); } /** * Function from jQuery to swap some CSS values, run a callback, * then restore the CSS. Modified to pass JSLint and handle undefined * values with 'use strict'. * * @param jQuery $el Element * @param object newCss CSS values to swap out * @param Function callback Function to run */ function swap($elements, newCss, callback) { var restore, item; restore = []; $elements.each(function () { var name; for (name in newCss) { if (Object.prototype.hasOwnProperty.call(newCss, name)) { restore.push({ el: this, name: name, old: this.style[name] }); this.style[name] = newCss[name]; } } }); callback(); while (restore.length) { item = restore.pop(); item.el.style[item.name] = item.old; } } /** * The browser doesn't provide sizes of elements that are not visible. * This will clone an element and add it to the DOM for calculations. * * @param jQuery $el * @param String method */ function sizingInvisible($el, callback) { var targets; // We wish to target ourselves and any parents as long as // they are not visible targets = $el.parents(); targets.push($el[0]); targets = targets.not(':visible'); swap(targets, { visibility: "hidden", display: "block", position: "absolute" }, callback); } /** * Standard way to unwrap the div/span combination from an element * * @param jQuery $el Element that we wish to preserve * @param Object options Uniform options for the element * @return Function This generated function will perform the given work */ function unwrapUnwrapUnbindFunction($el, options) { return function () { $el.unwrap().unwrap().unbind(options.eventNamespace); }; } var allowStyling = true, // False if IE6 or other unsupported browsers highContrastTest = false, // Was the high contrast test ran? uniformHandlers = [ // Objects that take care of "unification" { // Buttons match: function ($el) { return $el.is("a, button, :submit, :reset, input[type='button']"); }, apply: function ($el, options) { var $div, defaultSpanHtml, ds, getHtml, doingClickEvent; defaultSpanHtml = options.submitDefaultHtml; if ($el.is(":reset")) { defaultSpanHtml = options.resetDefaultHtml; } if ($el.is("a, button")) { // Use the HTML inside the tag getHtml = function () { return $el.html() || defaultSpanHtml; }; } else { // Use the value property of the element getHtml = function () { return htmlify(attrOrProp($el, "value")) || defaultSpanHtml; }; } ds = divSpan($el, options, { divClass: options.buttonClass, spanHtml: getHtml() }); $div = ds.div; bindUi($el, $div, options); doingClickEvent = false; bindMany($div, options, { "click touchend": function () { var ev, res, target, href; if (doingClickEvent) { return; } if ($el.is(':disabled')) { return; } doingClickEvent = true; if ($el[0].dispatchEvent) { ev = document.createEvent("MouseEvents"); ev.initEvent("click", true, true); res = $el[0].dispatchEvent(ev); if ($el.is('a') && res) { target = attrOrProp($el, 'target'); href = attrOrProp($el, 'href'); if (!target || target === '_self') { document.location.href = href; } else { wind.open(href, target); } } } else { $el.click(); } doingClickEvent = false; } }); noSelect($div, options); return { remove: function () { // Move $el out $div.after($el); // Remove div and span $div.remove(); // Unbind events $el.unbind(options.eventNamespace); return $el; }, update: function () { classClearStandard($div, options); classUpdateDisabled($div, $el, options); $el.detach(); ds.span.html(getHtml()).append($el); } }; } }, { // Checkboxes match: function ($el) { return $el.is(":checkbox"); }, apply: function ($el, options) { var ds, $div, $span; ds = divSpan($el, options, { divClass: options.checkboxClass }); $div = ds.div; $span = ds.span; // Add focus classes, toggling, active, etc. bindUi($el, $div, options); bindMany($el, options, { "click touchend": function () { classUpdateChecked($span, $el, options); } }); classUpdateChecked($span, $el, options); return { remove: unwrapUnwrapUnbindFunction($el, options), update: function () { classClearStandard($div, options); $span.removeClass(options.checkedClass); classUpdateChecked($span, $el, options); classUpdateDisabled($div, $el, options); } }; } }, { // File selection / uploads match: function ($el) { return $el.is(":file"); }, apply: function ($el, options) { var ds, $div, $filename, $button; // The "span" is the button ds = divSpan($el, options, { divClass: options.fileClass, spanClass: options.fileButtonClass, spanHtml: options.fileButtonHtml, spanWrap: "after" }); $div = ds.div; $button = ds.span; $filename = $("<span />").html(options.fileDefaultHtml); $filename.addClass(options.filenameClass); $filename = divSpanWrap($el, $filename, "after"); // Set the size if (!attrOrProp($el, "size")) { attrOrProp($el, "size", $div.width() / 10); } // Actions function filenameUpdate() { setFilename($el, $filename, options); } bindUi($el, $div, options); // Account for input saved across refreshes filenameUpdate(); // IE7 doesn't fire onChange until blur or second fire. if (isMsie()) { // IE considers browser chrome blocking I/O, so it // suspends tiemouts until after the file has // been selected. bindMany($el, options, { click: function () { $el.trigger("change"); setTimeout(filenameUpdate, 0); } }); } else { // All other browsers behave properly bindMany($el, options, { change: filenameUpdate }); } noSelect($filename, options); noSelect($button, options); return { remove: function () { // Remove filename and button $filename.remove(); $button.remove(); // Unwrap parent div, remove events return $el.unwrap().unbind(options.eventNamespace); }, update: function () { classClearStandard($div, options); setFilename($el, $filename, options); classUpdateDisabled($div, $el, options); } }; } }, { // Input fields (text) match: function ($el) { if ($el.is("input")) { var t = (" " + attrOrProp($el, "type") + " ").toLowerCase(), allowed = " color date datetime datetime-local email month number password search tel text time url week "; return allowed.indexOf(t) >= 0; } return false; }, apply: function ($el, options) { var elType, $wrapper; elType = attrOrProp($el, "type"); $el.addClass(options.inputClass); $wrapper = wrapWithWrapperClass($el, options); bindUi($el, $el, options); if (options.inputAddTypeAsClass) { $el.addClass(elType); } return { remove: function () { $el.removeClass(options.inputClass); if (options.inputAddTypeAsClass) { $el.removeClass(elType); } if ($wrapper) { $el.unwrap(); } }, update: returnFalse }; } }, { // Radio buttons match: function ($el) { return $el.is(":radio"); }, apply: function ($el, options) { var ds, $div, $span; ds = divSpan($el, options, { divClass: options.radioClass }); $div = ds.div; $span = ds.span; // Add classes for focus, handle active, checked bindUi($el, $div, options); bindMany($el, options, { "click touchend": function () { // Find all radios with the same name, then update // them with $.uniform.update() so the right // per-element options are used $.uniform.update($(':radio[name="' + attrOrProp($el, "name") + '"]')); } }); classUpdateChecked($span, $el, options); return { remove: unwrapUnwrapUnbindFunction($el, options), update: function () { classClearStandard($div, options); classUpdateChecked($span, $el, options); classUpdateDisabled($div, $el, options); } }; } }, { // Select lists, but do not style multiselects here match: function ($el) { if ($el.is("select") && !isMultiselect($el)) { return true; } return false; }, apply: function ($el, options) { var ds, $div, $span, origElemWidth; if (options.selectAutoWidth) { sizingInvisible($el, function () { origElemWidth = $el.width(); }); } ds = divSpan($el, options, { divClass: options.selectClass, spanHtml: ($el.find(":selected:first") || $el.find("option:first")).html(), spanWrap: "before" }); $div = ds.div; $span = ds.span; if (options.selectAutoWidth) { // Use the width of the select and adjust the // span and div accordingly sizingInvisible($el, function () { // Force "display: block" - related to bug #287 swap($([$span[0], $div[0]]), { display: "block" }, function () { var spanPad; spanPad = $span.outerWidth() - $span.width(); $div.width(origElemWidth + spanPad); $span.width(origElemWidth); }); }); } else { // Force the select to fill the size of the div $div.addClass('fixedWidth'); } // Take care of events bindUi($el, $div, options); bindMany($el, options, { change: function () { $span.html($el.find(":selected").html()); $div.removeClass(options.activeClass); }, "click touchend": function () { // IE7 and IE8 may not update the value right // until after click event - issue #238 var selHtml = $el.find(":selected").html(); if ($span.html() !== selHtml) { // Change was detected // Fire the change event on the select tag $el.trigger('change'); } }, keyup: function () { $span.html($el.find(":selected").html()); } }); noSelect($span, options); return { remove: function () { // Remove sibling span $span.remove(); // Unwrap parent div $el.unwrap().unbind(options.eventNamespace); return $el; }, update: function () { if (options.selectAutoWidth) { // Easier to remove and reapply formatting $.uniform.restore($el); $el.uniform(options); } else { classClearStandard($div, options); // Reset current selected text $span.html($el.find(":selected").html()); classUpdateDisabled($div, $el, options); } } }; } }, { // Select lists - multiselect lists only match: function ($el) { if ($el.is("select") && isMultiselect($el)) { return true; } return false; }, apply: function ($el, options) { var $wrapper; $el.addClass(options.selectMultiClass); $wrapper = wrapWithWrapperClass($el, options); bindUi($el, $el, options); return { remove: function () { $el.removeClass(options.selectMultiClass); if ($wrapper) { $el.unwrap(); } }, update: returnFalse }; } }, { // Textareas match: function ($el) { return $el.is("textarea"); }, apply: function ($el, options) { var $wrapper; $el.addClass(options.textareaClass); $wrapper = wrapWithWrapperClass($el, options); bindUi($el, $el, options); return { remove: function () { $el.removeClass(options.textareaClass); if ($wrapper) { $el.unwrap(); } }, update: returnFalse }; } } ]; // IE6 can't be styled - can't set opacity on select if (isMsie() && !isMsieSevenOrNewer()) { allowStyling = false; } $.uniform = { // Default options that can be overridden globally or when uniformed // globally: $.uniform.defaults.fileButtonHtml = "Pick A File"; // on uniform: $('input').uniform({fileButtonHtml: "Pick a File"}); defaults: { activeClass: "active", autoHide: true, buttonClass: "button", checkboxClass: "checker", checkedClass: "checked", disabledClass: "disabled", eventNamespace: ".uniform", fileButtonClass: "action", fileButtonHtml: "Choose File", fileClass: "uploader", fileDefaultHtml: "No file selected", filenameClass: "filename", focusClass: "focus", hoverClass: "hover", idPrefix: "uniform", inputAddTypeAsClass: true, inputClass: "uniform-input", radioClass: "radio", resetDefaultHtml: "Reset", resetSelector: false, // We'll use our own function when you don't specify one selectAutoWidth: true, selectClass: "selector", selectMultiClass: "uniform-multiselect", submitDefaultHtml: "Submit", // Only text allowed textareaClass: "uniform", useID: true, wrapperClass: null }, // All uniformed elements - DOM objects elements: [] }; $.fn.uniform = function (options) { var el = this; options = $.extend({}, $.uniform.defaults, options); // If we are in high contrast mode, do not allow styling if (!highContrastTest) { highContrastTest = true; if (highContrast()) { allowStyling = false; } } // Only uniform on browsers that work if (!allowStyling) { return this; } // Code for specifying a reset button if (options.resetSelector) { $(options.resetSelector).mouseup(function () { wind.setTimeout(function () { $.uniform.update(el); }, 10); }); } return this.each(function () { var $el = $(this), i, handler, callbacks; // Avoid uniforming elements already uniformed - just update if ($el.data("uniformed")) { $.uniform.update($el); return; } // See if we have any handler for this type of element for (i = 0; i < uniformHandlers.length; i = i + 1) { handler = uniformHandlers[i]; if (handler.match($el, options)) { callbacks = handler.apply($el, options); $el.data("uniformed", callbacks); // Store element in our global array $.uniform.elements.push($el.get(0)); return; } } // Could not style this element }); }; $.uniform.restore = $.fn.uniform.restore = function (elem) { if (elem === undef) { elem = $.uniform.elements; } $(elem).each(function () { var $el = $(this), index, elementData; elementData = $el.data("uniformed"); // Skip elements that are not uniformed if (!elementData) { return; } // Unbind events, remove additional markup that was added elementData.remove(); // Remove item from list of uniformed elements index = $.inArray(this, $.uniform.elements); if (index >= 0) { $.uniform.elements.splice(index, 1); } $el.removeData("uniformed"); }); }; $.uniform.update = $.fn.uniform.update = function (elem) { if (elem === undef) { elem = $.uniform.elements; } $(elem).each(function () { var $el = $(this), elementData; elementData = $el.data("uniformed"); // Skip elements that are not uniformed if (!elementData) { return; } elementData.update($el, elementData.options); }); }; }(this, jQuery));
JavaScript
/*! Copyright (c) 2011 Piotr Rochala (http://rocha.la) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * Version: 1.3.0 * */ (function($) { jQuery.fn.extend({ slimScroll: function(options) { var defaults = { // width in pixels of the visible scroll area width : 'auto', // height in pixels of the visible scroll area height : '250px', // width in pixels of the scrollbar and rail size : '7px', // scrollbar color, accepts any hex/color value color: '#000', // scrollbar position - left/right position : 'right', // distance in pixels between the side edge and the scrollbar distance : '1px', // default scroll position on load - top / bottom / $('selector') start : 'top', // sets scrollbar opacity opacity : .4, // enables always-on mode for the scrollbar alwaysVisible : false, // check if we should hide the scrollbar when user is hovering over disableFadeOut : false, // sets visibility of the rail railVisible : false, // sets rail color railColor : '#333', // sets rail opacity railOpacity : .2, // whether we should use jQuery UI Draggable to enable bar dragging railDraggable : true, // defautlt CSS class of the slimscroll rail railClass : 'slimScrollRail', // defautlt CSS class of the slimscroll bar barClass : 'slimScrollBar', // defautlt CSS class of the slimscroll wrapper wrapperClass : 'slimScrollDiv', // check if mousewheel should scroll the window if we reach top/bottom allowPageScroll : false, // scroll amount applied to each mouse wheel step wheelStep : 20, // scroll amount applied when user is using gestures touchScrollStep : 200, // sets border radius borderRadius: '7px', // sets border radius of the rail railBorderRadius : '7px' }; var o = $.extend(defaults, options); // do it for every element that matches selector this.each(function(){ var isOverPanel, isOverBar, isDragg, queueHide, touchDif, barHeight, percentScroll, lastScroll, divS = '<div></div>', minBarHeight = 30, releaseScroll = false; // used in event handlers and for better minification var me = $(this); // ensure we are not binding it again if (me.parent().hasClass(o.wrapperClass)) { // start from last bar position var offset = me.scrollTop(); // find bar and rail bar = me.parent().find('.' + o.barClass); rail = me.parent().find('.' + o.railClass); getBarHeight(); // check if we should scroll existing instance if ($.isPlainObject(options)) { // Pass height: auto to an existing slimscroll object to force a resize after contents have changed if ( 'height' in options && options.height == 'auto' ) { me.parent().css('height', 'auto'); me.css('height', 'auto'); var height = me.parent().parent().height(); me.parent().css('height', height); me.css('height', height); } if ('scrollTo' in options) { // jump to a static point offset = parseInt(o.scrollTo); } else if ('scrollBy' in options) { // jump by value pixels offset += parseInt(o.scrollBy); } else if ('destroy' in options) { // remove slimscroll elements bar.remove(); rail.remove(); me.unwrap(); return; } // scroll content by the given offset scrollContent(offset, false, true); } return; } // optionally set height to the parent's height o.height = (o.height == 'auto') ? me.parent().height() : o.height; // wrap content var wrapper = $(divS) .addClass(o.wrapperClass) .css({ position: 'relative', overflow: 'hidden', width: o.width, height: o.height }); // update style for the div me.css({ overflow: 'hidden', width: o.width, height: o.height }); // create scrollbar rail var rail = $(divS) .addClass(o.railClass) .css({ width: o.size, height: '100%', position: 'absolute', top: 0, display: (o.alwaysVisible && o.railVisible) ? 'block' : 'none', 'border-radius': o.railBorderRadius, background: o.railColor, opacity: o.railOpacity, zIndex: 90 }); // create scrollbar var bar = $(divS) .addClass(o.barClass) .css({ background: o.color, width: o.size, position: 'absolute', top: 0, opacity: o.opacity, display: o.alwaysVisible ? 'block' : 'none', 'border-radius' : o.borderRadius, BorderRadius: o.borderRadius, MozBorderRadius: o.borderRadius, WebkitBorderRadius: o.borderRadius, zIndex: 99 }); // set position var posCss = (o.position == 'right') ? { right: o.distance } : { left: o.distance }; rail.css(posCss); bar.css(posCss); // wrap it me.wrap(wrapper); // append to parent div me.parent().append(bar); me.parent().append(rail); // make it draggable and no longer dependent on the jqueryUI if (o.railDraggable){ bar.bind("mousedown", function(e) { var $doc = $(document); isDragg = true; t = parseFloat(bar.css('top')); pageY = e.pageY; $doc.bind("mousemove.slimscroll", function(e){ currTop = t + e.pageY - pageY; bar.css('top', currTop); scrollContent(0, bar.position().top, false);// scroll content }); $doc.bind("mouseup.slimscroll", function(e) { isDragg = false;hideBar(); $doc.unbind('.slimscroll'); }); return false; }).bind("selectstart.slimscroll", function(e){ e.stopPropagation(); e.preventDefault(); return false; }); } // on rail over rail.hover(function(){ showBar(); }, function(){ hideBar(); }); // on bar over bar.hover(function(){ isOverBar = true; }, function(){ isOverBar = false; }); // show on parent mouseover me.hover(function(){ isOverPanel = true; showBar(); hideBar(); }, function(){ isOverPanel = false; hideBar(); }); // support for mobile me.bind('touchstart', function(e,b){ if (e.originalEvent.touches.length) { // record where touch started touchDif = e.originalEvent.touches[0].pageY; } }); me.bind('touchmove', function(e){ // prevent scrolling the page if necessary if(!releaseScroll) { e.originalEvent.preventDefault(); } if (e.originalEvent.touches.length) { // see how far user swiped var diff = (touchDif - e.originalEvent.touches[0].pageY) / o.touchScrollStep; // scroll content scrollContent(diff, true); touchDif = e.originalEvent.touches[0].pageY; } }); // set up initial height getBarHeight(); // check start position if (o.start === 'bottom') { // scroll content to bottom bar.css({ top: me.outerHeight() - bar.outerHeight() }); scrollContent(0, true); } else if (o.start !== 'top') { // assume jQuery selector scrollContent($(o.start).position().top, null, true); // make sure bar stays hidden if (!o.alwaysVisible) { bar.hide(); } } // attach scroll events attachWheel(); function _onWheel(e) { // use mouse wheel only when mouse is over if (!isOverPanel) { return; } var e = e || window.event; var delta = 0; if (e.wheelDelta) { delta = -e.wheelDelta/120; } if (e.detail) { delta = e.detail / 3; } var target = e.target || e.srcTarget || e.srcElement; if ($(target).closest('.' + o.wrapperClass).is(me.parent())) { // scroll content scrollContent(delta, true); } // stop window scroll if (e.preventDefault && !releaseScroll) { e.preventDefault(); } if (!releaseScroll) { e.returnValue = false; } } function scrollContent(y, isWheel, isJump) { releaseScroll = false; var delta = y; var maxTop = me.outerHeight() - bar.outerHeight(); if (isWheel) { // move bar with mouse wheel delta = parseInt(bar.css('top')) + y * parseInt(o.wheelStep) / 100 * bar.outerHeight(); // move bar, make sure it doesn't go out delta = Math.min(Math.max(delta, 0), maxTop); // if scrolling down, make sure a fractional change to the // scroll position isn't rounded away when the scrollbar's CSS is set // this flooring of delta would happened automatically when // bar.css is set below, but we floor here for clarity delta = (y > 0) ? Math.ceil(delta) : Math.floor(delta); // scroll the scrollbar bar.css({ top: delta + 'px' }); } // calculate actual scroll amount percentScroll = parseInt(bar.css('top')) / (me.outerHeight() - bar.outerHeight()); delta = percentScroll * (me[0].scrollHeight - me.outerHeight()); if (isJump) { delta = y; var offsetTop = delta / me[0].scrollHeight * me.outerHeight(); offsetTop = Math.min(Math.max(offsetTop, 0), maxTop); bar.css({ top: offsetTop + 'px' }); } // scroll content me.scrollTop(delta); // fire scrolling event me.trigger('slimscrolling', ~~delta); // ensure bar is visible showBar(); // trigger hide when scroll is stopped hideBar(); } function attachWheel() { if (window.addEventListener) { this.addEventListener('DOMMouseScroll', _onWheel, false ); this.addEventListener('mousewheel', _onWheel, false ); this.addEventListener('MozMousePixelScroll', _onWheel, false ); } else { document.attachEvent("onmousewheel", _onWheel) } } function getBarHeight() { // calculate scrollbar height and make sure it is not too small barHeight = Math.max((me.outerHeight() / me[0].scrollHeight) * me.outerHeight(), minBarHeight); bar.css({ height: barHeight + 'px' }); // hide scrollbar if content is not long enough var display = barHeight == me.outerHeight() ? 'none' : 'block'; bar.css({ display: display }); } function showBar() { // recalculate bar height getBarHeight(); clearTimeout(queueHide); // when bar reached top or bottom if (percentScroll == ~~percentScroll) { //release wheel releaseScroll = o.allowPageScroll; // publish approporiate event if (lastScroll != percentScroll) { var msg = (~~percentScroll == 0) ? 'top' : 'bottom'; me.trigger('slimscroll', msg); } } else { releaseScroll = false; } lastScroll = percentScroll; // show only when required if(barHeight >= me.outerHeight()) { //allow window scroll releaseScroll = true; return; } bar.stop(true,true).fadeIn('fast'); if (o.railVisible) { rail.stop(true,true).fadeIn('fast'); } } function hideBar() { // only hide when options allow it if (!o.alwaysVisible) { queueHide = setTimeout(function(){ if (!(o.disableFadeOut && isOverPanel) && !isOverBar && !isDragg) { bar.fadeOut('slow'); rail.fadeOut('slow'); } }, 1000); } } }); // maintain chainability return this; } }); jQuery.fn.extend({ slimscroll: jQuery.fn.slimScroll }); })(jQuery);
JavaScript
/*! * jQuery Migrate - v1.2.1 - 2013-05-08 * https://github.com/jquery/jquery-migrate * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; Licensed MIT */ (function( jQuery, window, undefined ) { // See http://bugs.jquery.com/ticket/13335 // "use strict"; var warnedAbout = {}; // List of warnings already given; public read only jQuery.migrateWarnings = []; // Set to true to prevent console output; migrateWarnings still maintained // jQuery.migrateMute = false; // Show a message on the console so devs know we're active if ( !jQuery.migrateMute && window.console && window.console.log ) { window.console.log("JQMIGRATE: Logging is active"); } // Set to false to disable traces that appear with warnings if ( jQuery.migrateTrace === undefined ) { jQuery.migrateTrace = true; } // Forget any warnings we've already given; public jQuery.migrateReset = function() { warnedAbout = {}; jQuery.migrateWarnings.length = 0; }; function migrateWarn( msg) { var console = window.console; if ( !warnedAbout[ msg ] ) { warnedAbout[ msg ] = true; jQuery.migrateWarnings.push( msg ); if ( console && console.warn && !jQuery.migrateMute ) { console.warn( "JQMIGRATE: " + msg ); if ( jQuery.migrateTrace && console.trace ) { console.trace(); } } } } function migrateWarnProp( obj, prop, value, msg ) { if ( Object.defineProperty ) { // On ES5 browsers (non-oldIE), warn if the code tries to get prop; // allow property to be overwritten in case some other plugin wants it try { Object.defineProperty( obj, prop, { configurable: true, enumerable: true, get: function() { migrateWarn( msg ); return value; }, set: function( newValue ) { migrateWarn( msg ); value = newValue; } }); return; } catch( err ) { // IE8 is a dope about Object.defineProperty, can't warn there } } // Non-ES5 (or broken) browser; just set the property jQuery._definePropertyBroken = true; obj[ prop ] = value; } if ( document.compatMode === "BackCompat" ) { // jQuery has never supported or tested Quirks Mode migrateWarn( "jQuery is not compatible with Quirks Mode" ); } var attrFn = jQuery( "<input/>", { size: 1 } ).attr("size") && jQuery.attrFn, oldAttr = jQuery.attr, valueAttrGet = jQuery.attrHooks.value && jQuery.attrHooks.value.get || function() { return null; }, valueAttrSet = jQuery.attrHooks.value && jQuery.attrHooks.value.set || function() { return undefined; }, rnoType = /^(?:input|button)$/i, rnoAttrNodeType = /^[238]$/, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, ruseDefault = /^(?:checked|selected)$/i; // jQuery.attrFn migrateWarnProp( jQuery, "attrFn", attrFn || {}, "jQuery.attrFn is deprecated" ); jQuery.attr = function( elem, name, value, pass ) { var lowerName = name.toLowerCase(), nType = elem && elem.nodeType; if ( pass ) { // Since pass is used internally, we only warn for new jQuery // versions where there isn't a pass arg in the formal params if ( oldAttr.length < 4 ) { migrateWarn("jQuery.fn.attr( props, pass ) is deprecated"); } if ( elem && !rnoAttrNodeType.test( nType ) && (attrFn ? name in attrFn : jQuery.isFunction(jQuery.fn[name])) ) { return jQuery( elem )[ name ]( value ); } } // Warn if user tries to set `type`, since it breaks on IE 6/7/8; by checking // for disconnected elements we don't warn on $( "<button>", { type: "button" } ). if ( name === "type" && value !== undefined && rnoType.test( elem.nodeName ) && elem.parentNode ) { migrateWarn("Can't change the 'type' of an input or button in IE 6/7/8"); } // Restore boolHook for boolean property/attribute synchronization if ( !jQuery.attrHooks[ lowerName ] && rboolean.test( lowerName ) ) { jQuery.attrHooks[ lowerName ] = { get: function( elem, name ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // Warn only for attributes that can remain distinct from their properties post-1.9 if ( ruseDefault.test( lowerName ) ) { migrateWarn( "jQuery.fn.attr('" + lowerName + "') may use property instead of attribute" ); } } return oldAttr.call( jQuery, elem, name, value ); }; // attrHooks: value jQuery.attrHooks.value = { get: function( elem, name ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "button" ) { return valueAttrGet.apply( this, arguments ); } if ( nodeName !== "input" && nodeName !== "option" ) { migrateWarn("jQuery.fn.attr('value') no longer gets properties"); } return name in elem ? elem.value : null; }, set: function( elem, value ) { var nodeName = ( elem.nodeName || "" ).toLowerCase(); if ( nodeName === "button" ) { return valueAttrSet.apply( this, arguments ); } if ( nodeName !== "input" && nodeName !== "option" ) { migrateWarn("jQuery.fn.attr('value', val) no longer sets properties"); } // Does not return so that setAttribute is also used elem.value = value; } }; var matched, browser, oldInit = jQuery.fn.init, oldParseJSON = jQuery.parseJSON, // Note: XSS check is done below after string is trimmed rquickExpr = /^([^<]*)(<[\w\W]+>)([^>]*)$/; // $(html) "looks like html" rule change jQuery.fn.init = function( selector, context, rootjQuery ) { var match; if ( selector && typeof selector === "string" && !jQuery.isPlainObject( context ) && (match = rquickExpr.exec( jQuery.trim( selector ) )) && match[ 0 ] ) { // This is an HTML string according to the "old" rules; is it still? if ( selector.charAt( 0 ) !== "<" ) { migrateWarn("$(html) HTML strings must start with '<' character"); } if ( match[ 3 ] ) { migrateWarn("$(html) HTML text after last tag is ignored"); } // Consistently reject any HTML-like string starting with a hash (#9521) // Note that this may break jQuery 1.6.x code that otherwise would work. if ( match[ 0 ].charAt( 0 ) === "#" ) { migrateWarn("HTML string cannot start with a '#' character"); jQuery.error("JQMIGRATE: Invalid selector string (XSS)"); } // Now process using loose rules; let pre-1.8 play too if ( context && context.context ) { // jQuery object as context; parseHTML expects a DOM object context = context.context; } if ( jQuery.parseHTML ) { return oldInit.call( this, jQuery.parseHTML( match[ 2 ], context, true ), context, rootjQuery ); } } return oldInit.apply( this, arguments ); }; jQuery.fn.init.prototype = jQuery.fn; // Let $.parseJSON(falsy_value) return null jQuery.parseJSON = function( json ) { if ( !json && json !== null ) { migrateWarn("jQuery.parseJSON requires a valid JSON string"); return null; } return oldParseJSON.apply( this, arguments ); }; jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; // Don't clobber any existing jQuery.browser in case it's different if ( !jQuery.browser ) { matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; } // Warn if the code tries to get jQuery.browser migrateWarnProp( jQuery, "browser", jQuery.browser, "jQuery.browser is deprecated" ); jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); migrateWarn( "jQuery.sub() is deprecated" ); return jQuerySub; }; // Ensure that $.ajax gets the new parseJSON defined in core.js jQuery.ajaxSetup({ converters: { "text json": jQuery.parseJSON } }); var oldFnData = jQuery.fn.data; jQuery.fn.data = function( name ) { var ret, evt, elem = this[0]; // Handles 1.7 which has this behavior and 1.8 which doesn't if ( elem && name === "events" && arguments.length === 1 ) { ret = jQuery.data( elem, name ); evt = jQuery._data( elem, name ); if ( ( ret === undefined || ret === evt ) && evt !== undefined ) { migrateWarn("Use of jQuery.fn.data('events') is deprecated"); return evt; } } return oldFnData.apply( this, arguments ); }; var rscriptType = /\/(java|ecma)script/i, oldSelf = jQuery.fn.andSelf || jQuery.fn.addBack; jQuery.fn.andSelf = function() { migrateWarn("jQuery.fn.andSelf() replaced by jQuery.fn.addBack()"); return oldSelf.apply( this, arguments ); }; // Since jQuery.clean is used internally on older versions, we only shim if it's missing if ( !jQuery.clean ) { jQuery.clean = function( elems, context, fragment, scripts ) { // Set context per 1.8 logic context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; migrateWarn("jQuery.clean() is deprecated"); var i, elem, handleScript, jsTags, ret = []; jQuery.merge( ret, jQuery.buildFragment( elems, context ).childNodes ); // Complex logic lifted directly from jQuery 1.8 if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }; } var eventAdd = jQuery.event.add, eventRemove = jQuery.event.remove, eventTrigger = jQuery.event.trigger, oldToggle = jQuery.fn.toggle, oldLive = jQuery.fn.live, oldDie = jQuery.fn.die, ajaxEvents = "ajaxStart|ajaxStop|ajaxSend|ajaxComplete|ajaxError|ajaxSuccess", rajaxEvent = new RegExp( "\\b(?:" + ajaxEvents + ")\\b" ), rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, hoverHack = function( events ) { if ( typeof( events ) !== "string" || jQuery.event.special.hover ) { return events; } if ( rhoverHack.test( events ) ) { migrateWarn("'hover' pseudo-event is deprecated, use 'mouseenter mouseleave'"); } return events && events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; // Event props removed in 1.9, put them back if needed; no practical way to warn them if ( jQuery.event.props && jQuery.event.props[ 0 ] !== "attrChange" ) { jQuery.event.props.unshift( "attrChange", "attrName", "relatedNode", "srcElement" ); } // Undocumented jQuery.event.handle was "deprecated" in jQuery 1.7 if ( jQuery.event.dispatch ) { migrateWarnProp( jQuery.event, "handle", jQuery.event.dispatch, "jQuery.event.handle is undocumented and deprecated" ); } // Support for 'hover' pseudo-event and ajax event warnings jQuery.event.add = function( elem, types, handler, data, selector ){ if ( elem !== document && rajaxEvent.test( types ) ) { migrateWarn( "AJAX events should be attached to document: " + types ); } eventAdd.call( this, elem, hoverHack( types || "" ), handler, data, selector ); }; jQuery.event.remove = function( elem, types, handler, selector, mappedTypes ){ eventRemove.call( this, elem, hoverHack( types ) || "", handler, selector, mappedTypes ); }; jQuery.fn.error = function() { var args = Array.prototype.slice.call( arguments, 0); migrateWarn("jQuery.fn.error() is deprecated"); args.splice( 0, 0, "error" ); if ( arguments.length ) { return this.bind.apply( this, args ); } // error event should not bubble to window, although it does pre-1.7 this.triggerHandler.apply( this, args ); return this; }; jQuery.fn.toggle = function( fn, fn2 ) { // Don't mess with animation or css toggles if ( !jQuery.isFunction( fn ) || !jQuery.isFunction( fn2 ) ) { return oldToggle.apply( this, arguments ); } migrateWarn("jQuery.fn.toggle(handler, handler...) is deprecated"); // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }; jQuery.fn.live = function( types, data, fn ) { migrateWarn("jQuery.fn.live() is deprecated"); if ( oldLive ) { return oldLive.apply( this, arguments ); } jQuery( this.context ).on( types, this.selector, data, fn ); return this; }; jQuery.fn.die = function( types, fn ) { migrateWarn("jQuery.fn.die() is deprecated"); if ( oldDie ) { return oldDie.apply( this, arguments ); } jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }; // Turn global events into document-triggered events jQuery.event.trigger = function( event, data, elem, onlyHandlers ){ if ( !elem && !rajaxEvent.test( event ) ) { migrateWarn( "Global events are undocumented and deprecated" ); } return eventTrigger.call( this, event, data, elem || document, onlyHandlers ); }; jQuery.each( ajaxEvents.split("|"), function( _, name ) { jQuery.event.special[ name ] = { setup: function() { var elem = this; // The document needs no shimming; must be !== for oldIE if ( elem !== document ) { jQuery.event.add( document, name + "." + jQuery.guid, function() { jQuery.event.trigger( name, null, elem, true ); }); jQuery._data( this, name, jQuery.guid++ ); } return false; }, teardown: function() { if ( this !== document ) { jQuery.event.remove( document, name + "." + jQuery._data( this, name ) ); } return false; } }; } ); })( jQuery, window );
JavaScript
/*! * jQuery Cookie Plugin v1.4.1 * https://github.com/carhartl/jquery-cookie * * Copyright 2013 Klaus Hartl * Released under the MIT license */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD define(['jquery'], factory); } else if (typeof exports === 'object') { // CommonJS factory(require('jquery')); } else { // Browser globals factory(jQuery); } }(function ($) { var pluses = /\+/g; function encode(s) { return config.raw ? s : encodeURIComponent(s); } function decode(s) { return config.raw ? s : decodeURIComponent(s); } function stringifyCookieValue(value) { return encode(config.json ? JSON.stringify(value) : String(value)); } function parseCookieValue(s) { if (s.indexOf('"') === 0) { // This is a quoted cookie as according to RFC2068, unescape... s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } try { // Replace server-side written pluses with spaces. // If we can't decode the cookie, ignore it, it's unusable. // If we can't parse the cookie, ignore it, it's unusable. s = decodeURIComponent(s.replace(pluses, ' ')); return config.json ? JSON.parse(s) : s; } catch(e) {} } function read(s, converter) { var value = config.raw ? s : parseCookieValue(s); return $.isFunction(converter) ? converter(value) : value; } var config = $.cookie = function (key, value, options) { // Write if (value !== undefined && !$.isFunction(value)) { options = $.extend({}, config.defaults, options); if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setTime(+t + days * 864e+5); } return (document.cookie = [ encode(key), '=', stringifyCookieValue(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // Read var result = key ? undefined : {}; // To prevent the for loop in the first place assign an empty array // in case there are no cookies at all. Also prevents odd result when // calling $.cookie(). var cookies = document.cookie ? document.cookie.split('; ') : []; for (var i = 0, l = cookies.length; i < l; i++) { var parts = cookies[i].split('='); var name = decode(parts.shift()); var cookie = parts.join('='); if (key && key === name) { // If second argument (value) is a function it's a converter... result = read(cookie, value); break; } // Prevent storing a cookie that we couldn't decode. if (!key && (cookie = read(cookie)) !== undefined) { result[name] = cookie; } } return result; }; config.defaults = {}; $.removeCookie = function (key, options) { if ($.cookie(key) === undefined) { return false; } // Must not alter options, thus extending a fresh object... $.cookie(key, '', $.extend({}, options, { expires: -1 })); return !$.cookie(key); }; }));
JavaScript
/*! * jQuery blockUI plugin * Version 2.70.0-2014.11.23 * Requires jQuery v1.7 or later * * Examples at: http://malsup.com/jquery/block/ * Copyright (c) 2007-2013 M. Alsup * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Thanks to Amir-Hossein Sobhi for some excellent contributions! */ ; (function () { /*jshint eqeqeq:false curly:false latedef:false */ "use strict"; function setup($) { $.fn._fadeIn = $.fn.fadeIn; var noOp = $.noop || function () { }; // this bit is to ensure we don't call setExpression when we shouldn't (with extra muscle to handle // confusing userAgent strings on Vista) var msie = /MSIE/.test(navigator.userAgent); var ie6 = /MSIE 6.0/.test(navigator.userAgent) && ! /MSIE 8.0/.test(navigator.userAgent); var mode = document.documentMode || 0; var setExpr = $.isFunction(document.createElement('div').style.setExpression); // global $ methods for blocking/unblocking the entire page $.blockUI = function (opts) { install(window, opts); }; $.unblockUI = function (opts) { remove(window, opts); }; // convenience method for quick growl-like notifications (http://www.google.com/search?q=growl) $.growlUI = function (title, message, timeout, onClose) { var $m = $('<div class="growlUI"></div>'); if (title) $m.append('<h1>' + title + '</h1>'); if (message) $m.append('<h2>' + message + '</h2>'); if (timeout === undefined) timeout = 3000; // Added by konapun: Set timeout to 30 seconds if this growl is moused over, like normal toast notifications var callBlock = function (opts) { opts = opts || {}; $.blockUI({ message: $m, fadeIn: typeof opts.fadeIn !== 'undefined' ? opts.fadeIn : 700, fadeOut: typeof opts.fadeOut !== 'undefined' ? opts.fadeOut : 1000, timeout: typeof opts.timeout !== 'undefined' ? opts.timeout : timeout, centerY: false, showOverlay: false, onUnblock: onClose, css: $.blockUI.defaults.growlCSS }); }; callBlock(); var nonmousedOpacity = $m.css('opacity'); $m.mouseover(function () { callBlock({ fadeIn: 0, timeout: 30000 }); var displayBlock = $('.blockMsg'); displayBlock.stop(); // cancel fadeout if it has started displayBlock.fadeTo(300, 1); // make it easier to read the message by removing transparency }).mouseout(function () { $('.blockMsg').fadeOut(1000); }); // End konapun additions }; // plugin method for blocking element content $.fn.block = function (opts) { if (this[0] === window) { $.blockUI(opts); return this; } var fullOpts = $.extend({}, $.blockUI.defaults, opts || {}); this.each(function () { var $el = $(this); if (fullOpts.ignoreIfBlocked && $el.data('blockUI.isBlocked')) return; $el.unblock({ fadeOut: 0 }); }); return this.each(function () { if ($.css(this, 'position') == 'static') { this.style.position = 'relative'; $(this).data('blockUI.static', true); } this.style.zoom = 1; // force 'hasLayout' in ie install(this, opts); }); }; // plugin method for unblocking element content $.fn.unblock = function (opts) { if (this[0] === window) { $.unblockUI(opts); return this; } return this.each(function () { remove(this, opts); }); }; $.blockUI.version = 2.70; // 2nd generation blocking at no extra cost! // override these in your code to change the default behavior and style $.blockUI.defaults = { // message displayed when blocking (use null for no message) message: '<h1>Please wait...</h1>', title: null, // title string; only used when theme == true draggable: true, // only used when theme == true (requires jquery-ui.js to be loaded) theme: false, // set to true to use with jQuery UI themes // styles for the message when blocking; if you wish to disable // these and use an external stylesheet then do this in your code: // $.blockUI.defaults.css = {}; css: { padding: 0, margin: 0, width: '30%', top: '40%', left: '35%', textAlign: 'center', color: '#000', border: '3px solid #aaa', backgroundColor: '#fff', cursor: 'wait' }, // minimal style set used when themes are used themedCSS: { width: '30%', top: '40%', left: '35%' }, // styles for the overlay overlayCSS: { backgroundColor: '#000', opacity: 0.6, cursor: 'wait' }, // style to replace wait cursor before unblocking to correct issue // of lingering wait cursor cursorReset: 'default', // styles applied when using $.growlUI growlCSS: { width: '350px', top: '10px', left: '', right: '10px', border: 'none', padding: '5px', opacity: 0.6, cursor: 'default', color: '#fff', backgroundColor: '#000', '-webkit-border-radius': '10px', '-moz-border-radius': '10px', 'border-radius': '10px' }, // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w // (hat tip to Jorge H. N. de Vasconcelos) /*jshint scripturl:true */ iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', // force usage of iframe in non-IE browsers (handy for blocking applets) forceIframe: false, // z-index for the blocking overlay baseZ: 1000, // set these to true to have the message automatically centered centerX: true, // <-- only effects element blocking (page block controlled via css above) centerY: true, // allow body element to be stetched in ie6; this makes blocking look better // on "short" pages. disable if you wish to prevent changes to the body height allowBodyStretch: true, // enable if you want key and mouse events to be disabled for content that is blocked bindEvents: true, // be default blockUI will supress tab navigation from leaving blocking content // (if bindEvents is true) constrainTabKey: true, // fadeIn time in millis; set to 0 to disable fadeIn on block fadeIn: 200, // fadeOut time in millis; set to 0 to disable fadeOut on unblock fadeOut: 400, // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock timeout: 0, // disable if you don't want to show the overlay showOverlay: true, // if true, focus will be placed in the first available input field when // page blocking focusInput: true, // elements that can receive focus focusableElements: ':input:enabled:visible', // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity) // no longer needed in 2012 // applyPlatformOpacityRules: true, // callback method invoked when fadeIn has completed and blocking message is visible onBlock: null, // callback method invoked when unblocking has completed; the callback is // passed the element that has been unblocked (which is the window object for page // blocks) and the options that were passed to the unblock call: // onUnblock(element, options) onUnblock: null, // callback method invoked when the overlay area is clicked. // setting this will turn the cursor to a pointer, otherwise cursor defined in overlayCss will be used. onOverlayClick: null, // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 quirksmodeOffsetHack: 4, // class name of the message block blockMsgClass: 'blockMsg', // if it is already blocked, then ignore it (don't unblock and reblock) ignoreIfBlocked: false }; // private data and functions follow... var pageBlock = null; var pageBlockEls = []; function install(el, opts) { var css, themedCSS; var full = (el == window); var msg = (opts && opts.message !== undefined ? opts.message : undefined); opts = $.extend({}, $.blockUI.defaults, opts || {}); if (opts.ignoreIfBlocked && $(el).data('blockUI.isBlocked')) return; opts.overlayCSS = $.extend({}, $.blockUI.defaults.overlayCSS, opts.overlayCSS || {}); css = $.extend({}, $.blockUI.defaults.css, opts.css || {}); if (opts.onOverlayClick) opts.overlayCSS.cursor = 'pointer'; themedCSS = $.extend({}, $.blockUI.defaults.themedCSS, opts.themedCSS || {}); msg = msg === undefined ? opts.message : msg; // remove the current block (if there is one) if (full && pageBlock) remove(window, { fadeOut: 0 }); // if an existing element is being used as the blocking content then we capture // its current place in the DOM (and current display style) so we can restore // it when we unblock if (msg && typeof msg != 'string' && (msg.parentNode || msg.jquery)) { var node = msg.jquery ? msg[0] : msg; var data = {}; $(el).data('blockUI.history', data); data.el = node; data.parent = node.parentNode; data.display = node.style.display; data.position = node.style.position; if (data.parent) data.parent.removeChild(node); } $(el).data('blockUI.onUnblock', opts.onUnblock); var z = opts.baseZ; // blockUI uses 3 layers for blocking, for simplicity they are all used on every platform; // layer1 is the iframe layer which is used to supress bleed through of underlying content // layer2 is the overlay layer which has opacity and a wait cursor (by default) // layer3 is the message content that is displayed while blocking var lyr1, lyr2, lyr3, s; if (msie || opts.forceIframe) lyr1 = $('<iframe class="blockUI" style="z-index:' + (z++) + ';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="' + opts.iframeSrc + '"></iframe>'); else lyr1 = $('<div class="blockUI" style="display:none"></div>'); if (opts.theme) lyr2 = $('<div class="blockUI blockOverlay ui-widget-overlay" style="z-index:' + (z++) + ';display:none"></div>'); else lyr2 = $('<div class="blockUI blockOverlay" style="z-index:' + (z++) + ';display:none;border:none;margin:0;padding:0;width:100%;height:100%;top:0;left:0"></div>'); if (opts.theme && full) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage ui-dialog ui-widget ui-corner-all" style="z-index:' + (z + 10) + ';display:none;position:fixed">'; if (opts.title) { s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">' + (opts.title || '&nbsp;') + '</div>'; } s += '<div class="ui-widget-content ui-dialog-content"></div>'; s += '</div>'; } else if (opts.theme) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement ui-dialog ui-widget ui-corner-all" style="z-index:' + (z + 10) + ';display:none;position:absolute">'; if (opts.title) { s += '<div class="ui-widget-header ui-dialog-titlebar ui-corner-all blockTitle">' + (opts.title || '&nbsp;') + '</div>'; } s += '<div class="ui-widget-content ui-dialog-content"></div>'; s += '</div>'; } else if (full) { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockPage" style="z-index:' + (z + 10) + ';display:none;position:fixed"></div>'; } else { s = '<div class="blockUI ' + opts.blockMsgClass + ' blockElement" style="z-index:' + (z + 10) + ';display:none;position:absolute"></div>'; } lyr3 = $(s); // if we have a message, style it if (msg) { if (opts.theme) { lyr3.css(themedCSS); lyr3.addClass('ui-widget-content'); } else lyr3.css(css); } // style the overlay if (!opts.theme /*&& (!opts.applyPlatformOpacityRules)*/) lyr2.css(opts.overlayCSS); lyr2.css('position', full ? 'fixed' : 'absolute'); // make iframe layer transparent in IE if (msie || opts.forceIframe) lyr1.css('opacity', 0.0); //$([lyr1[0],lyr2[0],lyr3[0]]).appendTo(full ? 'body' : el); var layers = [lyr1, lyr2, lyr3], $par = full ? $('body') : $(el); $.each(layers, function () { this.appendTo($par); }); if (opts.theme && opts.draggable && $.fn.draggable) { lyr3.draggable({ handle: '.ui-dialog-titlebar', cancel: 'li' }); } // ie7 must use absolute positioning in quirks mode and to account for activex issues (when scrolling) var expr = setExpr && (!$.support.boxModel || $('object,embed', full ? null : el).length > 0); if (ie6 || expr) { // give body 100% height if (full && opts.allowBodyStretch && $.support.boxModel) $('html,body').css('height', '100%'); // fix ie6 issue when blocked element has a border width if ((ie6 || !$.support.boxModel) && !full) { var t = sz(el, 'borderTopWidth'), l = sz(el, 'borderLeftWidth'); var fixT = t ? '(0 - ' + t + ')' : 0; var fixL = l ? '(0 - ' + l + ')' : 0; } // simulate fixed position $.each(layers, function (i, o) { var s = o[0].style; s.position = 'absolute'; if (i < 2) { if (full) s.setExpression('height', 'Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.support.boxModel?0:' + opts.quirksmodeOffsetHack + ') + "px"'); else s.setExpression('height', 'this.parentNode.offsetHeight + "px"'); if (full) s.setExpression('width', 'jQuery.support.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'); else s.setExpression('width', 'this.parentNode.offsetWidth + "px"'); if (fixL) s.setExpression('left', fixL); if (fixT) s.setExpression('top', fixT); } else if (opts.centerY) { if (full) s.setExpression('top', '(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"'); s.marginTop = 0; } else if (!opts.centerY && full) { var top = (opts.css && opts.css.top) ? parseInt(opts.css.top, 10) : 0; var expression = '((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + ' + top + ') + "px"'; s.setExpression('top', expression); } }); } // show the message if (msg) { if (opts.theme) lyr3.find('.ui-widget-content').append(msg); else lyr3.append(msg); if (msg.jquery || msg.nodeType) $(msg).show(); } if ((msie || opts.forceIframe) && opts.showOverlay) lyr1.show(); // opacity is zero if (opts.fadeIn) { var cb = opts.onBlock ? opts.onBlock : noOp; var cb1 = (opts.showOverlay && !msg) ? cb : noOp; var cb2 = msg ? cb : noOp; if (opts.showOverlay) lyr2._fadeIn(opts.fadeIn, cb1); if (msg) lyr3._fadeIn(opts.fadeIn, cb2); } else { if (opts.showOverlay) lyr2.show(); if (msg) lyr3.show(); if (opts.onBlock) opts.onBlock.bind(lyr3)(); } // bind key and mouse events bind(1, el, opts); if (full) { pageBlock = lyr3[0]; pageBlockEls = $(opts.focusableElements, pageBlock); if (opts.focusInput) setTimeout(focus, 20); } else center(lyr3[0], opts.centerX, opts.centerY); if (opts.timeout) { // auto-unblock var to = setTimeout(function () { if (full) $.unblockUI(opts); else $(el).unblock(opts); }, opts.timeout); $(el).data('blockUI.timeout', to); } } // remove the block function remove(el, opts) { var count; var full = (el == window); var $el = $(el); var data = $el.data('blockUI.history'); var to = $el.data('blockUI.timeout'); if (to) { clearTimeout(to); $el.removeData('blockUI.timeout'); } opts = $.extend({}, $.blockUI.defaults, opts || {}); bind(0, el, opts); // unbind events if (opts.onUnblock === null) { opts.onUnblock = $el.data('blockUI.onUnblock'); $el.removeData('blockUI.onUnblock'); } var els; if (full) // crazy selector to handle odd field errors in ie6/7 els = $('body').children().filter('.blockUI').add('body > .blockUI'); else els = $el.find('>.blockUI'); // fix cursor issue if (opts.cursorReset) { if (els.length > 1) els[1].style.cursor = opts.cursorReset; if (els.length > 2) els[2].style.cursor = opts.cursorReset; } if (full) pageBlock = pageBlockEls = null; if (opts.fadeOut) { count = els.length; els.stop().fadeOut(opts.fadeOut, function () { if (--count === 0) reset(els, data, opts, el); }); } else reset(els, data, opts, el); } // move blocking element back into the DOM where it started function reset(els, data, opts, el) { var $el = $(el); if ($el.data('blockUI.isBlocked')) return; els.each(function (i, o) { // remove via DOM calls so we don't lose event handlers if (this.parentNode) this.parentNode.removeChild(this); }); if (data && data.el) { data.el.style.display = data.display; data.el.style.position = data.position; data.el.style.cursor = 'default'; // #59 if (data.parent) data.parent.appendChild(data.el); $el.removeData('blockUI.history'); } if ($el.data('blockUI.static')) { $el.css('position', 'static'); // #22 } if (typeof opts.onUnblock == 'function') opts.onUnblock(el, opts); // fix issue in Safari 6 where block artifacts remain until reflow var body = $(document.body), w = body.width(), cssW = body[0].style.width; body.width(w - 1).width(w); body[0].style.width = cssW; } // bind/unbind the handler function bind(b, el, opts) { var full = el == window, $el = $(el); // don't bother unbinding if there is nothing to unbind if (!b && (full && !pageBlock || !full && !$el.data('blockUI.isBlocked'))) return; $el.data('blockUI.isBlocked', b); // don't bind events when overlay is not in use or if bindEvents is false if (!full || !opts.bindEvents || (b && !opts.showOverlay)) return; // bind anchors and inputs for mouse and key events var events = 'mousedown mouseup keydown keypress keyup touchstart touchend touchmove'; if (b) $(document).bind(events, opts, handler); else $(document).unbind(events, handler); // former impl... // var $e = $('a,:input'); // b ? $e.bind(events, opts, handler) : $e.unbind(events, handler); } // event handler to suppress keyboard/mouse events when blocking function handler(e) { // allow tab navigation (conditionally) if (e.type === 'keydown' && e.keyCode && e.keyCode == 9) { if (pageBlock && e.data.constrainTabKey) { var els = pageBlockEls; var fwd = !e.shiftKey && e.target === els[els.length - 1]; var back = e.shiftKey && e.target === els[0]; if (fwd || back) { setTimeout(function () { focus(back); }, 10); return false; } } } var opts = e.data; var target = $(e.target); if (target.hasClass('blockOverlay') && opts.onOverlayClick) opts.onOverlayClick(e); // allow events within the message content if (target.parents('div.' + opts.blockMsgClass).length > 0) return true; // allow events for content that is not being blocked return target.parents().children().filter('div.blockUI').length === 0; } function focus(back) { if (!pageBlockEls) return; var e = pageBlockEls[back === true ? pageBlockEls.length - 1 : 0]; if (e) e.focus(); } function center(el, x, y) { var p = el.parentNode, s = el.style; var l = ((p.offsetWidth - el.offsetWidth) / 2) - sz(p, 'borderLeftWidth'); var t = ((p.offsetHeight - el.offsetHeight) / 2) - sz(p, 'borderTopWidth'); if (x) s.left = l > 0 ? (l + 'px') : '0'; if (y) s.top = t > 0 ? (t + 'px') : '0'; } function sz(el, p) { return parseInt($.css(el, p), 10) || 0; } } /*global define:true */ if (typeof define === 'function' && define.amd && define.amd.jQuery) { define(['jquery'], setup); } else { setup(jQuery); } })();
JavaScript
String.prototype.toCapitalizeCase = function () { return this.charAt(0).toUpperCase() + this.slice(1); }; String.prototype.trim = function () { return this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""); }; String.prototype.startsWith = function (str) { return this.match("^" + str) == str; }; String.prototype.endsWith = function (str) { return this.match(str + "$") == str; }; Array.prototype.contains = function (obj) { return $.inArray(obj, this) > -1; };
JavaScript
//============================================================================= // System : Color Syntax Highlighter // File : Highlight.js // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 11/13/2007 // Note : Copyright 2006, Eric Woodruff, All rights reserved // // This contains the script to expand and collapse the regions in the // syntax highlighted code. // //============================================================================= // Expand/collapse a region function HighlightExpandCollapse(showId, hideId) { var showSpan = document.getElementById(showId), hideSpan = document.getElementById(hideId); showSpan.style.display = "inline"; hideSpan.style.display = "none"; } // Copy the code if Enter or Space is hit with the image focused function CopyColorizedCodeCheckKey(titleDiv, eventObj) { if(eventObj != undefined && (eventObj.keyCode == 13 || eventObj.keyCode == 32)) CopyColorizedCode(titleDiv); } // Change the icon as the mouse moves in and out of the Copy Code link // There should be an image with the same name but an "_h" suffix just // before the extension. function CopyCodeChangeIcon(linkSpan) { var image = linkSpan.firstChild.src; var pos = image.lastIndexOf("."); if(linkSpan.className == "highlight-copycode") { linkSpan.className = "highlight-copycode_h"; linkSpan.firstChild.src = image.substr(0, pos) + "_h" + image.substr(pos); } else { linkSpan.className = "highlight-copycode"; linkSpan.firstChild.src = image.substr(0, pos - 2) + image.substr(pos); } } // Copy the code from a colorized code block to the clipboard. function CopyColorizedCode(titleDiv) { var preTag, idx, line, block, htmlLines, lines, codeText, hasLineNos, hasRegions, clip, trans, copyObject, clipID; var reLineNo = /^\s*\d{1,4}/; var reRegion = /^\s*\d{1,4}\+.*?\d{1,4}-/; var reRegionText = /^\+.*?\-/; // Find the <pre> tag containing the code. It should be in the next // element or one of its children. block = titleDiv.nextSibling; while(block.nodeName == "#text") block = block.nextSibling; while(block.tagName != "PRE") { block = block.firstChild; while(block.nodeName == "#text") block = block.nextSibling; } if(block.innerText != undefined) codeText = block.innerText; else codeText = block.textContent; hasLineNos = block.innerHTML.indexOf("highlight-lineno"); hasRegions = block.innerHTML.indexOf("highlight-collapsebox"); htmlLines = block.innerHTML.split("\n"); lines = codeText.split("\n"); // Remove the line numbering and collapsible regions if present if(hasLineNos != -1 || hasRegions != -1) { codeText = ""; for(idx = 0; idx < lines.length; idx++) { line = lines[idx]; if(hasRegions && reRegion.test(line)) line = line.replace(reRegion, ""); else { line = line.replace(reLineNo, ""); // Lines in expanded blocks have an extra space if(htmlLines[idx].indexOf("highlight-expanded") != -1 || htmlLines[idx].indexOf("highlight-endblock") != -1) line = line.substr(1); } if(hasRegions && reRegionText.test(line)) line = line.replace(reRegionText, ""); codeText += line; // Not all browsers keep the line feed when split if(line[line.length - 1] != "\n") codeText += "\n"; } } // IE or FireFox/Netscape? if(window.clipboardData) window.clipboardData.setData("Text", codeText); else if(window.netscape) { // Give unrestricted access to browser APIs using XPConnect try { netscape.security.PrivilegeManager.enablePrivilege( "UniversalXPConnect"); } catch(e) { alert("Universal Connect was refused, cannot copy to " + "clipboard. Go to about:config and set " + "signed.applets.codebase_principal_support to true to " + "enable clipboard support."); return; } // Creates an instance of nsIClipboard clip = Components.classes[ "@mozilla.org/widget/clipboard;1"].createInstance( Components.interfaces.nsIClipboard); // Creates an instance of nsITransferable if(clip) trans = Components.classes[ "@mozilla.org/widget/transferable;1"].createInstance( Components.interfaces.nsITransferable); if(!trans) { alert("Copy to Clipboard is not supported by this browser"); return; } // Register the data flavor trans.addDataFlavor("text/unicode"); // Create object to hold the data copyObject = new Object(); // Creates an instance of nsISupportsString copyObject = Components.classes[ "@mozilla.org/supports-string;1"].createInstance( Components.interfaces.nsISupportsString); // Assign the data to be copied copyObject.data = codeText; // Add data objects to transferable trans.setTransferData("text/unicode", copyObject, codeText.length * 2); clipID = Components.interfaces.nsIClipboard; if(!clipID) { alert("Copy to Clipboard is not supported by this browser"); return; } // Transfer the data to the clipboard clip.setData(trans, null, clipID.kGlobalClipboard); } else alert("Copy to Clipboard is not supported by this browser"); }
JavaScript
//============================================================================= // System : Sandcastle Help File Builder // File : TOC.js // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 04/11/2008 // Note : Copyright 2006-2008, Eric Woodruff, All rights reserved // Compiler: JavaScript // // This file contains the methods necessary to implement a simple tree view // for the table of content with a resizable splitter and Ajax support to // load tree nodes on demand. It also contains the script necessary to do // full-text searches. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://www.CodePlex.com/SHFB. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.3.0.0 09/12/2006 EFW Created the code // 1.4.0.2 06/15/2007 EFW Reworked to get rid of frame set and to add // support for Ajax to load tree nodes on demand. // 1.5.0.0 06/24/2007 EFW Added full-text search capabilities // 1.6.0.7 04/01/2008 EFW Merged changes from Ferdinand Prantl to add a // website keyword index. Added support for "topic" // query string option. //============================================================================= // IE flag var isIE = (navigator.userAgent.indexOf("MSIE") >= 0); // Minimum width of the TOC div var minWidth = 100; // Elements and sizing info var divTOC, divSizer, topicContent, divNavOpts, divSearchOpts, divSearchResults, divIndexOpts, divIndexResults, divTree, docBody, maxWidth, offset, txtSearchText, chkSortByTitle; // Last node selected var lastNode, lastSearchNode, lastIndexNode; // Last page with keyword index var currentIndexPage = 0; //============================================================================ // Initialize the tree view and resize the content function Initialize() { docBody = document.getElementsByTagName("body")[0]; divTOC = document.getElementById("TOCDiv"); divSizer = document.getElementById("TOCSizer"); topicContent = document.getElementById("TopicContent"); divNavOpts = document.getElementById("divNavOpts"); divSearchOpts = document.getElementById("divSearchOpts"); divSearchResults = document.getElementById("divSearchResults"); divIndexOpts = document.getElementById("divIndexOpts"); divIndexResults = document.getElementById("divIndexResults"); divTree = document.getElementById("divTree"); txtSearchText = document.getElementById("txtSearchText"); chkSortByTitle = document.getElementById("chkSortByTitle"); // The sizes are bit off in FireFox if(!isIE) divNavOpts.style.width = divSearchOpts.style.width = divIndexOpts.style.width = 292; ResizeTree(); SyncTOC(); // Use an alternate default page if a topic is specified in // the query string. var queryString = document.location.search; if(queryString != "") { var idx, options = queryString.split(/[\?\=\&]/); for(idx = 0; idx < options.length; idx++) if(options[idx] == "topic" && idx + 1 < options.length) { topicContent.src = options[idx + 1]; break; } } } //============================================================================ // Navigation and expand/collaps code // Synchronize the table of content with the selected page if possible function SyncTOC() { var idx, anchor, base, href, url, anchors, treeNode, saveNode; base = window.location.href; base = base.substr(0, base.lastIndexOf("/") + 1); if(base.substr(0, 5) == "file:" && base.substr(0, 8) != "file:///") base = base.replace("file://", "file:///"); url = GetCurrentUrl(); if(url == "") return false; if(url.substr(0, 5) == "file:" && url.substr(0, 8) != "file:///") url = url.replace("file://", "file:///"); while(true) { anchors = divTree.getElementsByTagName("A"); anchor = null; for(idx = 0; idx < anchors.length; idx++) { href = anchors[idx].href; if(href.substring(0, 7) != 'http://' && href.substring(0, 8) != 'https://' && href.substring(0, 7) != 'file://') href = base + href; if(href == url) { anchor = anchors[idx]; break; } } if(anchor == null) { // If it contains a "#", strip anything after that and try again if(url.indexOf("#") != -1) { url = url.substr(0, url.indexOf("#")); continue; } return; } break; } // If found, select it and find the parent tree node SelectNode(anchor); saveNode = anchor; lastNode = null; while(anchor != null) { if(anchor.className == "TreeNode") { treeNode = anchor; break; } anchor = anchor.parentNode; } // Expand it and all of its parents while(anchor != null) { Expand(anchor); anchor = anchor.parentNode; while(anchor != null) { if(anchor.className == "TreeNode") break; anchor = anchor.parentNode; } } lastNode = saveNode; // Scroll the node into view var windowTop = lastNode.offsetTop - divTree.offsetTop - divTree.scrollTop; var windowBottom = divTree.clientHeight - windowTop - lastNode.offsetHeight; if(windowTop < 0) divTree.scrollTop += windowTop - 30; else if(windowBottom < 0) divTree.scrollTop -= windowBottom - 30; } // Get the currently loaded URL from the IFRAME function GetCurrentUrl() { var base, url = ""; try { url = window.frames["TopicContent"].document.URL.replace(/\\/g, "/"); } catch(e) { // If this happens the user probably navigated to another frameset // that didn't make itself the topmost frameset and we don't have // control of the other frame anymore. In that case, just reload // our index page. base = window.location.href; base = base.substr(0, base.lastIndexOf("/") + 1); if(base.substr(0, 5) == "file:" && base.substr(0, 8) != "file:///") base = base.replace("file://", "file:///"); if(base.substr(0, 5) == "file:") top.location.href = base + "Index.html"; else top.location.href = base + "Index.aspx"; } return url; } // Expand or collapse all nodes function ExpandOrCollapseAll(expandNodes) { var divIdx, childIdx, img, divs = document.getElementsByTagName("DIV"); var childNodes, child, div, link, img; for(divIdx = 0; divIdx < divs.length; divIdx++) if(divs[divIdx].className == "Hidden" || divs[divIdx].className == "Visible") { childNodes = divs[divIdx].parentNode.childNodes; for(childIdx = 0; childIdx < childNodes.length; childIdx++) { child = childNodes[childIdx]; if(child.className == "TreeNodeImg") img = child; if(child.className == "Hidden" || child.className == "Visible") { div = child; break; } } if(div.className == "Visible" && !expandNodes) { div.className = "Hidden"; img.src = "Collapsed.gif"; } else if(div.className == "Hidden" && expandNodes) { div.className = "Visible"; img.src = "Expanded.gif"; if(div.innerHTML == "") FillNode(div, true) } } } // Toggle the state of the specified node function Toggle(node) { var i, childNodes, child, div, link; childNodes = node.parentNode.childNodes; for(i = 0; i < childNodes.length; i++) { child = childNodes[i]; if(child.className == "Hidden" || child.className == "Visible") { div = child; break; } } if(div.className == "Visible") { div.className = "Hidden"; node.src = "Collapsed.gif"; } else { div.className = "Visible"; node.src = "Expanded.gif"; if(div.innerHTML == "") FillNode(div, false) } } // Expand the selected node function Expand(node) { var i, childNodes, child, div, img; // If not valid, don't bother if(GetCurrentUrl() == "") return false; if(node.tagName == "A") childNodes = node.parentNode.childNodes; else childNodes = node.childNodes; for(i = 0; i < childNodes.length; i++) { child = childNodes[i]; if(child.className == "TreeNodeImg") img = child; if(child.className == "Hidden" || child.className == "Visible") { div = child; break; } } if(lastNode != null) lastNode.className = "UnselectedNode"; div.className = "Visible"; img.src = "Expanded.gif"; if(node.tagName == "A") { node.className = "SelectedNode"; lastNode = node; } if(div.innerHTML == "") FillNode(div, false) return true; } // Set the style of the specified node to "selected" function SelectNode(node) { // If not valid, don't bother if(GetCurrentUrl() == "") return false; if(lastNode != null) lastNode.className = "UnselectedNode"; node.className = "SelectedNode"; lastNode = node; return true; } //============================================================================ // Ajax-related code used to fill the tree nodes on demand function GetXmlHttpRequest() { var xmlHttp = null; // If IE7, Mozilla, Safari, etc., use the native object. // Otherwise, use the ActiveX control for IE5.x and IE6. if(window.XMLHttpRequest) xmlHttp = new XMLHttpRequest(); else if(window.ActiveXObject) xmlHttp = new ActiveXObject("MSXML2.XMLHTTP.3.0"); return xmlHttp; } // Perform an AJAX-style request for the contents of a node and put the // contents into the empty div. function FillNode(div, expandChildren) { var xmlHttp = GetXmlHttpRequest(), now = new Date(); if(xmlHttp == null) { div.innerHTML = "<b>XML HTTP request not supported!</b>"; return; } div.innerHTML = "Loading..."; // Add a unique hash to ensure it doesn't use cached results xmlHttp.open("GET", "FillNode.aspx?Id=" + div.id + "&hash=" + now.getTime(), true); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { div.innerHTML = xmlHttp.responseText; if(expandChildren) ExpandOrCollapseAll(true); } } xmlHttp.send(null) } //============================================================================ // Resizing code // Resize the tree div so that it fills the document body function ResizeTree() { var y, newHeight; if(self.innerHeight) // All but IE y = self.innerHeight; else // IE - Strict if(document.documentElement && document.documentElement.clientHeight) y = document.documentElement.clientHeight; else // Everything else if(document.body) y = document.body.clientHeight; newHeight = y - parseInt(divNavOpts.style.height, 10) - 6; if(newHeight < 50) newHeight = 50; divTree.style.height = newHeight; newHeight = y - parseInt(divSearchOpts.style.height, 10) - 6; if(newHeight < 100) newHeight = 100; divSearchResults.style.height = newHeight; newHeight = y - parseInt(divIndexOpts.style.height, 10) - 6; if(newHeight < 25) newHeight = 25; divIndexResults.style.height = newHeight; // Resize the content div ResizeContent(); } // Resize the content div function ResizeContent() { if(isIE) maxWidth = docBody.clientWidth; else maxWidth = docBody.clientWidth - 4; topicContent.style.width = maxWidth - (divSizer.offsetLeft + divSizer.offsetWidth); maxWidth -= minWidth; } // This is called to prepare for dragging the sizer div function OnMouseDown(event) { var x; // Make sure the splitter is at the top of the z-index divSizer.style.zIndex = 5000; // The content is in an IFRAME which steals mouse events so // hide it while resizing. topicContent.style.display = "none"; if(isIE) x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; else x = event.clientX + window.scrollX; // Save starting offset offset = parseInt(divSizer.style.left, 10); if(isNaN(offset)) offset = 0; offset -= x; if(isIE) { document.attachEvent("onmousemove", OnMouseMove); document.attachEvent("onmouseup", OnMouseUp); window.event.cancelBubble = true; window.event.returnValue = false; } else { document.addEventListener("mousemove", OnMouseMove, true); document.addEventListener("mouseup", OnMouseUp, true); event.preventDefault(); } } // Resize the TOC and content divs as the sizer is dragged function OnMouseMove(event) { var x, pos; // Get cursor position with respect to the page if(isIE) x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft; else x = event.clientX + window.scrollX; left = offset + x; // Adjusts the width of the TOC divs pos = (event.clientX > maxWidth) ? maxWidth : (event.clientX < minWidth) ? minWidth : event.clientX; divTOC.style.width = divSearchResults.style.width = divIndexResults.style.width = divTree.style.width = pos; if(!isIE) pos -= 8; divNavOpts.style.width = divSearchOpts.style.width = divIndexOpts.style.width = pos; // Resize the content div to fit in the remaining space ResizeContent(); } // Finish the drag operation when the mouse button is released function OnMouseUp(event) { if(isIE) { document.detachEvent("onmousemove", OnMouseMove); document.detachEvent("onmouseup", OnMouseUp); } else { document.removeEventListener("mousemove", OnMouseMove, true); document.removeEventListener("mouseup", OnMouseUp, true); } // Show the content div again topicContent.style.display = "inline"; } //============================================================================ // Search code function ShowHideSearch(show) { if(show) { divNavOpts.style.display = divTree.style.display = "none"; divSearchOpts.style.display = divSearchResults.style.display = ""; } else { divSearchOpts.style.display = divSearchResults.style.display = "none"; divNavOpts.style.display = divTree.style.display = ""; } } // When enter is hit in the search text box, do the search function OnSearchTextKeyPress(evt) { if(evt.keyCode == 13) { PerformSearch(); return false; } return true; } // Perform a keyword search function PerformSearch() { var xmlHttp = GetXmlHttpRequest(), now = new Date(); if(xmlHttp == null) { divSearchResults.innerHTML = "<b>XML HTTP request not supported!</b>"; return; } divSearchResults.innerHTML = "<span class=\"PaddedText\">Searching...</span>"; // Add a unique hash to ensure it doesn't use cached results xmlHttp.open("GET", "SearchHelp.aspx?Keywords=" + txtSearchText.value + "&SortByTitle=" + (chkSortByTitle.checked ? "true" : "false") + "&hash=" + now.getTime(), true); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { divSearchResults.innerHTML = xmlHttp.responseText; lastSearchNode = divSearchResults.childNodes[0].childNodes[1]; if(lastSearchNode != null) { if(lastSearchNode.tagName != "A") lastSearchNode = lastSearchNode.nextSibling; SelectSearchNode(lastSearchNode); topicContent.src = lastSearchNode.href; } } } xmlHttp.send(null) } // Set the style of the specified search result node to "selected" function SelectSearchNode(node) { if(lastSearchNode != null) lastSearchNode.className = "UnselectedNode"; node.className = "SelectedNode"; lastSearchNode = node; return true; } //============================================================================ // KeyWordIndex code function ShowHideIndex(show) { if(show) { PopulateIndex(currentIndexPage); divNavOpts.style.display = divTree.style.display = "none"; divIndexOpts.style.display = divIndexResults.style.display = ""; } else { divIndexOpts.style.display = divIndexResults.style.display = "none"; divNavOpts.style.display = divTree.style.display = ""; } } // Populate keyword index function PopulateIndex(startIndex) { var xmlHttp = GetXmlHttpRequest(), now = new Date(); var firstNode; if(xmlHttp == null) { divIndexResults.innerHTML = "<b>XML HTTP request not supported!</b>"; return; } divIndexResults.innerHTML = "<span class=\"PaddedText\">Loading " + "keyword index...</span>"; // Add a unique hash to ensure it doesn't use cached results xmlHttp.open("GET", "LoadIndexKeywords.aspx?StartIndex=" + startIndex + "&hash=" + now.getTime(), true); xmlHttp.onreadystatechange = function() { if(xmlHttp.readyState == 4) { divIndexResults.innerHTML = xmlHttp.responseText; if(startIndex > 0) { firstNode = divIndexResults.childNodes[1]; if(firstNode != null && !firstNode.innerHTML) firstNode = divIndexResults.childNodes[2]; } else firstNode = divIndexResults.childNodes[0]; if(firstNode != null) lastIndexNode = firstNode.childNodes[0]; if(lastIndexNode != null) { if(lastIndexNode.tagName != "A") lastIndexNode = lastIndexNode.nextSibling; SelectIndexNode(lastIndexNode); topicContent.src = lastIndexNode.href; } currentIndexPage = startIndex; } } xmlHttp.send(null) } // Set the style of the specified keyword index node to "selected" function SelectIndexNode(node) { if(lastIndexNode != null) lastIndexNode.className = "UnselectedNode"; node.className = "SelectedNode"; lastIndexNode = node; return true; } // Changes the current page with keyword index forward or backward function ChangeIndexPage(direction) { PopulateIndex(currentIndexPage + direction); return false; }
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //#INSERTFILE "../../lib/filter.js" //#INSERTFILE "../../lib/glfx.js"
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //#ECHO (function() { var imagelib = {};
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //#REQUIRE "includes.js" imagelib.drawing = {}; imagelib.drawing.context = function(size) { var canvas = document.createElement('canvas'); canvas.width = size.w; canvas.height = size.h; canvas.style.setProperty('image-rendering', 'optimizeQuality', null); return canvas.getContext('2d'); }; imagelib.drawing.copy = function(dstCtx, src, size) { dstCtx.drawImage(src.canvas || src, 0, 0, size.w, size.h); }; imagelib.drawing.clear = function(ctx, size) { ctx.clearRect(0, 0, size.w, size.h); }; imagelib.drawing.drawCenterInside = function(dstCtx, src, dstRect, srcRect) { if (srcRect.w / srcRect.h > dstRect.w / dstRect.h) { var h = srcRect.h * dstRect.w / srcRect.w; imagelib.drawing.drawImageScaled(dstCtx, src, srcRect.x, srcRect.y, srcRect.w, srcRect.h, dstRect.x, dstRect.y + (dstRect.h - h) / 2, dstRect.w, h); } else { var w = srcRect.w * dstRect.h / srcRect.h; imagelib.drawing.drawImageScaled(dstCtx, src, srcRect.x, srcRect.y, srcRect.w, srcRect.h, dstRect.x + (dstRect.w - w) / 2, dstRect.y, w, dstRect.h); } }; imagelib.drawing.drawCenterCrop = function(dstCtx, src, dstRect, srcRect) { if (srcRect.w / srcRect.h > dstRect.w / dstRect.h) { var w = srcRect.h * dstRect.w / dstRect.h; imagelib.drawing.drawImageScaled(dstCtx, src, srcRect.x + (srcRect.w - w) / 2, srcRect.y, w, srcRect.h, dstRect.x, dstRect.y, dstRect.w, dstRect.h); } else { var h = srcRect.w * dstRect.h / dstRect.w; imagelib.drawing.drawImageScaled(dstCtx, src, srcRect.x, srcRect.y + (srcRect.h - h) / 2, srcRect.w, h, dstRect.x, dstRect.y, dstRect.w, dstRect.h); } }; imagelib.drawing.drawImageScaled = function(dstCtx, src, sx, sy, sw, sh, dx, dy, dw, dh) { if ((dw < sw && dh < sh) && imagelib.ALLOW_MANUAL_RESCALE) { sx = Math.floor(sx); sy = Math.floor(sy); sw = Math.ceil(sw); sh = Math.ceil(sh); dx = Math.floor(dx); dy = Math.floor(dy); dw = Math.ceil(dw); dh = Math.ceil(dh); // scaling down, use an averaging algorithm since canvas.drawImage doesn't do a good // job in all browsers. var tmpCtx = imagelib.drawing.context({ w: sw, h: sh }); tmpCtx.drawImage(src.canvas || src, 0, 0); var srcData = tmpCtx.getImageData(0, 0, sw, sh); var outCtx = imagelib.drawing.context({ w: dw, h: dh }); var outData = outCtx.createImageData(dw, dh); var tr, tg, tb, ta; // R/G/B/A totals var numOpaquePixels; var numPixels; for (var y = 0; y < dh; y++) { for (var x = 0; x < dw; x++) { tr = tg = tb = ta = 0; numOpaquePixels = numPixels = 0; // Average the relevant region from source image for (var j = Math.floor(y * sh / dh); j < (y + 1) * sh / dh; j++) { for (var i = Math.floor(x * sw / dw); i < (x + 1) * sw / dw; i++) { ++numPixels; ta += srcData.data[(j * sw + i) * 4 + 3]; if (srcData.data[(j * sw + i) * 4 + 3] == 0) { // disregard transparent pixels when computing average for R/G/B continue; } ++numOpaquePixels; tr += srcData.data[(j * sw + i) * 4 + 0]; tg += srcData.data[(j * sw + i) * 4 + 1]; tb += srcData.data[(j * sw + i) * 4 + 2]; } } outData.data[(y * dw + x) * 4 + 0] = tr / numOpaquePixels; outData.data[(y * dw + x) * 4 + 1] = tg / numOpaquePixels; outData.data[(y * dw + x) * 4 + 2] = tb / numOpaquePixels; outData.data[(y * dw + x) * 4 + 3] = ta / numPixels; } } outCtx.putImageData(outData, 0, 0); dstCtx.drawImage(outCtx.canvas, dx, dy); } else { // scaling up, use canvas.drawImage dstCtx.drawImage(src.canvas || src, sx, sy, sw, sh, dx, dy, dw, dh); } }; imagelib.drawing.trimRectWorkerJS_ = [ "self['onmessage'] = function(event) { ", " var l = event.data.size.w, t = event.data.size.h, r = 0, b = 0; ", " ", " var alpha; ", " for (var y = 0; y < event.data.size.h; y++) { ", " for (var x = 0; x < event.data.size.w; x++) { ", " alpha = event.data.imageData.data[ ", " ((y * event.data.size.w + x) << 2) + 3]; ", " if (alpha >= event.data.minAlpha) { ", " l = Math.min(x, l); ", " t = Math.min(y, t); ", " r = Math.max(x, r); ", " b = Math.max(y, b); ", " } ", " } ", " } ", " ", " if (l > r) { ", " // no pixels, couldn't trim ", " postMessage({ x: 0, y: 0, w: event.data.size.w, h: event.data.size.h });", " return; ", " } ", " ", " postMessage({ x: l, y: t, w: r - l + 1, h: b - t + 1 }); ", "}; ", ""].join('\n'); imagelib.drawing.getTrimRect = function(ctx, size, minAlpha, callback) { callback = callback || function(){}; if (!ctx.canvas) { // Likely an image var src = ctx; ctx = imagelib.drawing.context(size); imagelib.drawing.copy(ctx, src, size); } if (minAlpha == 0) callback({ x: 0, y: 0, w: size.w, h: size.h }); minAlpha = minAlpha || 1; var worker = imagelib.util.runWorkerJs( imagelib.drawing.trimRectWorkerJS_, { imageData: ctx.getImageData(0, 0, size.w, size.h), size: size, minAlpha: minAlpha }, callback); return worker; }; imagelib.drawing.getCenterOfMass = function(ctx, size, minAlpha, callback) { callback = callback || function(){}; if (!ctx.canvas) { // Likely an image var src = ctx; ctx = imagelib.drawing.context(size); imagelib.drawing.copy(ctx, src, size); } if (minAlpha == 0) callback({ x: size.w / 2, y: size.h / 2 }); minAlpha = minAlpha || 1; var l = size.w, t = size.h, r = 0, b = 0; var imageData = ctx.getImageData(0, 0, size.w, size.h); var sumX = 0; var sumY = 0; var n = 0; // number of pixels > minAlpha var alpha; for (var y = 0; y < size.h; y++) { for (var x = 0; x < size.w; x++) { alpha = imageData.data[((y * size.w + x) << 2) + 3]; if (alpha >= minAlpha) { sumX += x; sumY += y; ++n; } } } if (n <= 0) { // no pixels > minAlpha, just use center callback({ x: size.w / 2, h: size.h / 2 }); } callback({ x: Math.round(sumX / n), y: Math.round(sumY / n) }); }; imagelib.drawing.copyAsAlpha = function(dstCtx, src, size, onColor, offColor) { onColor = onColor || '#fff'; offColor = offColor || '#000'; dstCtx.save(); dstCtx.clearRect(0, 0, size.w, size.h); dstCtx.globalCompositeOperation = 'source-over'; imagelib.drawing.copy(dstCtx, src, size); dstCtx.globalCompositeOperation = 'source-atop'; dstCtx.fillStyle = onColor; dstCtx.fillRect(0, 0, size.w, size.h); dstCtx.globalCompositeOperation = 'destination-atop'; dstCtx.fillStyle = offColor; dstCtx.fillRect(0, 0, size.w, size.h); dstCtx.restore(); }; imagelib.drawing.makeAlphaMask = function(ctx, size, fillColor) { var src = ctx.getImageData(0, 0, size.w, size.h); var dst = ctx.createImageData(size.w, size.h); var srcData = src.data; var dstData = dst.data; var i, g; for (var y = 0; y < size.h; y++) { for (var x = 0; x < size.w; x++) { i = (y * size.w + x) << 2; g = 0.30 * srcData[i] + 0.59 * srcData[i + 1] + 0.11 * srcData[i + 2]; dstData[i] = dstData[i + 1] = dstData[i + 2] = 255; dstData[i + 3] = g; } } ctx.putImageData(dst, 0, 0); if (fillColor) { ctx.save(); ctx.globalCompositeOperation = 'source-atop'; ctx.fillStyle = fillColor; ctx.fillRect(0, 0, size.w, size.h); ctx.restore(); } }; imagelib.drawing.applyFilter = function(filter, ctx, size) { var src = ctx.getImageData(0, 0, size.w, size.h); var dst = ctx.createImageData(size.w, size.h); filter.apply(src, dst); ctx.putImageData(dst, 0, 0); }; (function() { function slowblur_(radius, ctx, size) { var rows = Math.ceil(radius); var r = rows * 2 + 1; var matrix = new Array(r * r); var sigma = radius / 3; var sigma22 = 2 * sigma * sigma; var sqrtPiSigma22 = Math.sqrt(Math.PI * sigma22); var radius2 = radius * radius; var total = 0; var index = 0; var distance2; for (var y = -rows; y <= rows; y++) { for (var x = -rows; x <= rows; x++) { distance2 = 1.0*x*x + 1.0*y*y; if (distance2 > radius2) matrix[index] = 0; else matrix[index] = Math.exp(-distance2 / sigma22) / sqrtPiSigma22; total += matrix[index]; index++; } } imagelib.drawing.applyFilter( new ConvolutionFilter(matrix, total, 0, true), ctx, size); } function glfxblur_(radius, ctx, size) { var canvas = fx.canvas(); var texture = canvas.texture(ctx.canvas); canvas.draw(texture).triangleBlur(radius).update(); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(canvas, 0, 0); } imagelib.drawing.blur = function(radius, ctx, size) { try { if (size.w > 128 || size.h > 128) { glfxblur_(radius, ctx, size); } else { slowblur_(radius, ctx, size); } } catch (e) { // WebGL unavailable, use the slower blur slowblur_(radius, ctx, size); } }; })(); imagelib.drawing.fx = function(effects, dstCtx, src, size) { effects = effects || []; var outerEffects = []; var innerEffects = []; var fillEffects = []; for (var i = 0; i < effects.length; i++) { if (/^outer/.test(effects[i].effect)) outerEffects.push(effects[i]); else if (/^inner/.test(effects[i].effect)) innerEffects.push(effects[i]); else if (/^fill/.test(effects[i].effect)) fillEffects.push(effects[i]); } var padLeft = 0, padTop, padRight, padBottom; var paddedSize; var tmpCtx, tmpCtx2; // Render outer effects for (var i = 0; i < outerEffects.length; i++) { padLeft = Math.max(padLeft, outerEffects[i].blur || 0); // blur radius } padTop = padRight = padBottom = padLeft; paddedSize = { w: size.w + padLeft + padRight, h: size.h + padTop + padBottom }; tmpCtx = imagelib.drawing.context(paddedSize); for (var i = 0; i < outerEffects.length; i++) { var effect = outerEffects[i]; dstCtx.save(); // D1 tmpCtx.save(); // T1 switch (effect.effect) { case 'outer-shadow': // The below method (faster) fails in Safari and other browsers, for some reason. Likely // something to do with the source-atop blending mode. // TODO: investigate why it fails in Safari // imagelib.drawing.clear(tmpCtx, size); // imagelib.drawing.copy(tmpCtx, src.canvas || src, size); // if (effect.blur) // imagelib.drawing.blur(effect.blur, tmpCtx, size); // tmpCtx.globalCompositeOperation = 'source-atop'; // tmpCtx.fillStyle = effect.color || '#000'; // tmpCtx.fillRect(0, 0, size.w, size.h); // if (effect.translate) // dstCtx.translate(effect.translate.x || 0, effect.translate.y || 0); // // dstCtx.globalAlpha = Math.max(0, Math.min(1, effect.opacity || 1)); // imagelib.drawing.copy(dstCtx, tmpCtx, size); imagelib.drawing.clear(tmpCtx, paddedSize); tmpCtx.save(); // T2 tmpCtx.translate(padLeft, padTop); imagelib.drawing.copyAsAlpha(tmpCtx, src.canvas || src, size); tmpCtx.restore(); // T2 if (effect.blur) imagelib.drawing.blur(effect.blur, tmpCtx, paddedSize); imagelib.drawing.makeAlphaMask(tmpCtx, paddedSize, effect.color || '#000'); if (effect.translate) dstCtx.translate(effect.translate.x || 0, effect.translate.y || 0); dstCtx.globalAlpha = Math.max(0, Math.min(1, effect.opacity || 1)); dstCtx.translate(-padLeft, -padTop); imagelib.drawing.copy(dstCtx, tmpCtx, paddedSize); break; } dstCtx.restore(); // D1 tmpCtx.restore(); // T1 } dstCtx.save(); // D1 // Render object with optional fill effects (only take first fill effect) tmpCtx = imagelib.drawing.context(size); imagelib.drawing.clear(tmpCtx, size); imagelib.drawing.copy(tmpCtx, src.canvas || src, size); var fillOpacity = 1.0; if (fillEffects.length) { var effect = fillEffects[0]; tmpCtx.save(); // T1 tmpCtx.globalCompositeOperation = 'source-atop'; switch (effect.effect) { case 'fill-color': tmpCtx.fillStyle = effect.color; break; case 'fill-lineargradient': var gradient = tmpCtx.createLinearGradient( effect.from.x, effect.from.y, effect.to.x, effect.to.y); for (var i = 0; i < effect.colors.length; i++) { gradient.addColorStop(effect.colors[i].offset, effect.colors[i].color); } tmpCtx.fillStyle = gradient; break; } fillOpacity = Math.max(0, Math.min(1, effect.opacity || 1)); tmpCtx.fillRect(0, 0, size.w, size.h); tmpCtx.restore(); // T1 } dstCtx.globalAlpha = fillOpacity; imagelib.drawing.copy(dstCtx, tmpCtx, size); dstCtx.globalAlpha = 1.0; // Render inner effects var translate; padLeft = padTop = padRight = padBottom = 0; for (var i = 0; i < innerEffects.length; i++) { translate = effect.translate || {}; padLeft = Math.max(padLeft, (innerEffects[i].blur || 0) + Math.max(0, translate.x || 0)); padTop = Math.max(padTop, (innerEffects[i].blur || 0) + Math.max(0, translate.y || 0)); padRight = Math.max(padRight, (innerEffects[i].blur || 0) + Math.max(0, -translate.x || 0)); padBottom = Math.max(padBottom, (innerEffects[i].blur || 0) + Math.max(0, -translate.y || 0)); } paddedSize = { w: size.w + padLeft + padRight, h: size.h + padTop + padBottom }; tmpCtx = imagelib.drawing.context(paddedSize); tmpCtx2 = imagelib.drawing.context(paddedSize); for (var i = 0; i < innerEffects.length; i++) { var effect = innerEffects[i]; dstCtx.save(); // D2 tmpCtx.save(); // T1 switch (effect.effect) { case 'inner-shadow': imagelib.drawing.clear(tmpCtx, paddedSize); tmpCtx.save(); // T2 tmpCtx.translate(padLeft, padTop); imagelib.drawing.copyAsAlpha(tmpCtx, src.canvas || src, size, '#fff', '#000'); tmpCtx.restore(); // T2 tmpCtx2.save(); // T2 tmpCtx2.translate(padLeft, padTop); imagelib.drawing.copyAsAlpha(tmpCtx2, src.canvas || src, size); tmpCtx2.restore(); // T2 if (effect.blur) imagelib.drawing.blur(effect.blur, tmpCtx2, paddedSize); imagelib.drawing.makeAlphaMask(tmpCtx2, paddedSize, '#000'); if (effect.translate) tmpCtx.translate(effect.translate.x || 0, effect.translate.y || 0); tmpCtx.globalCompositeOperation = 'source-over'; imagelib.drawing.copy(tmpCtx, tmpCtx2, paddedSize); imagelib.drawing.makeAlphaMask(tmpCtx, paddedSize, effect.color); dstCtx.globalAlpha = Math.max(0, Math.min(1, effect.opacity || 1)); dstCtx.translate(-padLeft, -padTop); imagelib.drawing.copy(dstCtx, tmpCtx, paddedSize); break; } tmpCtx.restore(); // T1 dstCtx.restore(); // D2 } dstCtx.restore(); // D1 };
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ imagelib.util = {}; /** * Helper method for running inline Web Workers, if the browser can support * them. If the browser doesn't support inline Web Workers, run the script * on the main thread, with this function body's scope, using eval. Browsers * must provide BlobBuilder, URL.createObjectURL, and Worker support to use * inline Web Workers. Most features such as importScripts() are not * currently supported, so this only works for basic workers. * @param {String} js The inline Web Worker Javascript code to run. This code * must use 'self' and not 'this' as the global context variable. * @param {Object} params The parameters object to pass to the worker. * Equivalent to calling Worker.postMessage(params); * @param {Function} callback The callback to run when the worker calls * postMessage. Equivalent to adding a 'message' event listener on a * Worker object and running callback(event.data); */ imagelib.util.runWorkerJs = function(js, params, callback) { var BlobBuilder = (window.BlobBuilder || window.WebKitBlobBuilder); var URL = (window.URL || window.webkitURL); var Worker = window.Worker; if (URL && BlobBuilder && Worker) { // BlobBuilder, Worker, and window.URL.createObjectURL are all available, // so we can use inline workers. var bb = new BlobBuilder(); bb.append(js); var worker = new Worker(URL.createObjectURL(bb.getBlob())); worker.onmessage = function(event) { callback(event.data); }; worker.postMessage(params); return worker; } else { // We can't use inline workers, so run the worker JS on the main thread. (function() { var __DUMMY_OBJECT__ = {}; // Proxy to Worker.onmessage var postMessage = function(result) { callback(result); }; // Bind the worker to this dummy object. The worker will run // in this scope. eval('var self=__DUMMY_OBJECT__;\n' + js); // Proxy to Worker.postMessage __DUMMY_OBJECT__.onmessage({ data: params }); })(); // Return a dummy Worker. return { terminate: function(){} }; } };
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ window.imagelib = imagelib; //#ECHO })();
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ imagelib.loadImageResources = function(images, callback) { var imageResources = {}; var checkForCompletion = function() { for (var id in images) { if (!(id in imageResources)) return; } (callback || function(){})(imageResources); callback = null; }; for (var id in images) { var img = document.createElement('img'); img.src = images[id]; (function(img, id) { img.onload = function() { imageResources[id] = img; checkForCompletion(); }; img.onerror = function() { imageResources[id] = null; checkForCompletion(); } })(img, id); } }; imagelib.loadFromUri = function(uri, callback) { callback = callback || function(){}; var img = document.createElement('img'); img.src = uri; img.onload = function() { callback(img); }; img.onerror = function() { callback(null); } }; imagelib.toDataUri = function(img) { var canvas = document.createElement('canvas'); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); return canvas.toDataURL(); };
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ studio.checkBrowser = function() { var chromeMatch = navigator.userAgent.match(/Chrome\/(\d+)/); var browserSupported = false; if (chromeMatch) { var chromeVersion = parseInt(chromeMatch[1], 10); if (chromeVersion >= 6) { browserSupported = true; } } if (!browserSupported) { $('<div>') .addClass('browser-unsupported-note ui-state-highlight') .attr('title', 'Your browser is not supported.') .append($('<span class="ui-icon ui-icon-alert" ' + 'style="float:left; margin:0 7px 50px 0;">')) .append($('<p>') .html('Currently only ' + '<a href="http://www.google.com/chrome">Google Chrome</a> ' + 'is recommended and supported. Your mileage may vary with ' + 'other browsers.')) .prependTo('body'); } };
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //#INSERTFILE "../../lib/jquery.ui.combobox.js" //#INSERTFILE "../../lib/jquery.ui.autocompletewithbutton.js"
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //#ECHO (function() { var studio = {};
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //#REQUIRE "fields.js" /** * This is needed due to what seems like a bug in Chrome where using drawImage * with any SVG, regardless of origin (even if it was loaded from a data URI), * marks the canvas's origin dirty flag, precluding us from accessing its pixel * data. */ var USE_CANVG = window.canvg && true; /** * Represents a form field for image values. */ studio.forms.ImageField = studio.forms.Field.extend({ constructor: function(id, params) { this.valueType_ = null; this.textParams_ = {}; this.imageParams_ = {}; this.spaceFormValues_ = {}; // cache this.base(id, params); }, createUI: function(container) { var fieldUI = this.base(container); var fieldContainer = $('.form-field-container', fieldUI); var me = this; // Set up drag+drop on the entire field container fieldUI.addClass('form-field-drop-target'); fieldUI.get(0).ondragenter = studio.forms.ImageField.makeDragenterHandler_( fieldUI); fieldUI.get(0).ondragleave = studio.forms.ImageField.makeDragleaveHandler_( fieldUI); fieldUI.get(0).ondragover = studio.forms.ImageField.makeDragoverHandler_( fieldUI); fieldUI.get(0).ondrop = studio.forms.ImageField.makeDropHandler_(fieldUI, function(evt) { studio.forms.ImageField.loadImageFromFileList(evt.dataTransfer.files, function(ret) { if (!ret) return; me.setValueType_('image'); me.imageParams_ = ret; me.valueFilename_ = ret.name; me.renderValueAndNotifyChanged_(); }); }); // Create radio buttons this.el_ = $('<div>') .attr('id', this.getHtmlId()) .addClass('.form-field-buttonset') .appendTo(fieldContainer); var types; if (this.params_.imageOnly) { types = [ 'image', 'Select Image' ]; } else { types = [ 'image', 'Image', 'clipart', 'Clipart', 'text', 'Text' ]; } var typeEls = {}; for (var i = 0; i < types.length / 2; i++) { $('<input>') .attr({ type: 'radio', name: this.getHtmlId(), id: this.getHtmlId() + '-' + types[i * 2], value: types[i * 2] }) .appendTo(this.el_); typeEls[types[i * 2]] = $('<label>') .attr('for', this.getHtmlId() + '-' + types[i * 2]) .text(types[i * 2 + 1]) .appendTo(this.el_); } this.el_.buttonset(); // Prepare UI for the 'image' type this.fileEl_ = $('<input>') .addClass('form-image-hidden-file-field') .attr({ id: this.getHtmlId(), type: 'file', accept: 'image/*' }) .change(function() { studio.forms.ImageField.loadImageFromFileList(me.fileEl_.get(0).files, function(ret) { if (!ret) return; me.setValueType_('image'); me.imageParams_ = ret; me.valueFilename_ = ret.name; me.renderValueAndNotifyChanged_(); }); }) .appendTo(this.el_); typeEls.image.click(function(evt) { me.fileEl_.trigger('click'); me.setValueType_(null); me.renderValueAndNotifyChanged_(); evt.preventDefault(); return false; }); // Prepare UI for the 'clipart' type if (!this.params_.imageOnly) { var clipartParamsEl = $('<div>') .addClass('form-image-type-params form-image-type-params-clipart') .hide() .appendTo(this.el_); var clipartListEl = $('<div>') .addClass('form-image-clipart-list') .appendTo(clipartParamsEl); for (var i = 0; i < studio.forms.ImageField.clipartList_.length; i++) { var clipartSrc = 'res/clipart/' + studio.forms.ImageField.clipartList_[i]; $('<img>') .addClass('form-image-clipart-item') .attr('src', clipartSrc) .click(function(clipartSrc) { return function() { me.loadClipart_(clipartSrc); }; }(clipartSrc)) .appendTo(clipartListEl); } var clipartAttributionEl = $('<div>') .addClass('form-image-clipart-attribution') .html([ 'Clipart courtesy of ', '<a href="http://www.yay.se/2011/02/', 'native-android-icons-in-vector-format/"', ' target="_blank">Olof Brickarp</a>.' ].join('')) .appendTo(clipartParamsEl); typeEls.clipart.click(function(evt) { me.setValueType_('clipart'); me.renderValueAndNotifyChanged_(); }); // Prepare UI for the 'text' type var textParamsEl = $('<div>') .addClass( 'form-subform ' + 'form-image-type-params ' + 'form-image-type-params-text') .hide() .appendTo(this.el_); this.textForm_ = new studio.forms.Form( this.form_.id_ + '-' + this.id_ + '-textform', { onChange: function() { var values = me.textForm_.getValues(); me.textParams_.text = values['text']; me.textParams_.fontStack = values['font'] ? values['font'] : 'sans-serif'; me.valueFilename_ = values['text']; me.tryLoadWebFont_(); me.renderValueAndNotifyChanged_(); }, fields: [ new studio.forms.TextField('text', { title: 'Text', }), new studio.forms.AutocompleteTextField('font', { title: 'Font', items: studio.forms.ImageField.fontList_ }) ] }); this.textForm_.createUI(textParamsEl); typeEls.text.click(function(evt) { me.setValueType_('text'); me.renderValueAndNotifyChanged_(); }); } // Create spacing subform if (!this.params_.noTrimForm) { this.spaceFormValues_ = {}; this.spaceForm_ = new studio.forms.Form( this.form_.id_ + '-' + this.id_ + '-spaceform', { onChange: function() { me.spaceFormValues_ = me.spaceForm_.getValues(); me.renderValueAndNotifyChanged_(); }, fields: [ new studio.forms.BooleanField('trim', { title: 'Trim', defaultValue: this.params_.defaultValueTrim || false, offText: 'Don\'t Trim', onText: 'Trim' }), new studio.forms.RangeField('pad', { title: 'Padding', defaultValue: 0, min: -0.1, max: 0.5, // 1/2 of min(width, height) step: 0.05, textFn: function(v) { return (v * 100) + '%'; } }), ] }); this.spaceForm_.createUI($('<div>') .addClass('form-subform') .appendTo(fieldContainer)); this.spaceFormValues_ = this.spaceForm_.getValues(); } else { this.spaceFormValues_ = {}; } // Create image preview element if (!this.params_.noPreview) { this.imagePreview_ = $('<canvas>') .addClass('form-image-preview') .hide() .appendTo(fieldContainer.parent()); } }, tryLoadWebFont_: function(force) { var desiredFont = this.textForm_.getValues()['font']; if (this.loadedWebFont_ == desiredFont) { return; } var me = this; if (!force) { if (this.tryLoadWebFont_.timeout_) { clearTimeout(this.tryLoadWebFont_.timeout_); } this.tryLoadWebFont_.timeout_ = setTimeout(function() { me.tryLoadWebFont_(true); }, 100); return; } this.loadedWebFont_ = desiredFont; var webFontNodeId = this.form_.id_ + '-' + this.id_ + '-__webfont-stylesheet__'; var $webFontNode = $('#' + webFontNodeId); if (!$webFontNode.length) { $webFontNode = $('<link>') .attr('id', webFontNodeId) .attr('rel', 'stylesheet') .appendTo('head'); } $webFontNode.attr( 'href', 'http://fonts.googleapis.com/css?family=' + encodeURIComponent(desiredFont)); }, setValueType_: function(type) { this.valueType_ = type; $('label', this.el_).removeClass('ui-state-active'); $('.form-image-type-params', this.el_).hide(); if (type) { $('label[for=' + this.getHtmlId() + '-' + type + ']').addClass('ui-state-active'); $('.form-image-type-params-' + type, this.el_).show(); } }, loadClipart_: function(clipartSrc) { var useCanvg = USE_CANVG && clipartSrc.match(/\.svg$/); $('img.form-image-clipart-item', this.el_).removeClass('selected'); $('img[src="' + clipartSrc + '"]').addClass('selected'); this.imageParams_ = { canvgSvgUri: useCanvg ? clipartSrc : null, uri: useCanvg ? null : clipartSrc }; this.clipartSrc_ = clipartSrc; this.valueFilename_ = clipartSrc.match(/[^/]+$/)[0]; this.renderValueAndNotifyChanged_(); }, clearValue: function() { this.valueType_ = null; this.valueFilename_ = null; this.valueCtx_ = null; this.fileEl_.val(''); if (this.imagePreview_) { this.imagePreview_.hide(); } }, getValue: function() { return { ctx: this.valueCtx_, name: this.valueFilename_ }; }, // this function is asynchronous renderValueAndNotifyChanged_: function() { if (!this.valueType_) { this.valueCtx_ = null; } var me = this; // Render the base image (text, clipart, or image) switch (this.valueType_) { case 'image': case 'clipart': if (this.imageParams_.canvgSvgText || this.imageParams_.canvgSvgUri) { var canvas = document.createElement('canvas'); var size = { w: 800, h: 800 }; canvas.className = 'offscreen'; canvas.width = size.w; canvas.height = size.h; document.body.appendChild(canvas); canvg( canvas, this.imageParams_.canvgSvgText || this.imageParams_.canvgSvgUri, { scaleWidth: size.w, scaleHeight: size.h, ignoreMouse: true, ignoreAnimation: true, ignoreDimensions: true, ignoreClear: true } ); continue_(canvas.getContext('2d'), size); document.body.removeChild(canvas); } else if (this.imageParams_.uri) { imagelib.loadFromUri(this.imageParams_.uri, function(img) { var size = { w: img.naturalWidth, h: img.naturalHeight }; var ctx = imagelib.drawing.context(size); imagelib.drawing.copy(ctx, img, size); continue_(ctx, size); }); } break; case 'text': var size = { w: 4800, h: 1600 }; var textHeight = size.h * 0.75; var ctx = imagelib.drawing.context(size); var text = this.textParams_.text || ''; text = ' ' + text + ' '; ctx.fillStyle = '#000'; ctx.font = 'bold ' + textHeight + 'px/' + size.h + 'px ' + (this.textParams_.fontStack || 'sans-serif'); ctx.textBaseline = 'alphabetic'; ctx.fillText(text, 0, textHeight); size.w = Math.ceil(Math.min(ctx.measureText(text).width, size.w) || size.w); continue_(ctx, size); break; default: me.form_.notifyChanged_(me); } function continue_(srcCtx, srcSize) { // Apply trimming if (me.spaceFormValues_['trim']) { if (me.trimWorker_) { me.trimWorker_.terminate(); } me.trimWorker_ = imagelib.drawing.getTrimRect(srcCtx, srcSize, 1, function(trimRect) { continue2_(srcCtx, srcSize, trimRect); }); } else { continue2_(srcCtx, srcSize, /*trimRect*/{ x: 0, y: 0, w: srcSize.w, h: srcSize.h }); } } function continue2_(srcCtx, srcSize, trimRect) { // If trimming, add a tiny bit of padding to fix artifacts around the // edges. var extraPadding = me.spaceFormValues_['trim'] ? 0.001 : 0; if (trimRect.x == 0 && trimRect.y == 0 && trimRect.w == srcSize.w && trimRect.h == srcSize.h) { extraPadding = 0; } var padPx = Math.round(((me.spaceFormValues_['pad'] || 0) + extraPadding) * Math.min(trimRect.w, trimRect.h)); var targetRect = { x: padPx, y: padPx, w: trimRect.w, h: trimRect.h }; var outCtx = imagelib.drawing.context({ w: trimRect.w + padPx * 2, h: trimRect.h + padPx * 2 }); // TODO: replace with a simple draw() as the centering is useless imagelib.drawing.drawCenterInside(outCtx, srcCtx, targetRect, trimRect); // Set the final URI value and show a preview me.valueCtx_ = outCtx; if (me.imagePreview_) { me.imagePreview_.attr('width', outCtx.canvas.width); me.imagePreview_.attr('height', outCtx.canvas.height); var previewCtx = me.imagePreview_.get(0).getContext('2d'); previewCtx.drawImage(outCtx.canvas, 0, 0); me.imagePreview_.show(); } me.form_.notifyChanged_(me); } }, serializeValue: function() { return { type: this.valueType_, space: this.spaceForm_.getValuesSerialized(), clipart: (this.valueType_ == 'clipart') ? this.clipartSrc_ : null, text: (this.valueType_ == 'text') ? this.textForm_.getValuesSerialized() : null }; }, deserializeValue: function(o) { if (o.type) { this.setValueType_(o.type); } if (o.space) { this.spaceForm_.setValuesSerialized(o.space); this.spaceFormValues_ = this.spaceForm_.getValues(); } if (o.clipart && this.valueType_ == 'clipart') { this.loadClipart_(o.clipart); } if (o.text && this.valueType_ == 'text') { this.textForm_.setValuesSerialized(o.text); this.tryLoadWebFont_(); } } }); studio.forms.ImageField.clipartList_ = [ 'icons/accounts.svg', 'icons/add.svg', 'icons/agenda.svg', 'icons/all_friends.svg', 'icons/attachment.svg', 'icons/back.svg', 'icons/backspace.svg', 'icons/barcode.svg', 'icons/battery_charging.svg', 'icons/bell.svg', 'icons/block.svg', 'icons/block_user.svg', 'icons/bookmarks.svg', 'icons/camera.svg', 'icons/circle_arrow.svg', 'icons/clock.svg', 'icons/compass.svg', 'icons/cross.svg', 'icons/cross2.svg', 'icons/directions.svg', 'icons/down_arrow.svg', 'icons/edit.svg', 'icons/expand_arrows.svg', 'icons/export.svg', 'icons/eye.svg', 'icons/gallery.svg', 'icons/group.svg', 'icons/happy_droid.svg', 'icons/help.svg', 'icons/home.svg', 'icons/info.svg', 'icons/key.svg', 'icons/list.svg', 'icons/lock.svg', 'icons/mail.svg', 'icons/map.svg', 'icons/map_pin.svg', 'icons/mic.svg', 'icons/notification.svg', 'icons/phone.svg', 'icons/play_clip.svg', 'icons/plus.svg', 'icons/position.svg', 'icons/power.svg', 'icons/refresh.svg', 'icons/search.svg', 'icons/settings.svg', 'icons/share.svg', 'icons/slideshow.svg', 'icons/sort_by_size.svg', 'icons/sound_full.svg', 'icons/sound_off.svg', 'icons/star.svg', 'icons/stars_grade.svg', 'icons/stop.svg', 'icons/trashcan.svg', 'icons/usb.svg', 'icons/user.svg', 'icons/warning.svg' ]; studio.forms.ImageField.fontList_ = [ 'Helvetica', 'Arial', 'Georgia', 'Book Antiqua', 'Palatino', 'Courier', 'Courier New', 'Webdings', 'Wingdings' ]; /** * Loads the first valid image from a FileList (e.g. drag + drop source), as a data URI. This method * will throw an alert() in case of errors and call back with null. * @param {FileList} fileList The FileList to load. * @param {Function} callback The callback to fire once image loading is done (or fails). * @return Returns an object containing 'uri' or 'canvgSvgText' fields representing * the loaded image. There will also be a 'name' field indicating the file name, if one * is available. */ studio.forms.ImageField.loadImageFromFileList = function(fileList, callback) { fileList = fileList || []; var file = null; for (var i = 0; i < fileList.length; i++) { if (studio.forms.ImageField.isValidFile_(fileList[i])) { file = fileList[i]; break; } } if (!file) { alert('Please choose a valid image file (PNG, JPG, GIF, SVG, etc.)'); callback(null); return; } var useCanvg = USE_CANVG && file.type == 'image/svg+xml'; var fileReader = new FileReader(); // Closure to capture the file information. fileReader.onload = function(e) { callback({ uri: useCanvg ? null : e.target.result, canvgSvgText: useCanvg ? e.target.result : null, name: file.name }); }; fileReader.onerror = function(e) { switch(e.target.error.code) { case e.target.error.NOT_FOUND_ERR: alert('File not found!'); break; case e.target.error.NOT_READABLE_ERR: alert('File is not readable'); break; case e.target.error.ABORT_ERR: break; // noop default: alert('An error occurred reading this file.'); } callback(null); }; /*fileReader.onprogress = function(e) { $('#read-progress').css('visibility', 'visible'); // evt is an ProgressEvent. if (e.lengthComputable) { $('#read-progress').val(Math.round((e.loaded / e.total) * 100)); } else { $('#read-progress').removeAttr('value'); } };*/ fileReader.onabort = function(e) { alert('File read cancelled'); callback(null); }; /*fileReader.onloadstart = function(e) { $('#read-progress').css('visibility', 'visible'); };*/ if (useCanvg) fileReader.readAsText(file); else fileReader.readAsDataURL(file); }; /** * Determines whether or not the given File is a valid value for the image. * 'File' here is a File using the W3C File API. * @private * @param {File} file Describe this parameter */ studio.forms.ImageField.isValidFile_ = function(file) { return !!file.type.toLowerCase().match(/^image\//); }; /*studio.forms.ImageField.isValidFile_.allowedTypes = { 'image/png': true, 'image/jpeg': true, 'image/svg+xml': true, 'image/gif': true, 'image/vnd.adobe.photoshop': true };*/ studio.forms.ImageField.makeDropHandler_ = function(el, handler) { return function(evt) { $(el).removeClass('drag-hover'); handler(evt); }; }; studio.forms.ImageField.makeDragoverHandler_ = function(el) { return function(evt) { el = $(el).get(0); if (el._studio_frm_dragtimeout_) { window.clearTimeout(el._studio_frm_dragtimeout_); el._studio_frm_dragtimeout_ = null; } evt.dataTransfer.dropEffect = 'link'; evt.preventDefault(); }; }; studio.forms.ImageField.makeDragenterHandler_ = function(el) { return function(evt) { el = $(el).get(0); if (el._studio_frm_dragtimeout_) { window.clearTimeout(el._studio_frm_dragtimeout_); el._studio_frm_dragtimeout_ = null; } $(el).addClass('drag-hover'); evt.preventDefault(); }; }; studio.forms.ImageField.makeDragleaveHandler_ = function(el) { return function(evt) { el = $(el).get(0); if (el._studio_frm_dragtimeout_) window.clearTimeout(el._studio_frm_dragtimeout_); el._studio_frm_dragtimeout_ = window.setTimeout(function() { $(el).removeClass('drag-hover'); }, 100); }; };
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ studio.hash = {}; studio.hash.boundFormOldOnChange_ = null; studio.hash.boundForm_ = null; studio.hash.currentParams_ = {}; studio.hash.currentHash_ = null; // The URI encoded, currently loaded state. studio.hash.bindFormToDocumentHash = function(form) { if (!studio.hash.boundForm_) { // Checks for changes in the document hash // and reloads the form if necessary. var hashChecker_ = function() { // Don't use document.location.hash because it automatically // resolves URI-escaped entities. var docHash = studio.hash.paramsToHash(studio.hash.hashToParams( (document.location.href.match(/#.*/) || [''])[0])); if (docHash != studio.hash.currentHash_) { var newHash = docHash; var newParams = studio.hash.hashToParams(newHash); studio.hash.onHashParamsChanged_(newParams); studio.hash.currentParams_ = newParams; studio.hash.currentHash_ = newHash; }; window.setTimeout(hashChecker_, 100); } window.setTimeout(hashChecker_, 0); } if (studio.hash.boundFormOldOnChange_ && studio.hash.boundForm_) { studio.hash.boundForm_.onChange = studio.hash.boundFormOldOnChange_; } studio.hash.boundFormOldOnChange_ = form.onChange; studio.hash.boundForm_ = form; var formChangeTimeout = null; studio.hash.boundForm_.onChange = function() { if (formChangeTimeout) { window.clearTimeout(formChangeTimeout); } formChangeTimeout = window.setTimeout(function() { studio.hash.onFormChanged_(); }, 500); (studio.hash.boundFormOldOnChange_ || function(){}).apply(form, arguments); }; }; studio.hash.onHashParamsChanged_ = function(newParams) { if (studio.hash.boundForm_) { studio.hash.boundForm_.setValuesSerialized(newParams); } }; studio.hash.onFormChanged_ = function() { if (studio.hash.boundForm_) { // We set this to prevent feedback in the hash checker. studio.hash.currentParams_ = studio.hash.boundForm_.getValuesSerialized(); studio.hash.currentHash_ = studio.hash.paramsToHash( studio.hash.currentParams_); document.location.hash = studio.hash.currentHash_; } }; studio.hash.hashToParams = function(hash) { var params = {}; hash = hash.replace(/^[?#]/, ''); var pairs = hash.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('=', 2); // Most of the time path == key, but for objects like a.b=1, we need to // descend into the hierachy. var path = parts[0] ? decodeURIComponent(parts[0]) : parts[0]; var val = parts[1] ? decodeURIComponent(parts[1]) : parts[1]; var pathArr = path.split('.'); var obj = params; for (var j = 0; j < pathArr.length - 1; j++) { obj[pathArr[j]] = obj[pathArr[j]] || {}; obj = obj[pathArr[j]]; } var key = pathArr[pathArr.length - 1]; if (key in obj) { // Handle array values. if (obj[key] && obj[key].splice) { obj[key].push(val); } else { obj[key] = [obj[key], val]; } } else { obj[key] = val; } } return params; }; studio.hash.paramsToHash = function(params, prefix) { var hashArr = []; var keyPath_ = function(k) { return encodeURIComponent((prefix ? prefix + '.' : '') + k); }; var pushKeyValue_ = function(k, v) { if (v === false) v = 0; if (v === true) v = 1; hashArr.push(keyPath_(k) + '=' + encodeURIComponent(v.toString())); }; for (var key in params) { var val = params[key]; if (val === undefined || val === null) { continue; } if (typeof val == 'object') { if (val.splice && val.length) { // Arrays for (var i = 0; i < val.length; i++) { pushKeyValue_(key, val[i]); } } else { // Objects hashArr.push(studio.hash.paramsToHash(val, keyPath_(key))); } } else { // All other values pushKeyValue_(key, val); } } return hashArr.join('&'); };
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //#REQUIRE "includes.js" //#REQUIRE "forms.js" /** * Represents a form field and its associated UI elements. This should be * broken out into a more MVC-like architecture in the future. */ studio.forms.Field = Base.extend({ /** * Instantiates a new field with the given ID and parameters. * @constructor */ constructor: function(id, params) { this.id_ = id; this.params_ = params; }, /** * Sets the form owner of the field. Internally called by * {@link studio.forms.Form}. * @private * @param {studio.forms.Form} form The owner form. */ setForm_: function(form) { this.form_ = form; }, /** * Returns a complete ID. * @type String */ getLongId: function() { return this.form_.id_ + '-' + this.id_; }, /** * Returns the ID for the form's UI element (or container). * @type String */ getHtmlId: function() { return '_frm-' + this.getLongId(); }, /** * Generates the UI elements for a form field container. Not very portable * outside the Asset Studio UI. Intended to be overriden by descendents. * @private * @param {HTMLElement} container The destination element to contain the * field. */ createUI: function(container) { container = $(container); return $('<div>') .addClass('form-field-outer') .append( $('<label>') .attr('for', this.getHtmlId()) .text(this.params_.title) .append($('<div>') .addClass('form-field-help-text') .css('display', this.params_.helpText ? '' : 'none') .html(this.params_.helpText)) ) .append( $('<div>') .addClass('form-field-container') ) .appendTo(container); } }); studio.forms.TextField = studio.forms.Field.extend({ createUI: function(container) { var fieldContainer = $('.form-field-container', this.base(container)); var me = this; this.el_ = $('<input>') .addClass('form-text ui-widget ui-widget-content ' + 'ui-autocomplete-input ui-corner-all') .attr('type', 'text') .val(this.getValue()) .bind('change', function() { me.setValue($(this).val(), true); }) .bind('keydown change', function() { var inputEl = this; var oldVal = me.getValue(); window.setTimeout(function() { var newVal = $(inputEl).val(); if (oldVal != newVal) { me.setValue(newVal, true); } }, 0); }) .appendTo(fieldContainer); }, getValue: function() { var value = this.value_; if (typeof value != 'string') { value = this.params_.defaultValue || ''; } return value; }, setValue: function(val, pauseUi) { this.value_ = val; if (!pauseUi) { $(this.el_).val(val); } this.form_.notifyChanged_(this); }, serializeValue: function() { return this.getValue(); }, deserializeValue: function(s) { this.setValue(s); } }); studio.forms.AutocompleteTextField = studio.forms.Field.extend({ createUI: function(container) { var fieldContainer = $('.form-field-container', this.base(container)); var me = this; this.el_ = $('<input>') .attr('type', 'text') .val(this.getValue()) .bind('keydown change', function() { var inputEl = this; window.setTimeout(function() { me.setValue($(inputEl).val(), true); }, 0); }) .appendTo(fieldContainer); this.el_.autocompletewithbutton({ source: this.params_.items || [], delay: 0, minLength: 0, selected: function(evt, val) { me.setValue(val, true); } }); }, getValue: function() { var value = this.value_; if (typeof value != 'string') { value = this.params_.defaultValue || ''; } return value; }, setValue: function(val, pauseUi) { this.value_ = val; if (!pauseUi) { $(this.el_).val(val); } this.form_.notifyChanged_(this); }, serializeValue: function() { return this.getValue(); }, deserializeValue: function(s) { this.setValue(s); } }); studio.forms.ColorField = studio.forms.Field.extend({ createUI: function(container) { var fieldContainer = $('.form-field-container', this.base(container)); var me = this; this.el_ = $('<div>') .addClass('form-color') .attr('id', this.getHtmlId()) .append($('<div>') .addClass('form-color-preview') .css('background-color', this.getValue().color) ) .button({ label: null, icons: { secondary: 'ui-icon-carat-1-s' }}) .appendTo(fieldContainer); this.el_.ColorPicker({ color: this.getValue().color, onChange: function(hsb, hex, rgb) { me.setValue({ color:'#' + hex }, true); } }); if (this.params_.alpha) { this.alphaEl_ = $('<div>') .addClass('form-color-alpha') .slider({ min: 0, max: 100, range: 'min', value: this.getValue().alpha, slide: function(evt, ui) { me.setValue({ alpha: ui.value }, true); } }) .appendTo(fieldContainer); } }, getValue: function() { var color = this.value_ || this.params_.defaultValue || '#000000'; if (/^([0-9a-f]{6}|[0-9a-f]{3})$/i.test(color)) { color = '#' + color; } var alpha = this.alpha_; if (typeof alpha != 'number') { alpha = this.params_.defaultAlpha; if (typeof alpha != 'number') alpha = 100; } return { color: color, alpha: alpha }; }, setValue: function(val, pauseUi) { val = val || {}; if ('color' in val) { this.value_ = val.color; } if ('alpha' in val) { this.alpha_ = val.alpha; } var computedValue = this.getValue(); $('.form-color-preview', this.el_) .css('background-color', computedValue.color); if (!pauseUi) { $(this.el_).ColorPickerSetColor(computedValue.color); if (this.alphaEl_) { $(this.alphaEl_).slider('value', computedValue.alpha); } } this.form_.notifyChanged_(this); }, serializeValue: function() { var computedValue = this.getValue(); return computedValue.color.replace(/^#/, '') + ',' + computedValue.alpha; }, deserializeValue: function(s) { var val = {}; var arr = s.split(',', 2); if (arr.length >= 1) { val.color = arr[0]; } if (arr.length >= 2) { val.alpha = parseInt(arr[1], 10); } this.setValue(val); } }); studio.forms.EnumField = studio.forms.Field.extend({ createUI: function(container) { var fieldContainer = $('.form-field-container', this.base(container)); var me = this; if (this.params_.buttons) { this.el_ = $('<div>') .attr('id', this.getHtmlId()) .addClass('.form-field-buttonset') .appendTo(fieldContainer); for (var i = 0; i < this.params_.options.length; i++) { var option = this.params_.options[i]; $('<input>') .attr({ type: 'radio', name: this.getHtmlId(), id: this.getHtmlId() + '-' + option.id, value: option.id }) .change(function() { me.setValueInternal_($(this).val(), true); }) .appendTo(this.el_); $('<label>') .attr('for', this.getHtmlId() + '-' + option.id) .html(option.title) .appendTo(this.el_); } this.setValueInternal_(this.getValue()); this.el_.buttonset(); } else { this.el_ = $('<select>') .attr('id', this.getHtmlId()) .change(function() { me.setValueInternal_($(this).val(), true); }) .appendTo(fieldContainer); for (var i = 0; i < this.params_.options.length; i++) { var option = this.params_.options[i]; $('<option>') .attr('value', option.id) .text(option.title) .appendTo(this.el_); } this.el_.combobox({ selected: function(evt, data) { me.setValueInternal_(data.item.value, true); me.form_.notifyChanged_(me); } }); this.setValueInternal_(this.getValue()); } }, getValue: function() { var value = this.value_; if (value === undefined) { value = this.params_.defaultValue || this.params_.options[0].id; } return value; }, setValue: function(val, pauseUi) { this.setValueInternal_(val, pauseUi); }, setValueInternal_: function(val, pauseUi) { // Note, this needs to be its own function because setValue gets // overridden in BooleanField and we need access to this method // from createUI. this.value_ = val; if (!pauseUi) { if (this.params_.buttons) { $('input', this.el_).each(function(i, el) { $(el).attr('checked', $(el).val() == val); }); $(this.el_).buttonset('refresh'); } else { this.el_.val(val); } } this.form_.notifyChanged_(this); }, serializeValue: function() { return this.getValue(); }, deserializeValue: function(s) { this.setValue(s); } }); studio.forms.BooleanField = studio.forms.EnumField.extend({ constructor: function(id, params) { params.options = [ { id: '1', title: params.onText || 'Yes' }, { id: '0', title: params.offText || 'No' } ]; params.defaultValue = params.defaultValue ? '1' : '0'; params.buttons = true; this.base(id, params); }, getValue: function() { return this.base() == '1'; }, setValue: function(val, pauseUi) { this.base(val ? '1' : '0', pauseUi); }, serializeValue: function() { return this.getValue() ? '1' : '0'; }, deserializeValue: function(s) { this.setValue(s == '1'); } }); studio.forms.RangeField = studio.forms.Field.extend({ createUI: function(container) { var fieldContainer = $('.form-field-container', this.base(container)); var me = this; this.el_ = $('<div>') .addClass('form-range') .slider({ min: this.params_.min || 0, max: this.params_.max || 100, step: this.params_.step || 1, range: 'min', value: this.getValue(), slide: function(evt, ui) { me.setValue(ui.value, true); } }) .appendTo(fieldContainer); if (this.params_.textFn || this.params_.showText) { this.params_.textFn = this.params_.textFn || function(d){ return d; }; this.textEl_ = $('<div>') .addClass('form-range-text') .text(this.params_.textFn(this.getValue())) .appendTo(fieldContainer); } }, getValue: function() { var value = this.value_; if (typeof value != 'number') { value = this.params_.defaultValue; if (typeof value != 'number') value = 0; } return value; }, setValue: function(val, pauseUi) { this.value_ = val; if (!pauseUi) { $(this.el_).slider('value', val); } if (this.textEl_) { this.textEl_.text(this.params_.textFn(val)); } this.form_.notifyChanged_(this); }, serializeValue: function() { return this.getValue().toString(); }, deserializeValue: function(s) { this.setValue(Number(s)); // don't use parseInt nor parseFloat } });
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ studio.util = {}; studio.util.getMultBaseMdpi = function(density) { switch (density) { case 'xhdpi': return 2.00; case 'hdpi': return 1.50; case 'mdpi': return 1.00; case 'ldpi': return 0.75; } return 1.0; }; studio.util.mult = function(s, mult) { var d = {}; for (k in s) { d[k] = s[k] * mult; } return d; }; studio.util.multRound = function(s, mult) { var d = {}; for (k in s) { d[k] = Math.round(s[k] * mult); } return d; };
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ window.studio = studio; //#ECHO })();
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ studio.ui = {}; studio.ui.createImageOutputGroup = function(params) { return $('<div>') .addClass('out-image-group') .append($('<div>') .addClass('label') .text(params.label)) .appendTo(params.container); }; studio.ui.createImageOutputSlot = function(params) { return $('<div>') .addClass('out-image-block') .append($('<div>') .addClass('label') .text(params.label)) .append($('<img>') .addClass('out-image') .attr('id', params.id)) .appendTo(params.container); }; studio.ui.drawImageGuideRects = function(ctx, size, guides) { guides = guides || []; ctx.save(); ctx.globalAlpha = 0.5; ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, size.w, size.h); ctx.globalAlpha = 1.0; var guideColors = studio.ui.drawImageGuideRects.guideColors_; for (var i = 0; i < guides.length; i++) { ctx.strokeStyle = guideColors[(i - 1) % guideColors.length]; ctx.strokeRect(guides[i].x + 0.5, guides[i].y + 0.5, guides[i].w - 1, guides[i].h - 1); } ctx.restore(); }; studio.ui.drawImageGuideRects.guideColors_ = [ '#f00' ];
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ studio.zip = {}; studio.zip.createDownloadifyZipButton = function(element, options) { // TODO: badly needs to be documented :-) var zipperHandle = { fileSpecs_: [] }; options = options || {}; options.swf = options.swf || 'lib/downloadify/media/downloadify.swf'; options.downloadImage = options.downloadImage || 'images/download-zip-button.png'; options.width = options.width || 133; options.height = options.height || 30; options.dataType = 'base64'; options.onError = options.onError || function() { if (zipperHandle.fileSpecs_.length) alert('There was an error downloading the .zip'); }; // Zip file data and filename generator functions. options.filename = function() { return zipperHandle.zipFilename_ || 'output.zip'; }; options.data = function() { if (!zipperHandle.fileSpecs_.length) return ''; var zip = new JSZip(); for (var i = 0; i < zipperHandle.fileSpecs_.length; i++) { var fileSpec = zipperHandle.fileSpecs_[i]; if (fileSpec.base64data) zip.add(fileSpec.name, fileSpec.base64data, {base64:true}); else if (fileSpec.textData) zip.add(fileSpec.name, fileSpec.textData); } return zip.generate(); }; var downloadifyHandle; if (window.Downloadify) { downloadifyHandle = Downloadify.create($(element).get(0), options); } //downloadifyHandle.disable(); // Set up zipper control functions zipperHandle.setZipFilename = function(zipFilename) { zipperHandle.zipFilename_ = zipFilename; }; zipperHandle.clear = function() { zipperHandle.fileSpecs_ = []; //downloadifyHandle.disable(); }; zipperHandle.add = function(spec) { zipperHandle.fileSpecs_.push(spec); //downloadifyHandle.enable(); }; return zipperHandle; };
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ studio.forms = {}; /** * Class defining a data entry form for use in the Asset Studio. */ studio.forms.Form = Base.extend({ /** * Creates a new form with the given parameters. * @constructor * @param {Function} [params.onChange] A function * @param {Array} [params.inputs] A list of inputs */ constructor: function(id, params) { this.id_ = id; this.params_ = params; this.fields_ = params.fields; this.pauseNotify_ = false; for (var i = 0; i < this.fields_.length; i++) { this.fields_[i].setForm_(this); } this.onChange = this.params_.onChange || function(){}; }, /** * Creates the user interface for the form in the given container. * @private * @param {HTMLElement} container The container node for the form UI. */ createUI: function(container) { for (var i = 0; i < this.fields_.length; i++) { var field = this.fields_[i]; field.createUI(container); } }, /** * Notifies that the form contents have changed; * @private */ notifyChanged_: function(field) { if (this.pauseNotify_) { return; } this.onChange(field); }, /** * Returns the current values of the form fields, as an object. * @type Object */ getValues: function() { var values = {}; for (var i = 0; i < this.fields_.length; i++) { var field = this.fields_[i]; values[field.id_] = field.getValue(); } return values; }, /** * Returns all available serialized values of the form fields, as an object. * All values in the returned object are either strings or objects. * @type Object */ getValuesSerialized: function() { var values = {}; for (var i = 0; i < this.fields_.length; i++) { var field = this.fields_[i]; var value = field.serializeValue ? field.serializeValue() : undefined; if (value !== undefined) { values[field.id_] = field.serializeValue(); } } return values; }, /** * Sets the form field values for the key/value pairs in the given object. * Values must be serialized forms of the form values. The form must be * initialized before calling this method. */ setValuesSerialized: function(serializedValues) { this.pauseNotify_ = true; for (var i = 0; i < this.fields_.length; i++) { var field = this.fields_[i]; if (field.id_ in serializedValues && field.deserializeValue) { field.deserializeValue(serializedValues[field.id_]); } } this.pauseNotify_ = false; this.notifyChanged_(null); } });
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //#INSERTFILE "../lib/base.js"
JavaScript
// A modified version of bitmap.js from http://rest-term.com/archives/2566/ var Class = { create : function() { var properties = arguments[0]; function self() { this.initialize.apply(this, arguments); } for(var i in properties) { self.prototype[i] = properties[i]; } if(!self.prototype.initialize) { self.prototype.initialize = function() {}; } return self; } }; var ConvolutionFilter = Class.create({ initialize : function(matrix, divisor, bias, separable) { this.r = (Math.sqrt(matrix.length) - 1) / 2; this.matrix = matrix; this.divisor = divisor; this.bias = bias; this.separable = separable; }, apply : function(src, dst) { var w = src.width, h = src.height; var srcData = src.data; var dstData = dst.data; var di, si, idx; var r, g, b; //if (this.separable) { // TODO: optimize if linearly separable ... may need changes to divisor // and bias calculations //} else { // Not linearly separable for(var y=0;y<h;++y) { for(var x=0;x<w;++x) { idx = r = g = b = 0; di = (y*w + x) << 2; for(var ky=-this.r;ky<=this.r;++ky) { for(var kx=-this.r;kx<=this.r;++kx) { si = (Math.max(0, Math.min(h - 1, y + ky)) * w + Math.max(0, Math.min(w - 1, x + kx))) << 2; r += srcData[si]*this.matrix[idx]; g += srcData[si + 1]*this.matrix[idx]; b += srcData[si + 2]*this.matrix[idx]; //a += srcData[si + 3]*this.matrix[idx]; idx++; } } dstData[di] = r/this.divisor + this.bias; dstData[di + 1] = g/this.divisor + this.bias; dstData[di + 2] = b/this.divisor + this.bias; //dstData[di + 3] = a/this.divisor + this.bias; dstData[di + 3] = 255; } } //} // for Firefox //dstData.forEach(function(n, i, arr) { arr[i] = n<0 ? 0 : n>255 ? 255 : n; }); } });
JavaScript
/* Base.js, version 1.1 Copyright 2006-2007, Dean Edwards License: http://www.opensource.org/licenses/mit-license.php */ var Base = function() { // dummy }; Base.extend = function(_instance, _static) { // subclass var extend = Base.prototype.extend; // build the prototype Base._prototyping = true; var proto = new this; extend.call(proto, _instance); delete Base._prototyping; // create the wrapper for the constructor function //var constructor = proto.constructor.valueOf(); //-dean var constructor = proto.constructor; var klass = proto.constructor = function() { if (!Base._prototyping) { if (this._constructing || this.constructor == klass) { // instantiation this._constructing = true; constructor.apply(this, arguments); delete this._constructing; } else if (arguments[0] != null) { // casting return (arguments[0].extend || extend).call(arguments[0], proto); } } }; // build the class interface klass.ancestor = this; klass.extend = this.extend; klass.forEach = this.forEach; klass.implement = this.implement; klass.prototype = proto; klass.toString = this.toString; klass.valueOf = function(type) { //return (type == "object") ? klass : constructor; //-dean return (type == "object") ? klass : constructor.valueOf(); }; extend.call(klass, _static); // class initialisation if (typeof klass.init == "function") klass.init(); return klass; }; Base.prototype = { extend: function(source, value) { if (arguments.length > 1) { // extending with a name/value pair var ancestor = this[source]; if (ancestor && (typeof value == "function") && // overriding a method? // the valueOf() comparison is to avoid circular references (!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) && /\bbase\b/.test(value)) { // get the underlying method var method = value.valueOf(); // override value = function() { var previous = this.base || Base.prototype.base; this.base = ancestor; var returnValue = method.apply(this, arguments); this.base = previous; return returnValue; }; // point to the underlying method value.valueOf = function(type) { return (type == "object") ? value : method; }; value.toString = Base.toString; } this[source] = value; } else if (source) { // extending with an object literal var extend = Base.prototype.extend; // if this object has a customised extend method then use it if (!Base._prototyping && typeof this != "function") { extend = this.extend || extend; } var proto = {toSource: null}; // do the "toString" and other methods manually var hidden = ["constructor", "toString", "valueOf"]; // if we are prototyping then include the constructor var i = Base._prototyping ? 0 : 1; while (key = hidden[i++]) { if (source[key] != proto[key]) { extend.call(this, key, source[key]); } } // copy each of the source object's properties to this object for (var key in source) { if (!proto[key]) extend.call(this, key, source[key]); } } return this; }, base: function() { // call this method from any other method to invoke that method's ancestor } }; // initialise Base = Base.extend({ constructor: function() { this.extend(arguments[0]); } }, { ancestor: Object, version: "1.1", forEach: function(object, block, context) { for (var key in object) { if (this.prototype[key] === undefined) { block.call(context, object[key], key, object); } } }, implement: function() { for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] == "function") { // if it's a function, call it arguments[i](this.prototype); } else { // add the interface using the extend method this.prototype.extend(arguments[i]); } } return this; }, toString: function() { return String(this.valueOf()); } });
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
JavaScript
/* Copyright 2010 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var TESTS_INTERACTIVE = 0x01; var TESTS_AUTOMATED = 0x02; var TESTS_ALL = TESTS_INTERACTIVE | TESTS_AUTOMATED; var g_tests = []; var g_testsByName = {}; function init() { discoverTests(); buildTestTable(); } function discoverTests() { g_testsByName = {}; if (navigator.userAgent.toLowerCase().indexOf('msie') >= 0) { // IE doesn't support enumerating custom members of window for (var i = 0; i < document.scripts.length; i++) { var scriptNode = document.scripts[i]; var scriptBody = ''; if (scriptNode.innerHTML) { scriptBody += scriptNode.innerHTML; } if (scriptNode.src) { try { var xhr = new ActiveXObject('Msxml2.XMLHTTP'); xhr.open('get', scriptNode.src, false); // false -- not async xhr.send(); scriptBody += xhr.responseText; } catch (e) {} } // parse script body for test_xx functions var possibleTests = scriptBody.match(/test_\w+/g); if (possibleTests) { for (var j = 0; j < possibleTests.length; j++) { if (possibleTests[j] in window && typeof window[possibleTests[j]] === 'function') g_testsByName[possibleTests[j]] = true; } } } } else { for (var f in window) { if (f.substr(0, 5) == 'test_' && typeof window[f] === 'function') g_testsByName[f] = true; } } // convert into an array g_tests = []; for (var test in g_testsByName) { g_tests.push(test); } g_tests.sort(); } function buildTestTable() { var testTable = jQuery('#test-table'); for (var i = 0; i < g_tests.length; i++) { var row = jQuery('<tr id="testrow_' + g_tests[i] + '" "class="test">'); row.append(jQuery('<td class="test-number">' + (i + 1) + '</tr>')); row.append(jQuery('<td class="test-name">' + g_tests[i] + '</td>')); row.append(jQuery('<td class="test-status">&nbsp;</td>')); var runTestButton = jQuery('<input type="button" value="Run">') .click(function(testName) { return function() { enableUI(false); runSingleTest(testName, function() { enableUI(true); }); }; }(g_tests[i])); row.append(jQuery('<td class="test-actions"></td>').append(runTestButton)); var notes = []; if (window[g_tests[i]].interactive) notes.push('Interactive'); if (window[g_tests[i]].async) notes.push('Async'); row.append(jQuery('<td class="test-notes">' + (notes.join(', ') || '&nbsp;') + '</td>')); testTable.append(row); } } function clearResults() { jQuery('tr.test').removeClass('pass').removeClass('fail'); jQuery('.test-status').html('&nbsp;'); } function isEmptyObjectLiteral(o) { if (!o) return true; for (var k in o) return false; return true; } function logResult(testName, pass, message, otherInfo) { var testRow = jQuery('#testrow_' + testName); if (!testRow || !testRow.length) return; testRow.removeClass('pass').removeClass('fail'); testRow.addClass(pass ? 'pass' : 'fail'); var testStatusCell = jQuery('.test-status', testRow); message = message ? message.toString() : (pass ? 'pass' : 'fail') testStatusCell.text(message); if (!isEmptyObjectLiteral(otherInfo)) { testStatusCell.append(jQuery('<div><a href="#">[More Info]</a></div>') .click(function() { jQuery('.other-info', testStatusCell).toggle(); return false; })); var otherInfoHtml = ['<ul class="other-info" style="display: none">']; for (var k in otherInfo) { otherInfoHtml.push('<li><span>' + (k || '&nbsp;') + '</span>'); otherInfoHtml.push((otherInfo[k] || '&nbsp;') + '</li>'); } otherInfoHtml.push('</ul>'); testStatusCell.append(jQuery(otherInfoHtml.join(''))); } } function enableUI(enable) { if (enable) jQuery('input').removeAttr('disabled'); else jQuery('input').attr('disabled', true); } function runSingleTest(testName, completeFn) { completeFn = completeFn || function(){}; var testFn = window[testName]; var successFn = function() { // log result and run next test logResult(testName, true); completeFn(); }; var errorFn = function(e) { var message = ''; var otherInfo = {}; if (e.jsUnitMessage) { message = new String(e.jsUnitMessage); } else if (e.message) { message = new String(e.message); } else if (e.comment) { message = new String(e.comment); } else if (e.description) { message = new String(e.description); } // log result and run next test for (var k in e) { var val = e[k]; if (val === null) val = '<null>'; else if (typeof(e[k]) == 'undefined') val = '<undefined>'; val = val.toString(); if (k == 'stackTrace') { var MAX_LENGTH = 500; if (val.length >= MAX_LENGTH) val = val.substr(0, MAX_LENGTH - 3) + '...'; } otherInfo[k] = val; } logResult(testName, false, message, otherInfo); completeFn(); }; var runFunc = function() { if (testFn.interactive || testFn.async) { testFn.call(null, successFn, errorFn); } else { testFn.call(null); successFn(); } }; var passExceptions = document.getElementById('passexceptions').checked; if (passExceptions) { runFunc.call(); } else { try { runFunc.call(); } catch (e) { errorFn(e); } } } function runTests(type) { if (!type) type = TESTS_ALL; enableUI(false); clearResults(); var i = -1; var runNextTest = function() { i++; if (i >= g_tests.length) { enableUI(true); return; } var testName = g_tests[i]; var testFn = window[testName]; if (testFn.interactive) { if (!(type & TESTS_INTERACTIVE)) { runNextTest(); return; } } else { if (!(type & TESTS_AUTOMATED)) { runNextTest(); return; } } runSingleTest(testName, runNextTest); } runNextTest(); }
JavaScript
/** * * 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 = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>', 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<len; i++) { o.push('0'); } o.push(hex); hex = o.join(''); } return hex; }, HexToRGB = function (hex) { var hex = parseInt(((hex.indexOf('#') > -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)
JavaScript
/** * A class to parse color values * @author Stoyan Stefanov <sstoo@gmail.com> * @link http://www.phpied.com/rgb-color-parser-in-javascript/ * @license Use it if you like it */ function RGBColor(color_string) { this.ok = false; // strip any leading # if (color_string.charAt(0) == '#') { // remove # if any color_string = color_string.substr(1,6); } color_string = color_string.replace(/ /g,''); color_string = color_string.toLowerCase(); // before getting into regexps, try simple matches // and overwrite the input var simple_colors = { aliceblue: 'f0f8ff', antiquewhite: 'faebd7', aqua: '00ffff', aquamarine: '7fffd4', azure: 'f0ffff', beige: 'f5f5dc', bisque: 'ffe4c4', black: '000000', blanchedalmond: 'ffebcd', blue: '0000ff', blueviolet: '8a2be2', brown: 'a52a2a', burlywood: 'deb887', cadetblue: '5f9ea0', chartreuse: '7fff00', chocolate: 'd2691e', coral: 'ff7f50', cornflowerblue: '6495ed', cornsilk: 'fff8dc', crimson: 'dc143c', cyan: '00ffff', darkblue: '00008b', darkcyan: '008b8b', darkgoldenrod: 'b8860b', darkgray: 'a9a9a9', darkgreen: '006400', darkkhaki: 'bdb76b', darkmagenta: '8b008b', darkolivegreen: '556b2f', darkorange: 'ff8c00', darkorchid: '9932cc', darkred: '8b0000', darksalmon: 'e9967a', darkseagreen: '8fbc8f', darkslateblue: '483d8b', darkslategray: '2f4f4f', darkturquoise: '00ced1', darkviolet: '9400d3', deeppink: 'ff1493', deepskyblue: '00bfff', dimgray: '696969', dodgerblue: '1e90ff', feldspar: 'd19275', firebrick: 'b22222', floralwhite: 'fffaf0', forestgreen: '228b22', fuchsia: 'ff00ff', gainsboro: 'dcdcdc', ghostwhite: 'f8f8ff', gold: 'ffd700', goldenrod: 'daa520', gray: '808080', green: '008000', greenyellow: 'adff2f', honeydew: 'f0fff0', hotpink: 'ff69b4', indianred : 'cd5c5c', indigo : '4b0082', ivory: 'fffff0', khaki: 'f0e68c', lavender: 'e6e6fa', lavenderblush: 'fff0f5', lawngreen: '7cfc00', lemonchiffon: 'fffacd', lightblue: 'add8e6', lightcoral: 'f08080', lightcyan: 'e0ffff', lightgoldenrodyellow: 'fafad2', lightgrey: 'd3d3d3', lightgreen: '90ee90', lightpink: 'ffb6c1', lightsalmon: 'ffa07a', lightseagreen: '20b2aa', lightskyblue: '87cefa', lightslateblue: '8470ff', lightslategray: '778899', lightsteelblue: 'b0c4de', lightyellow: 'ffffe0', lime: '00ff00', limegreen: '32cd32', linen: 'faf0e6', magenta: 'ff00ff', maroon: '800000', mediumaquamarine: '66cdaa', mediumblue: '0000cd', mediumorchid: 'ba55d3', mediumpurple: '9370d8', mediumseagreen: '3cb371', mediumslateblue: '7b68ee', mediumspringgreen: '00fa9a', mediumturquoise: '48d1cc', mediumvioletred: 'c71585', midnightblue: '191970', mintcream: 'f5fffa', mistyrose: 'ffe4e1', moccasin: 'ffe4b5', navajowhite: 'ffdead', navy: '000080', oldlace: 'fdf5e6', olive: '808000', olivedrab: '6b8e23', orange: 'ffa500', orangered: 'ff4500', orchid: 'da70d6', palegoldenrod: 'eee8aa', palegreen: '98fb98', paleturquoise: 'afeeee', palevioletred: 'd87093', papayawhip: 'ffefd5', peachpuff: 'ffdab9', peru: 'cd853f', pink: 'ffc0cb', plum: 'dda0dd', powderblue: 'b0e0e6', purple: '800080', red: 'ff0000', rosybrown: 'bc8f8f', royalblue: '4169e1', saddlebrown: '8b4513', salmon: 'fa8072', sandybrown: 'f4a460', seagreen: '2e8b57', seashell: 'fff5ee', sienna: 'a0522d', silver: 'c0c0c0', skyblue: '87ceeb', slateblue: '6a5acd', slategray: '708090', snow: 'fffafa', springgreen: '00ff7f', steelblue: '4682b4', tan: 'd2b48c', teal: '008080', thistle: 'd8bfd8', tomato: 'ff6347', turquoise: '40e0d0', violet: 'ee82ee', violetred: 'd02090', wheat: 'f5deb3', white: 'ffffff', whitesmoke: 'f5f5f5', yellow: 'ffff00', yellowgreen: '9acd32' }; for (var key in simple_colors) { if (color_string == key) { color_string = simple_colors[key]; } } // emd of simple type-in colors // array of color definition objects var color_defs = [ { re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/, example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'], process: function (bits){ return [ parseInt(bits[1]), parseInt(bits[2]), parseInt(bits[3]) ]; } }, { re: /^(\w{2})(\w{2})(\w{2})$/, example: ['#00ff00', '336699'], process: function (bits){ return [ parseInt(bits[1], 16), parseInt(bits[2], 16), parseInt(bits[3], 16) ]; } }, { re: /^(\w{1})(\w{1})(\w{1})$/, example: ['#fb0', 'f0f'], process: function (bits){ return [ parseInt(bits[1] + bits[1], 16), parseInt(bits[2] + bits[2], 16), parseInt(bits[3] + bits[3], 16) ]; } } ]; // search through the definitions to find a match for (var i = 0; i < color_defs.length; i++) { var re = color_defs[i].re; var processor = color_defs[i].process; var bits = re.exec(color_string); if (bits) { channels = processor(bits); this.r = channels[0]; this.g = channels[1]; this.b = channels[2]; this.ok = true; } } // validate/cleanup values this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r); this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g); this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b); // some getters this.toRGB = function () { return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')'; } this.toHex = function () { var r = this.r.toString(16); var g = this.g.toString(16); var b = this.b.toString(16); if (r.length == 1) r = '0' + r; if (g.length == 1) g = '0' + g; if (b.length == 1) b = '0' + b; return '#' + r + g + b; } // help this.getHelpXML = function () { var examples = new Array(); // add regexps for (var i = 0; i < color_defs.length; i++) { var example = color_defs[i].example; for (var j = 0; j < example.length; j++) { examples[examples.length] = example[j]; } } // add type-in colors for (var sc in simple_colors) { examples[examples.length] = sc; } var xml = document.createElement('ul'); xml.setAttribute('id', 'rgbcolor-examples'); for (var i = 0; i < examples.length; i++) { try { var list_item = document.createElement('li'); var list_color = new RGBColor(examples[i]); var example_div = document.createElement('div'); example_div.style.cssText = 'margin: 3px; ' + 'border: 1px solid black; ' + 'background:' + list_color.toHex() + '; ' + 'color:' + list_color.toHex() ; example_div.appendChild(document.createTextNode('test')); var list_item_value = document.createTextNode( ' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex() ); list_item.appendChild(example_div); list_item.appendChild(list_item_value); xml.appendChild(list_item); } catch(e){} } return xml; } }
JavaScript
/* * canvg.js - Javascript SVG parser and renderer on Canvas * MIT Licensed * Gabe Lerner (gabelerner@gmail.com) * http://code.google.com/p/canvg/ * * Requires: rgbcolor.js - http://www.phpied.com/rgb-color-parser-in-javascript/ */ if(!window.console) { window.console = {}; window.console.log = function(str) {}; window.console.dir = function(str) {}; } // <3 IE if(!Array.indexOf){ Array.prototype.indexOf = function(obj){ for(var i=0; i<this.length; i++){ if(this[i]==obj){ return i; } } return -1; } } (function(){ // canvg(target, s) // target: canvas element or the id of a canvas element // s: svg string or url to svg file // opts: optional hash of options // ignoreMouse: true => ignore mouse events // ignoreAnimation: true => ignore animations // ignoreDimensions: true => does not try to resize canvas // ignoreClear: true => does not clear canvas // offsetX: int => draws at a x offset // offsetY: int => draws at a y offset // scaleWidth: int => scales horizontally to width // scaleHeight: int => scales vertically to height // renderCallback: function => will call the function after the first render is completed // forceRedraw: function => will call the function on every frame, if it returns true, will redraw this.canvg = function (target, s, opts) { if (typeof target == 'string') { target = document.getElementById(target); } // reuse class per canvas var svg; if (target.svg == null) { svg = build(); target.svg = svg; } else { svg = target.svg; svg.stop(); } svg.opts = opts; var ctx = target.getContext('2d'); if (s.substr(0,1) == '<') { // load from xml string svg.loadXml(ctx, s); } else { // load from url svg.load(ctx, s); } } function build() { var svg = { }; svg.FRAMERATE = 30; // globals svg.init = function(ctx) { svg.Definitions = {}; svg.Styles = {}; svg.Animations = []; svg.Images = []; svg.ctx = ctx; svg.ViewPort = new (function () { this.viewPorts = []; this.SetCurrent = function(width, height) { this.viewPorts.push({ width: width, height: height }); } this.RemoveCurrent = function() { this.viewPorts.pop(); } this.Current = function() { return this.viewPorts[this.viewPorts.length - 1]; } this.width = function() { return this.Current().width; } this.height = function() { return this.Current().height; } this.ComputeSize = function(d) { if (d != null && typeof(d) == 'number') return d; if (d == 'x') return this.width(); if (d == 'y') return this.height(); return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2); } }); } svg.init(); // images loaded svg.ImagesLoaded = function() { for (var i=0; i<svg.Images.length; i++) { if (!svg.Images[i].loaded) return false; } return true; } // trim svg.trim = function(s) { return s.replace(/^\s+|\s+$/g, ''); } // compress spaces svg.compressSpaces = function(s) { return s.replace(/[\s\r\t\n]+/gm,' '); } // ajax svg.ajax = function(url) { var AJAX; if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();} else{AJAX=new ActiveXObject('Microsoft.XMLHTTP');} if(AJAX){ AJAX.open('GET',url,false); AJAX.send(null); return AJAX.responseText; } return null; } // parse xml svg.parseXml = function(xml) { if (window.DOMParser) { var parser = new DOMParser(); return parser.parseFromString(xml, 'text/xml'); } else { xml = xml.replace(/<!DOCTYPE svg[^>]*>/, ''); var xmlDoc = new ActiveXObject('Microsoft.XMLDOM'); xmlDoc.async = 'false'; xmlDoc.loadXML(xml); return xmlDoc; } } svg.Property = function(name, value) { this.name = name; this.value = value; this.hasValue = function() { return (this.value != null && this.value != ''); } // return the numerical value of the property this.numValue = function() { if (!this.hasValue()) return 0; var n = parseFloat(this.value); if ((this.value + '').match(/%$/)) { n = n / 100.0; } return n; } this.valueOrDefault = function(def) { if (this.hasValue()) return this.value; return def; } this.numValueOrDefault = function(def) { if (this.hasValue()) return this.numValue(); return def; } /* EXTENSIONS */ var that = this; // color extensions this.Color = { // augment the current color value with the opacity addOpacity: function(opacity) { var newValue = that.value; if (opacity != null && opacity != '') { var color = new RGBColor(that.value); if (color.ok) { newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacity + ')'; } } return new svg.Property(that.name, newValue); } } // definition extensions this.Definition = { // get the definition from the definitions table getDefinition: function() { var name = that.value.replace(/^(url\()?#([^\)]+)\)?$/, '$2'); return svg.Definitions[name]; }, isUrl: function() { return that.value.indexOf('url(') == 0 }, getFillStyle: function(e) { var def = this.getDefinition(); // gradient if (def != null && def.createGradient) { return def.createGradient(svg.ctx, e); } // pattern if (def != null && def.createPattern) { return def.createPattern(svg.ctx, e); } return null; } } // length extensions this.Length = { DPI: function(viewPort) { return 96.0; // TODO: compute? }, EM: function(viewPort) { var em = 12; var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); if (fontSize.hasValue()) em = fontSize.Length.toPixels(viewPort); return em; }, // get the length as pixels toPixels: function(viewPort) { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/em$/)) return that.numValue() * this.EM(viewPort); if (s.match(/ex$/)) return that.numValue() * this.EM(viewPort) / 2.0; if (s.match(/px$/)) return that.numValue(); if (s.match(/pt$/)) return that.numValue() * 1.25; if (s.match(/pc$/)) return that.numValue() * 15; if (s.match(/cm$/)) return that.numValue() * this.DPI(viewPort) / 2.54; if (s.match(/mm$/)) return that.numValue() * this.DPI(viewPort) / 25.4; if (s.match(/in$/)) return that.numValue() * this.DPI(viewPort); if (s.match(/%$/)) return that.numValue() * svg.ViewPort.ComputeSize(viewPort); return that.numValue(); } } // time extensions this.Time = { // get the time as milliseconds toMilliseconds: function() { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/s$/)) return that.numValue() * 1000; if (s.match(/ms$/)) return that.numValue(); return that.numValue(); } } // angle extensions this.Angle = { // get the angle as radians toRadians: function() { if (!that.hasValue()) return 0; var s = that.value+''; if (s.match(/deg$/)) return that.numValue() * (Math.PI / 180.0); if (s.match(/grad$/)) return that.numValue() * (Math.PI / 200.0); if (s.match(/rad$/)) return that.numValue(); return that.numValue() * (Math.PI / 180.0); } } } // fonts svg.Font = new (function() { this.Styles = ['normal','italic','oblique','inherit']; this.Variants = ['normal','small-caps','inherit']; this.Weights = ['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','inherit']; this.CreateFont = function(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) { var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font); return { fontFamily: fontFamily || f.fontFamily, fontSize: fontSize || f.fontSize, fontStyle: fontStyle || f.fontStyle, fontWeight: fontWeight || f.fontWeight, fontVariant: fontVariant || f.fontVariant, toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') } } } var that = this; this.Parse = function(s) { var f = {}; var d = svg.trim(svg.compressSpaces(s || '')).split(' '); var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false } var ff = ''; for (var i=0; i<d.length; i++) { if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontStyle = d[i]; set.fontStyle = true; } else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true; } else if (!set.fontWeight && that.Weights.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontWeight = d[i]; set.fontStyle = set.fontVariant = set.fontWeight = true; } else if (!set.fontSize) { if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; } else { if (d[i] != 'inherit') ff += d[i]; } } if (ff != '') f.fontFamily = ff; return f; } }); // points and paths svg.ToNumberArray = function(s) { var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' '); for (var i=0; i<a.length; i++) { a[i] = parseFloat(a[i]); } return a; } svg.Point = function(x, y) { this.x = x; this.y = y; this.angleTo = function(p) { return Math.atan2(p.y - this.y, p.x - this.x); } this.applyTransform = function(v) { var xp = this.x * v[0] + this.y * v[2] + v[4]; var yp = this.x * v[1] + this.y * v[3] + v[5]; this.x = xp; this.y = yp; } } svg.CreatePoint = function(s) { var a = svg.ToNumberArray(s); return new svg.Point(a[0], a[1]); } svg.CreatePath = function(s) { var a = svg.ToNumberArray(s); var path = []; for (var i=0; i<a.length; i+=2) { path.push(new svg.Point(a[i], a[i+1])); } return path; } // bounding box svg.BoundingBox = function(x1, y1, x2, y2) { // pass in initial points if you want this.x1 = Number.NaN; this.y1 = Number.NaN; this.x2 = Number.NaN; this.y2 = Number.NaN; this.x = function() { return this.x1; } this.y = function() { return this.y1; } this.width = function() { return this.x2 - this.x1; } this.height = function() { return this.y2 - this.y1; } this.addPoint = function(x, y) { if (x != null) { if (isNaN(this.x1) || isNaN(this.x2)) { this.x1 = x; this.x2 = x; } if (x < this.x1) this.x1 = x; if (x > this.x2) this.x2 = x; } if (y != null) { if (isNaN(this.y1) || isNaN(this.y2)) { this.y1 = y; this.y2 = y; } if (y < this.y1) this.y1 = y; if (y > this.y2) this.y2 = y; } } this.addX = function(x) { this.addPoint(x, null); } this.addY = function(y) { this.addPoint(null, y); } this.addBoundingBox = function(bb) { this.addPoint(bb.x1, bb.y1); this.addPoint(bb.x2, bb.y2); } this.addQuadraticCurve = function(p0x, p0y, p1x, p1y, p2x, p2y) { var cp1x = p0x + 2/3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0) var cp1y = p0y + 2/3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0) var cp2x = cp1x + 1/3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0) var cp2y = cp1y + 1/3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0) this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y); } this.addBezierCurve = function(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) { // from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y]; this.addPoint(p0[0], p0[1]); this.addPoint(p3[0], p3[1]); for (i=0; i<=1; i++) { var f = function(t) { return Math.pow(1-t, 3) * p0[i] + 3 * Math.pow(1-t, 2) * t * p1[i] + 3 * (1-t) * Math.pow(t, 2) * p2[i] + Math.pow(t, 3) * p3[i]; } var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i]; var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i]; var c = 3 * p1[i] - 3 * p0[i]; if (a == 0) { if (b == 0) continue; var t = -c / b; if (0 < t && t < 1) { if (i == 0) this.addX(f(t)); if (i == 1) this.addY(f(t)); } continue; } var b2ac = Math.pow(b, 2) - 4 * c * a; if (b2ac < 0) continue; var t1 = (-b + Math.sqrt(b2ac)) / (2 * a); if (0 < t1 && t1 < 1) { if (i == 0) this.addX(f(t1)); if (i == 1) this.addY(f(t1)); } var t2 = (-b - Math.sqrt(b2ac)) / (2 * a); if (0 < t2 && t2 < 1) { if (i == 0) this.addX(f(t2)); if (i == 1) this.addY(f(t2)); } } } this.isPointInBox = function(x, y) { return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2); } this.addPoint(x1, y1); this.addPoint(x2, y2); } // transforms svg.Transform = function(v) { var that = this; this.Type = {} // translate this.Type.translate = function(s) { this.p = svg.CreatePoint(s); this.apply = function(ctx) { ctx.translate(this.p.x || 0.0, this.p.y || 0.0); } this.applyToPoint = function(p) { p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); } } // rotate this.Type.rotate = function(s) { var a = svg.ToNumberArray(s); this.angle = new svg.Property('angle', a[0]); this.cx = a[1] || 0; this.cy = a[2] || 0; this.apply = function(ctx) { ctx.translate(this.cx, this.cy); ctx.rotate(this.angle.Angle.toRadians()); ctx.translate(-this.cx, -this.cy); } this.applyToPoint = function(p) { var a = this.angle.Angle.toRadians(); p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]); p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]); p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]); } } this.Type.scale = function(s) { this.p = svg.CreatePoint(s); this.apply = function(ctx) { ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0); } this.applyToPoint = function(p) { p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]); } } this.Type.matrix = function(s) { this.m = svg.ToNumberArray(s); this.apply = function(ctx) { ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]); } this.applyToPoint = function(p) { p.applyTransform(this.m); } } this.Type.SkewBase = function(s) { this.base = that.Type.matrix; this.base(s); this.angle = new svg.Property('angle', s); } this.Type.SkewBase.prototype = new this.Type.matrix; this.Type.skewX = function(s) { this.base = that.Type.SkewBase; this.base(s); this.m = [1, 0, Math.tan(this.angle.Angle.toRadians()), 1, 0, 0]; } this.Type.skewX.prototype = new this.Type.SkewBase; this.Type.skewY = function(s) { this.base = that.Type.SkewBase; this.base(s); this.m = [1, Math.tan(this.angle.Angle.toRadians()), 0, 1, 0, 0]; } this.Type.skewY.prototype = new this.Type.SkewBase; this.transforms = []; this.apply = function(ctx) { for (var i=0; i<this.transforms.length; i++) { this.transforms[i].apply(ctx); } } this.applyToPoint = function(p) { for (var i=0; i<this.transforms.length; i++) { this.transforms[i].applyToPoint(p); } } var data = v.split(/\s(?=[a-z])/); for (var i=0; i<data.length; i++) { var type = data[i].split('(')[0]; var s = data[i].split('(')[1].replace(')',''); var transform = eval('new this.Type.' + type + '(s)'); this.transforms.push(transform); } } // aspect ratio svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) { // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute aspectRatio = svg.compressSpaces(aspectRatio); aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer var align = aspectRatio.split(' ')[0] || 'xMidYMid'; var meetOrSlice = aspectRatio.split(' ')[1] || 'meet'; // calculate scale var scaleX = width / desiredWidth; var scaleY = height / desiredHeight; var scaleMin = Math.min(scaleX, scaleY); var scaleMax = Math.max(scaleX, scaleY); if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; } if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; } refX = new svg.Property('refX', refX); refY = new svg.Property('refY', refY); if (refX.hasValue() && refY.hasValue()) { ctx.translate(-scaleMin * refX.Length.toPixels('x'), -scaleMin * refY.Length.toPixels('y')); } else { // align if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0); if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0); if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0); if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight); } // scale if (align == 'none') ctx.scale(scaleX, scaleY); else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin); else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax); // translate ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY); } // elements svg.Element = {} svg.Element.ElementBase = function(node) { this.attributes = {}; this.styles = {}; this.children = []; // get or create attribute this.attribute = function(name, createIfNotExists) { var a = this.attributes[name]; if (a != null) return a; a = new svg.Property(name, ''); if (createIfNotExists == true) this.attributes[name] = a; return a; } // get or create style this.style = function(name, createIfNotExists) { var s = this.styles[name]; if (s != null) return s; var a = this.attribute(name); if (a != null && a.hasValue()) { return a; } s = new svg.Property(name, ''); if (createIfNotExists == true) this.styles[name] = s; return s; } // base render this.render = function(ctx) { // don't render display=none if (this.attribute('display').value == 'none') return; ctx.save(); this.setContext(ctx); this.renderChildren(ctx); this.clearContext(ctx); ctx.restore(); } // base set context this.setContext = function(ctx) { // OVERRIDE ME! } // base clear context this.clearContext = function(ctx) { // OVERRIDE ME! } // base render children this.renderChildren = function(ctx) { for (var i=0; i<this.children.length; i++) { this.children[i].render(ctx); } } this.addChild = function(childNode, create) { var child = childNode; if (create) child = svg.CreateElement(childNode); child.parent = this; this.children.push(child); } if (node != null && node.nodeType == 1) { //ELEMENT_NODE // add children for (var i=0; i<node.childNodes.length; i++) { var childNode = node.childNodes[i]; if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE } // add attributes for (var i=0; i<node.attributes.length; i++) { var attribute = node.attributes[i]; this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue); } // add tag styles var styles = svg.Styles[this.type]; if (styles != null) { for (var name in styles) { this.styles[name] = styles[name]; } } // add class styles if (this.attribute('class').hasValue()) { var classes = svg.compressSpaces(this.attribute('class').value).split(' '); for (var j=0; j<classes.length; j++) { styles = svg.Styles['.'+classes[j]]; if (styles != null) { for (var name in styles) { this.styles[name] = styles[name]; } } } } // add inline styles if (this.attribute('style').hasValue()) { var styles = this.attribute('style').value.split(';'); for (var i=0; i<styles.length; i++) { if (svg.trim(styles[i]) != '') { var style = styles[i].split(':'); var name = svg.trim(style[0]); var value = svg.trim(style[1]); this.styles[name] = new svg.Property(name, value); } } } // add id if (this.attribute('id').hasValue()) { if (svg.Definitions[this.attribute('id').value] == null) { svg.Definitions[this.attribute('id').value] = this; } } } } svg.Element.RenderedElementBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.setContext = function(ctx) { // fill if (this.style('fill').Definition.isUrl()) { var fs = this.style('fill').Definition.getFillStyle(this); if (fs != null) ctx.fillStyle = fs; } else if (this.style('fill').hasValue()) { var fillStyle = this.style('fill'); if (this.style('fill-opacity').hasValue()) fillStyle = fillStyle.Color.addOpacity(this.style('fill-opacity').value); ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value); } // stroke if (this.style('stroke').Definition.isUrl()) { var fs = this.style('stroke').Definition.getFillStyle(this); if (fs != null) ctx.strokeStyle = fs; } else if (this.style('stroke').hasValue()) { var strokeStyle = this.style('stroke'); if (this.style('stroke-opacity').hasValue()) strokeStyle = strokeStyle.Color.addOpacity(this.style('stroke-opacity').value); ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value); } if (this.style('stroke-width').hasValue()) ctx.lineWidth = this.style('stroke-width').Length.toPixels(); if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value; if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value; if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value; // font if (typeof(ctx.font) != 'undefined') { ctx.font = svg.Font.CreateFont( this.style('font-style').value, this.style('font-variant').value, this.style('font-weight').value, this.style('font-size').hasValue() ? this.style('font-size').Length.toPixels() + 'px' : '', this.style('font-family').value).toString(); } // transform if (this.attribute('transform').hasValue()) { var transform = new svg.Transform(this.attribute('transform').value); transform.apply(ctx); } // clip if (this.attribute('clip-path').hasValue()) { var clip = this.attribute('clip-path').Definition.getDefinition(); if (clip != null) clip.apply(ctx); } // opacity if (this.style('opacity').hasValue()) { ctx.globalAlpha = this.style('opacity').numValue(); } } } svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase; svg.Element.PathElementBase = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.path = function(ctx) { if (ctx != null) ctx.beginPath(); return new svg.BoundingBox(); } this.renderChildren = function(ctx) { this.path(ctx); svg.Mouse.checkPath(this, ctx); if (ctx.fillStyle != '') ctx.fill(); if (ctx.strokeStyle != '') ctx.stroke(); var markers = this.getMarkers(); if (markers != null) { if (this.attribute('marker-start').Definition.isUrl()) { var marker = this.attribute('marker-start').Definition.getDefinition(); marker.render(ctx, markers[0][0], markers[0][1]); } if (this.attribute('marker-mid').Definition.isUrl()) { var marker = this.attribute('marker-mid').Definition.getDefinition(); for (var i=1;i<markers.length-1;i++) { marker.render(ctx, markers[i][0], markers[i][1]); } } if (this.attribute('marker-end').Definition.isUrl()) { var marker = this.attribute('marker-end').Definition.getDefinition(); marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]); } } } this.getBoundingBox = function() { return this.path(); } this.getMarkers = function() { return null; } } svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase; // svg element svg.Element.svg = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.baseClearContext = this.clearContext; this.clearContext = function(ctx) { this.baseClearContext(ctx); svg.ViewPort.RemoveCurrent(); } this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); // create new view port if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) { ctx.translate(this.attribute('x').Length.toPixels('x'), this.attribute('y').Length.toPixels('y')); } var width = svg.ViewPort.width(); var height = svg.ViewPort.height(); if (this.attribute('width').hasValue() && this.attribute('height').hasValue()) { width = this.attribute('width').Length.toPixels('x'); height = this.attribute('height').Length.toPixels('y'); var x = 0; var y = 0; if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) { x = -this.attribute('refX').Length.toPixels('x'); y = -this.attribute('refY').Length.toPixels('y'); } ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(width, y); ctx.lineTo(width, height); ctx.lineTo(x, height); ctx.closePath(); ctx.clip(); } svg.ViewPort.SetCurrent(width, height); // viewbox if (this.attribute('viewBox').hasValue()) { var viewBox = svg.ToNumberArray(this.attribute('viewBox').value); var minX = viewBox[0]; var minY = viewBox[1]; width = viewBox[2]; height = viewBox[3]; svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, svg.ViewPort.width(), width, svg.ViewPort.height(), height, minX, minY, this.attribute('refX').value, this.attribute('refY').value); svg.ViewPort.RemoveCurrent(); svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]); } // initial values ctx.strokeStyle = 'rgba(0,0,0,0)'; ctx.lineCap = 'butt'; ctx.lineJoin = 'miter'; ctx.miterLimit = 4; } } svg.Element.svg.prototype = new svg.Element.RenderedElementBase; // rect element svg.Element.rect = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); var rx = this.attribute('rx').Length.toPixels('x'); var ry = this.attribute('ry').Length.toPixels('y'); if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx; if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry; if (ctx != null) { ctx.beginPath(); ctx.moveTo(x + rx, y); ctx.lineTo(x + width - rx, y); ctx.quadraticCurveTo(x + width, y, x + width, y + ry) ctx.lineTo(x + width, y + height - ry); ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height) ctx.lineTo(x + rx, y + height); ctx.quadraticCurveTo(x, y + height, x, y + height - ry) ctx.lineTo(x, y + ry); ctx.quadraticCurveTo(x, y, x + rx, y) ctx.closePath(); } return new svg.BoundingBox(x, y, x + width, y + height); } } svg.Element.rect.prototype = new svg.Element.PathElementBase; // circle element svg.Element.circle = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var cx = this.attribute('cx').Length.toPixels('x'); var cy = this.attribute('cy').Length.toPixels('y'); var r = this.attribute('r').Length.toPixels(); if (ctx != null) { ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2, true); ctx.closePath(); } return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r); } } svg.Element.circle.prototype = new svg.Element.PathElementBase; // ellipse element svg.Element.ellipse = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.path = function(ctx) { var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3); var rx = this.attribute('rx').Length.toPixels('x'); var ry = this.attribute('ry').Length.toPixels('y'); var cx = this.attribute('cx').Length.toPixels('x'); var cy = this.attribute('cy').Length.toPixels('y'); if (ctx != null) { ctx.beginPath(); ctx.moveTo(cx, cy - ry); ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy); ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry); ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy); ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry); ctx.closePath(); } return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry); } } svg.Element.ellipse.prototype = new svg.Element.PathElementBase; // line element svg.Element.line = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.getPoints = function() { return [ new svg.Point(this.attribute('x1').Length.toPixels('x'), this.attribute('y1').Length.toPixels('y')), new svg.Point(this.attribute('x2').Length.toPixels('x'), this.attribute('y2').Length.toPixels('y'))]; } this.path = function(ctx) { var points = this.getPoints(); if (ctx != null) { ctx.beginPath(); ctx.moveTo(points[0].x, points[0].y); ctx.lineTo(points[1].x, points[1].y); } return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y); } this.getMarkers = function() { var points = this.getPoints(); var a = points[0].angleTo(points[1]); return [[points[0], a], [points[1], a]]; } } svg.Element.line.prototype = new svg.Element.PathElementBase; // polyline element svg.Element.polyline = function(node) { this.base = svg.Element.PathElementBase; this.base(node); this.points = svg.CreatePath(this.attribute('points').value); this.path = function(ctx) { var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y); if (ctx != null) { ctx.beginPath(); ctx.moveTo(this.points[0].x, this.points[0].y); } for (var i=1; i<this.points.length; i++) { bb.addPoint(this.points[i].x, this.points[i].y); if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y); } return bb; } this.getMarkers = function() { var markers = []; for (var i=0; i<this.points.length - 1; i++) { markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]); } markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]); return markers; } } svg.Element.polyline.prototype = new svg.Element.PathElementBase; // polygon element svg.Element.polygon = function(node) { this.base = svg.Element.polyline; this.base(node); this.basePath = this.path; this.path = function(ctx) { var bb = this.basePath(ctx); if (ctx != null) { ctx.lineTo(this.points[0].x, this.points[0].y); ctx.closePath(); } return bb; } } svg.Element.polygon.prototype = new svg.Element.polyline; // path element svg.Element.path = function(node) { this.base = svg.Element.PathElementBase; this.base(node); var d = this.attribute('d').value; // TODO: floating points, convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF d = d.replace(/,/gm,' '); // get rid of all commas d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,'$1 $2'); // separate commands from points d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from points d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits when no comma d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when no comma d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax d = svg.compressSpaces(d); // compress multiple spaces d = svg.trim(d); this.PathParser = new (function(d) { this.tokens = d.split(' '); this.reset = function() { this.i = -1; this.command = ''; this.previousCommand = ''; this.start = new svg.Point(0, 0); this.control = new svg.Point(0, 0); this.current = new svg.Point(0, 0); this.points = []; this.angles = []; } this.isEnd = function() { return this.i >= this.tokens.length - 1; } this.isCommandOrEnd = function() { if (this.isEnd()) return true; return this.tokens[this.i + 1].match(/[A-Za-z]/) != null; } this.isRelativeCommand = function() { return this.command == this.command.toLowerCase(); } this.getToken = function() { this.i = this.i + 1; return this.tokens[this.i]; } this.getScalar = function() { return parseFloat(this.getToken()); } this.nextCommand = function() { this.previousCommand = this.command; this.command = this.getToken(); } this.getPoint = function() { var p = new svg.Point(this.getScalar(), this.getScalar()); return this.makeAbsolute(p); } this.getAsControlPoint = function() { var p = this.getPoint(); this.control = p; return p; } this.getAsCurrentPoint = function() { var p = this.getPoint(); this.current = p; return p; } this.getReflectedControlPoint = function() { if (this.previousCommand.toLowerCase() != 'c' && this.previousCommand.toLowerCase() != 's') { return this.current; } // reflect point var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y); return p; } this.makeAbsolute = function(p) { if (this.isRelativeCommand()) { p.x = this.current.x + p.x; p.y = this.current.y + p.y; } return p; } this.addMarker = function(p, from) { this.addMarkerAngle(p, from == null ? null : from.angleTo(p)); } this.addMarkerAngle = function(p, a) { this.points.push(p); this.angles.push(a); } this.getMarkerPoints = function() { return this.points; } this.getMarkerAngles = function() { for (var i=0; i<this.angles.length; i++) { if (this.angles[i] == null) { for (var j=i+1; j<this.angles.length; j++) { if (this.angles[j] != null) { this.angles[i] = this.angles[j]; break; } } } } return this.angles; } })(d); this.path = function(ctx) { var pp = this.PathParser; pp.reset(); var bb = new svg.BoundingBox(); if (ctx != null) ctx.beginPath(); while (!pp.isEnd()) { pp.nextCommand(); switch (pp.command.toUpperCase()) { case 'M': var p = pp.getAsCurrentPoint(); pp.addMarker(p); bb.addPoint(p.x, p.y); if (ctx != null) ctx.moveTo(p.x, p.y); pp.start = pp.current; while (!pp.isCommandOrEnd()) { var p = pp.getAsCurrentPoint(); pp.addMarker(p); bb.addPoint(p.x, p.y); if (ctx != null) ctx.lineTo(p.x, p.y); } break; case 'L': while (!pp.isCommandOrEnd()) { var c = pp.current; var p = pp.getAsCurrentPoint(); pp.addMarker(p, c); bb.addPoint(p.x, p.y); if (ctx != null) ctx.lineTo(p.x, p.y); } break; case 'H': while (!pp.isCommandOrEnd()) { var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y); pp.addMarker(newP, pp.current); pp.current = newP; bb.addPoint(pp.current.x, pp.current.y); if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y); } break; case 'V': while (!pp.isCommandOrEnd()) { var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar()); pp.addMarker(newP, pp.current); pp.current = newP; bb.addPoint(pp.current.x, pp.current.y); if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y); } break; case 'C': while (!pp.isCommandOrEnd()) { var curr = pp.current; var p1 = pp.getPoint(); var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl); bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'S': while (!pp.isCommandOrEnd()) { var curr = pp.current; var p1 = pp.getReflectedControlPoint(); var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl); bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'Q': while (!pp.isCommandOrEnd()) { var curr = pp.current; var cntrl = pp.getAsControlPoint(); var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl); bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'T': while (!pp.isCommandOrEnd()) { var curr = pp.current; var cntrl = pp.getReflectedControlPoint(); pp.control = cntrl; var cp = pp.getAsCurrentPoint(); pp.addMarker(cp, cntrl); bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y); if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y); } break; case 'A': while (!pp.isCommandOrEnd()) { var curr = pp.current; var rx = pp.getScalar(); var ry = pp.getScalar(); var xAxisRotation = pp.getScalar() * (Math.PI / 180.0); var largeArcFlag = pp.getScalar(); var sweepFlag = pp.getScalar(); var cp = pp.getAsCurrentPoint(); // Conversion from endpoint to center parameterization // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes // x1', y1' var currp = new svg.Point( Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0, -Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0 ); // adjust radii var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2); if (l > 1) { rx *= Math.sqrt(l); ry *= Math.sqrt(l); } // cx', cy' var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt( ((Math.pow(rx,2)*Math.pow(ry,2))-(Math.pow(rx,2)*Math.pow(currp.y,2))-(Math.pow(ry,2)*Math.pow(currp.x,2))) / (Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2)) ); if (isNaN(s)) s = 0; var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx); // cx, cy var centp = new svg.Point( (curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y, (curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y ); // vector magnitude var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); } // ratio between two vectors var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) } // angle between two vectors var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); } // initial angle var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]); // angle delta var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]; var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry]; var ad = a(u, v); if (r(u,v) <= -1) ad = Math.PI; if (r(u,v) >= 1) ad = 0; if (sweepFlag == 0 && ad > 0) ad = ad - 2 * Math.PI; if (sweepFlag == 1 && ad < 0) ad = ad + 2 * Math.PI; // for markers var halfWay = new svg.Point( centp.x - rx * Math.cos((a1 + ad) / 2), centp.y - ry * Math.sin((a1 + ad) / 2) ); pp.addMarkerAngle(halfWay, (a1 + ad) / 2 + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2); pp.addMarkerAngle(cp, ad + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2); bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better if (ctx != null) { var r = rx > ry ? rx : ry; var sx = rx > ry ? 1 : rx / ry; var sy = rx > ry ? ry / rx : 1; ctx.translate(centp.x, centp.y); ctx.rotate(xAxisRotation); ctx.scale(sx, sy); ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag); ctx.scale(1/sx, 1/sy); ctx.rotate(-xAxisRotation); ctx.translate(-centp.x, -centp.y); } } break; case 'Z': if (ctx != null) ctx.closePath(); pp.current = pp.start; } } return bb; } this.getMarkers = function() { var points = this.PathParser.getMarkerPoints(); var angles = this.PathParser.getMarkerAngles(); var markers = []; for (var i=0; i<points.length; i++) { markers.push([points[i], angles[i]]); } return markers; } } svg.Element.path.prototype = new svg.Element.PathElementBase; // pattern element svg.Element.pattern = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.createPattern = function(ctx, element) { // render me using a temporary svg element var tempSvg = new svg.Element.svg(); tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value); tempSvg.attributes['x'] = new svg.Property('x', this.attribute('x').value); tempSvg.attributes['y'] = new svg.Property('y', this.attribute('y').value); tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value); tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value); tempSvg.children = this.children; var c = document.createElement('canvas'); c.width = this.attribute('width').Length.toPixels(); c.height = this.attribute('height').Length.toPixels(); tempSvg.render(c.getContext('2d')); return ctx.createPattern(c, 'repeat'); } } svg.Element.pattern.prototype = new svg.Element.ElementBase; // marker element svg.Element.marker = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.baseRender = this.render; this.render = function(ctx, point, angle) { ctx.translate(point.x, point.y); if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle); if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth); ctx.save(); // render me using a temporary svg element var tempSvg = new svg.Element.svg(); tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value); tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value); tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value); tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value); tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value); tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black')); tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none')); tempSvg.children = this.children; tempSvg.render(ctx); ctx.restore(); if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth); if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle); ctx.translate(-point.x, -point.y); } } svg.Element.marker.prototype = new svg.Element.ElementBase; // definitions element svg.Element.defs = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.render = function(ctx) { // NOOP } } svg.Element.defs.prototype = new svg.Element.ElementBase; // base for gradients svg.Element.GradientBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox'); this.stops = []; for (var i=0; i<this.children.length; i++) { var child = this.children[i]; this.stops.push(child); } this.getGradient = function() { // OVERRIDE ME! } this.createGradient = function(ctx, element) { var stopsContainer = this; if (this.attribute('xlink:href').hasValue()) { stopsContainer = this.attribute('xlink:href').Definition.getDefinition(); } var g = this.getGradient(ctx, element); for (var i=0; i<stopsContainer.stops.length; i++) { g.addColorStop(stopsContainer.stops[i].offset, stopsContainer.stops[i].color); } return g; } } svg.Element.GradientBase.prototype = new svg.Element.ElementBase; // linear gradient element svg.Element.linearGradient = function(node) { this.base = svg.Element.GradientBase; this.base(node); this.getGradient = function(ctx, element) { var bb = element.getBoundingBox(); var x1 = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('x1').numValue() : this.attribute('x1').Length.toPixels('x')); var y1 = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('y1').numValue() : this.attribute('y1').Length.toPixels('y')); var x2 = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('x2').numValue() : this.attribute('x2').Length.toPixels('x')); var y2 = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('y2').numValue() : this.attribute('y2').Length.toPixels('y')); var p1 = new svg.Point(x1, y1); var p2 = new svg.Point(x2, y2); if (this.attribute('gradientTransform').hasValue()) { var transform = new svg.Transform(this.attribute('gradientTransform').value); transform.applyToPoint(p1); transform.applyToPoint(p2); } return ctx.createLinearGradient(p1.x, p1.y, p2.x, p2.y); } } svg.Element.linearGradient.prototype = new svg.Element.GradientBase; // radial gradient element svg.Element.radialGradient = function(node) { this.base = svg.Element.GradientBase; this.base(node); this.getGradient = function(ctx, element) { var bb = element.getBoundingBox(); var cx = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('cx').numValue() : this.attribute('cx').Length.toPixels('x')); var cy = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('cy').numValue() : this.attribute('cy').Length.toPixels('y')); var fx = cx; var fy = cy; if (this.attribute('fx').hasValue()) { fx = (this.gradientUnits == 'objectBoundingBox' ? bb.x() + bb.width() * this.attribute('fx').numValue() : this.attribute('fx').Length.toPixels('x')); } if (this.attribute('fy').hasValue()) { fy = (this.gradientUnits == 'objectBoundingBox' ? bb.y() + bb.height() * this.attribute('fy').numValue() : this.attribute('fy').Length.toPixels('y')); } var r = (this.gradientUnits == 'objectBoundingBox' ? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue() : this.attribute('r').Length.toPixels()); var c = new svg.Point(cx, cy); var f = new svg.Point(fx, fy); if (this.attribute('gradientTransform').hasValue()) { var transform = new svg.Transform(this.attribute('gradientTransform').value); transform.applyToPoint(c); transform.applyToPoint(f); } return ctx.createRadialGradient(f.x, f.y, 0, c.x, c.y, r); } } svg.Element.radialGradient.prototype = new svg.Element.GradientBase; // gradient stop element svg.Element.stop = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.offset = this.attribute('offset').numValue(); var stopColor = this.style('stop-color'); if (this.style('stop-opacity').hasValue()) stopColor = stopColor.Color.addOpacity(this.style('stop-opacity').value); this.color = stopColor.value; } svg.Element.stop.prototype = new svg.Element.ElementBase; // animation base element svg.Element.AnimateBase = function(node) { this.base = svg.Element.ElementBase; this.base(node); svg.Animations.push(this); this.duration = 0.0; this.begin = this.attribute('begin').Time.toMilliseconds(); this.maxDuration = this.begin + this.attribute('dur').Time.toMilliseconds(); this.getProperty = function() { var attributeType = this.attribute('attributeType').value; var attributeName = this.attribute('attributeName').value; if (attributeType == 'CSS') { return this.parent.style(attributeName, true); } return this.parent.attribute(attributeName, true); }; this.initialValue = null; this.removed = false; this.calcValue = function() { // OVERRIDE ME! return ''; } this.update = function(delta) { // set initial value if (this.initialValue == null) { this.initialValue = this.getProperty().value; } // if we're past the end time if (this.duration > this.maxDuration) { // loop for indefinitely repeating animations if (this.attribute('repeatCount').value == 'indefinite') { this.duration = 0.0 } else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) { this.removed = true; this.getProperty().value = this.initialValue; return true; } else { return false; // no updates made } } this.duration = this.duration + delta; // if we're past the begin time var updated = false; if (this.begin < this.duration) { var newValue = this.calcValue(); // tween if (this.attribute('type').hasValue()) { // for transform, etc. var type = this.attribute('type').value; newValue = type + '(' + newValue + ')'; } this.getProperty().value = newValue; updated = true; } return updated; } // fraction of duration we've covered this.progress = function() { return ((this.duration - this.begin) / (this.maxDuration - this.begin)); } } svg.Element.AnimateBase.prototype = new svg.Element.ElementBase; // animate element svg.Element.animate = function(node) { this.base = svg.Element.AnimateBase; this.base(node); this.calcValue = function() { var from = this.attribute('from').numValue(); var to = this.attribute('to').numValue(); // tween value linearly return from + (to - from) * this.progress(); }; } svg.Element.animate.prototype = new svg.Element.AnimateBase; // animate color element svg.Element.animateColor = function(node) { this.base = svg.Element.AnimateBase; this.base(node); this.calcValue = function() { var from = new RGBColor(this.attribute('from').value); var to = new RGBColor(this.attribute('to').value); if (from.ok && to.ok) { // tween color linearly var r = from.r + (to.r - from.r) * this.progress(); var g = from.g + (to.g - from.g) * this.progress(); var b = from.b + (to.b - from.b) * this.progress(); return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')'; } return this.attribute('from').value; }; } svg.Element.animateColor.prototype = new svg.Element.AnimateBase; // animate transform element svg.Element.animateTransform = function(node) { this.base = svg.Element.animate; this.base(node); } svg.Element.animateTransform.prototype = new svg.Element.animate; // text element svg.Element.text = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); if (node != null) { // add children this.children = []; for (var i=0; i<node.childNodes.length; i++) { var childNode = node.childNodes[i]; if (childNode.nodeType == 1) { // capture tspan and tref nodes this.addChild(childNode, true); } else if (childNode.nodeType == 3) { // capture text this.addChild(new svg.Element.tspan(childNode), false); } } } this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); if (this.attribute('text-anchor').hasValue()) { var textAnchor = this.attribute('text-anchor').value; ctx.textAlign = textAnchor == 'middle' ? 'center' : textAnchor; } if (this.attribute('alignment-baseline').hasValue()) ctx.textBaseline = this.attribute('alignment-baseline').value; } this.renderChildren = function(ctx) { var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); for (var i=0; i<this.children.length; i++) { var child = this.children[i]; if (child.attribute('x').hasValue()) { child.x = child.attribute('x').Length.toPixels('x'); } else { if (child.attribute('dx').hasValue()) x += child.attribute('dx').Length.toPixels('x'); child.x = x; x += child.measureText(ctx); } if (child.attribute('y').hasValue()) { child.y = child.attribute('y').Length.toPixels('y'); } else { if (child.attribute('dy').hasValue()) y += child.attribute('dy').Length.toPixels('y'); child.y = y; } child.render(ctx); } } } svg.Element.text.prototype = new svg.Element.RenderedElementBase; // text base svg.Element.TextElementBase = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.renderChildren = function(ctx) { ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y); } this.getText = function() { // OVERRIDE ME } this.measureText = function(ctx) { var textToMeasure = svg.compressSpaces(this.getText()); if (!ctx.measureText) return textToMeasure.length * 10; return ctx.measureText(textToMeasure).width; } } svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase; // tspan svg.Element.tspan = function(node) { this.base = svg.Element.TextElementBase; this.base(node); // TEXT ELEMENT this.text = node.nodeType == 3 ? node.nodeValue : node.childNodes[0].nodeValue; this.getText = function() { return this.text; } } svg.Element.tspan.prototype = new svg.Element.TextElementBase; // tref svg.Element.tref = function(node) { this.base = svg.Element.TextElementBase; this.base(node); this.getText = function() { var element = this.attribute('xlink:href').Definition.getDefinition(); if (element != null) return element.children[0].getText(); } } svg.Element.tref.prototype = new svg.Element.TextElementBase; // a element svg.Element.a = function(node) { this.base = svg.Element.TextElementBase; this.base(node); this.hasText = true; for (var i=0; i<node.childNodes.length; i++) { if (node.childNodes[i].nodeType != 3) this.hasText = false; } // this might contain text this.text = this.hasText ? node.childNodes[0].nodeValue : ''; this.getText = function() { return this.text; } this.baseRenderChildren = this.renderChildren; this.renderChildren = function(ctx) { if (this.hasText) { // render as text element this.baseRenderChildren(ctx); var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize); svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.Length.toPixels('y'), this.x + this.measureText(ctx), this.y)); } else { // render as temporary group var g = new svg.Element.g(); g.children = this.children; g.parent = this; g.render(ctx); } } this.onclick = function() { window.open(this.attribute('xlink:href').value); } this.onmousemove = function() { svg.ctx.canvas.style.cursor = 'pointer'; } } svg.Element.a.prototype = new svg.Element.TextElementBase; // image element svg.Element.image = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); svg.Images.push(this); this.img = document.createElement('img'); this.loaded = false; var that = this; this.img.onload = function() { that.loaded = true; } this.img.src = this.attribute('xlink:href').value; this.renderChildren = function(ctx) { var x = this.attribute('x').Length.toPixels('x'); var y = this.attribute('y').Length.toPixels('y'); var width = this.attribute('width').Length.toPixels('x'); var height = this.attribute('height').Length.toPixels('y'); if (width == 0 || height == 0) return; ctx.save(); ctx.translate(x, y); svg.AspectRatio(ctx, this.attribute('preserveAspectRatio').value, width, this.img.width, height, this.img.height, 0, 0); ctx.drawImage(this.img, 0, 0); ctx.restore(); } } svg.Element.image.prototype = new svg.Element.RenderedElementBase; // group element svg.Element.g = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.getBoundingBox = function() { var bb = new svg.BoundingBox(); for (var i=0; i<this.children.length; i++) { bb.addBoundingBox(this.children[i].getBoundingBox()); } return bb; }; } svg.Element.g.prototype = new svg.Element.RenderedElementBase; // symbol element svg.Element.symbol = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); } svg.Element.symbol.prototype = new svg.Element.RenderedElementBase; // style element svg.Element.style = function(node) { this.base = svg.Element.ElementBase; this.base(node); var css = node.childNodes[0].nodeValue; css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(\/\/.*)/gm, ''); // remove comments css = svg.compressSpaces(css); // replace whitespace var cssDefs = css.split('}'); for (var i=0; i<cssDefs.length; i++) { if (svg.trim(cssDefs[i]) != '') { var cssDef = cssDefs[i].split('{'); var cssClasses = cssDef[0].split(','); var cssProps = cssDef[1].split(';'); for (var j=0; j<cssClasses.length; j++) { var cssClass = svg.trim(cssClasses[j]); if (cssClass != '') { var props = {}; for (var k=0; k<cssProps.length; k++) { var prop = cssProps[k].split(':'); var name = prop[0]; var value = prop[1]; if (name != null && value != null) { props[svg.trim(prop[0])] = new svg.Property(svg.trim(prop[0]), svg.trim(prop[1])); } } svg.Styles[cssClass] = props; } } } } } svg.Element.style.prototype = new svg.Element.ElementBase; // use element svg.Element.use = function(node) { this.base = svg.Element.RenderedElementBase; this.base(node); this.baseSetContext = this.setContext; this.setContext = function(ctx) { this.baseSetContext(ctx); if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').Length.toPixels('x'), 0); if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').Length.toPixels('y')); } this.getDefinition = function() { return this.attribute('xlink:href').Definition.getDefinition(); } this.path = function(ctx) { var element = this.getDefinition(); if (element != null) element.path(ctx); } this.renderChildren = function(ctx) { var element = this.getDefinition(); if (element != null) element.render(ctx); } } svg.Element.use.prototype = new svg.Element.RenderedElementBase; // clip element svg.Element.clipPath = function(node) { this.base = svg.Element.ElementBase; this.base(node); this.apply = function(ctx) { for (var i=0; i<this.children.length; i++) { if (this.children[i].path) { this.children[i].path(ctx); ctx.clip(); } } } } svg.Element.clipPath.prototype = new svg.Element.ElementBase; // title element, do nothing svg.Element.title = function(node) { } svg.Element.title.prototype = new svg.Element.ElementBase; // desc element, do nothing svg.Element.desc = function(node) { } svg.Element.desc.prototype = new svg.Element.ElementBase; svg.Element.MISSING = function(node) { console.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.'); } svg.Element.MISSING.prototype = new svg.Element.ElementBase; // element factory svg.CreateElement = function(node) { var className = 'svg.Element.' + node.nodeName.replace(/^[^:]+:/,''); if (!eval(className)) className = 'svg.Element.MISSING'; var e = eval('new ' + className + '(node)'); e.type = node.nodeName; return e; } // load from url svg.load = function(ctx, url) { svg.loadXml(ctx, svg.ajax(url)); } // load from xml svg.loadXml = function(ctx, xml) { svg.init(ctx); var mapXY = function(p) { var e = ctx.canvas; while (e) { p.x -= e.offsetLeft; p.y -= e.offsetTop; e = e.offsetParent; } if (window.scrollX) p.x += window.scrollX; if (window.scrollY) p.y += window.scrollY; return p; } // bind mouse if (svg.opts == null || svg.opts['ignoreMouse'] != true) { ctx.canvas.onclick = function(e) { var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY)); svg.Mouse.onclick(p.x, p.y); }; ctx.canvas.onmousemove = function(e) { var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY)); svg.Mouse.onmousemove(p.x, p.y); }; } var dom = svg.parseXml(xml); var e = svg.CreateElement(dom.documentElement); // render loop var isFirstRender = true; var draw = function() { if (svg.opts == null || svg.opts['ignoreDimensions'] != true) { // set canvas size if (e.style('width').hasValue()) { ctx.canvas.width = e.style('width').Length.toPixels(ctx.canvas.parentNode.clientWidth); } if (e.style('height').hasValue()) { ctx.canvas.height = e.style('height').Length.toPixels(ctx.canvas.parentNode.clientHeight); } } svg.ViewPort.SetCurrent(ctx.canvas.clientWidth, ctx.canvas.clientHeight); if (svg.opts != null && svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX']; if (svg.opts != null && svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY']; if (svg.opts != null && svg.opts['scaleWidth'] != null && svg.opts['scaleHeight'] != null) { e.attribute('width', true).value = svg.opts['scaleWidth']; e.attribute('height', true).value = svg.opts['scaleHeight']; // REMOVED FOR android-ui-utils // e.attribute('viewBox', true).value = '0 0 ' + ctx.canvas.clientWidth + ' ' + ctx.canvas.clientHeight; e.attribute('preserveAspectRatio', true).value = 'none'; } // clear and render if (svg.opts == null || svg.opts['ignoreClear'] != true) { ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight); } e.render(ctx); if (isFirstRender) { isFirstRender = false; if (svg.opts != null && typeof(svg.opts['renderCallback']) == 'function') svg.opts['renderCallback'](); } } var waitingForImages = true; if (svg.ImagesLoaded()) { waitingForImages = false; draw(); } svg.intervalID = setInterval(function() { var needUpdate = false; if (waitingForImages && svg.ImagesLoaded()) { waitingForImages = false; needUpdate = true; } // need update from mouse events? if (svg.opts == null || svg.opts['ignoreMouse'] != true) { needUpdate = needUpdate | svg.Mouse.hasEvents(); } // need update from animations? if (svg.opts == null || svg.opts['ignoreAnimation'] != true) { for (var i=0; i<svg.Animations.length; i++) { needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE); } } // need update from redraw? if (svg.opts != null && typeof(svg.opts['forceRedraw']) == 'function') { if (svg.opts['forceRedraw']() == true) needUpdate = true; } // render if needed if (needUpdate) { draw(); svg.Mouse.runEvents(); // run and clear our events } }, 1000 / svg.FRAMERATE); } svg.stop = function() { if (svg.intervalID) { clearInterval(svg.intervalID); } } svg.Mouse = new (function() { this.events = []; this.hasEvents = function() { return this.events.length != 0; } this.onclick = function(x, y) { this.events.push({ type: 'onclick', x: x, y: y, run: function(e) { if (e.onclick) e.onclick(); } }); } this.onmousemove = function(x, y) { this.events.push({ type: 'onmousemove', x: x, y: y, run: function(e) { if (e.onmousemove) e.onmousemove(); } }); } this.eventElements = []; this.checkPath = function(element, ctx) { for (var i=0; i<this.events.length; i++) { var e = this.events[i]; if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element; } } this.checkBoundingBox = function(element, bb) { for (var i=0; i<this.events.length; i++) { var e = this.events[i]; if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element; } } this.runEvents = function() { svg.ctx.canvas.style.cursor = ''; for (var i=0; i<this.events.length; i++) { var e = this.events[i]; var element = this.eventElements[i]; while (element) { e.run(element); element = element.parent; } } // done running, clear this.events = []; this.eventElements = []; } }); return svg; } })(); if (CanvasRenderingContext2D) { CanvasRenderingContext2D.prototype.drawSvg = function(s, dx, dy, dw, dh) { canvg(this.canvas, s, { ignoreMouse: true, ignoreAnimation: true, ignoreDimensions: true, ignoreClear: true, offsetX: dx, offsetY: dy, scaleWidth: dw, scaleHeight: dh }); } }
JavaScript
/* Downloadify: Client Side File Creation JavaScript + Flash Library Version: 0.2 Copyright (c) 2009 Douglas C. Neiner Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function(){ Downloadify = window.Downloadify = { queue: {}, uid: new Date().getTime(), getTextForSave: function(queue){ var obj = Downloadify.queue[queue]; if(obj) return obj.getData(); return ""; }, getFileNameForSave: function(queue){ var obj = Downloadify.queue[queue]; if(obj) return obj.getFilename(); return ""; }, getDataTypeForSave: function(queue){ var obj = Downloadify.queue[queue]; if(obj) return obj.getDataType(); return ""; }, saveComplete: function(queue){ var obj = Downloadify.queue[queue]; if(obj) obj.complete(); return true; }, saveCancel: function(queue){ var obj = Downloadify.queue[queue]; if(obj) obj.cancel(); return true; }, saveError: function(queue){ var obj = Downloadify.queue[queue]; if(obj) obj.error(); return true; }, addToQueue: function(container){ Downloadify.queue[container.queue_name] = container; }, // Concept adapted from: http://tinyurl.com/yzsyfto // SWF object runs off of ID's, so this is the good way to get a unique ID getUID: function(el){ if(el.id == "") el.id = 'downloadify_' + Downloadify.uid++; return el.id; } }; Downloadify.create = function( idOrDOM, options ){ var el = (typeof(idOrDOM) == "string" ? document.getElementById(idOrDOM) : idOrDOM ); return new Downloadify.Container(el, options); }; Downloadify.Container = function(el, options){ var base = this; base.el = el; base.enabled = true; base.dataCallback = null; base.filenameCallback = null; base.data = null; base.filename = null; var init = function(){ base.options = options; if( !base.options.append ) base.el.innerHTML = ""; base.flashContainer = document.createElement('span'); base.el.appendChild(base.flashContainer); base.queue_name = Downloadify.getUID( base.flashContainer ); if( typeof(base.options.filename) === "function" ) base.filenameCallback = base.options.filename; else if (base.options.filename) base.filename = base.options.filename; if( typeof(base.options.data) === "function" ) base.dataCallback = base.options.data; else if (base.options.data) base.data = base.options.data; var flashVars = { queue_name: base.queue_name, width: base.options.width, height: base.options.height }; var params = { allowScriptAccess: 'always' }; var attributes = { id: base.flashContainer.id, name: base.flashContainer.id }; if(base.options.enabled === false) base.enabled = false; if(base.options.transparent === true) params.wmode = "transparent"; if(base.options.downloadImage) flashVars.downloadImage = base.options.downloadImage; swfobject.embedSWF(base.options.swf, base.flashContainer.id, base.options.width, base.options.height, "10", null, flashVars, params, attributes ); Downloadify.addToQueue( base ); }; base.enable = function(){ var swf = document.getElementById(base.flashContainer.id); swf.setEnabled(true); base.enabled = true; }; base.disable = function(){ var swf = document.getElementById(base.flashContainer.id); swf.setEnabled(false); base.enabled = false; }; base.getData = function(){ if( !base.enabled ) return ""; if( base.dataCallback ) return base.dataCallback(); else if (base.data) return base.data; else return ""; }; base.getFilename = function(){ if( base.filenameCallback ) return base.filenameCallback(); else if (base.filename) return base.filename; else return ""; }; base.getDataType = function(){ if (base.options.dataType) return base.options.dataType; return "string"; }; base.complete = function(){ if( typeof(base.options.onComplete) === "function" ) base.options.onComplete(); }; base.cancel = function(){ if( typeof(base.options.onCancel) === "function" ) base.options.onCancel(); }; base.error = function(){ if( typeof(base.options.onError) === "function" ) base.options.onError(); }; init(); }; Downloadify.defaultOptions = { swf: 'media/downloadify.swf', downloadImage: 'images/download.png', width: 100, height: 30, transparent: true, append: false, dataType: "string" }; })(); // Support for jQuery if(typeof(jQuery) != "undefined"){ (function($){ $.fn.downloadify = function(options){ return this.each(function(){ options = $.extend({}, Downloadify.defaultOptions, options); var dl = Downloadify.create( this, options); $(this).data('Downloadify', dl); }); }; })(jQuery); }; /* mootools helper */ if(typeof(MooTools) != 'undefined'){ Element.implement({ downloadify: function(options) { options = $extend(Downloadify.defaultOptions,options); return this.store('Downloadify',Downloadify.create(this,options)); } }); };
JavaScript